diff --git a/build.gradle b/build.gradle index 678d5aec94..0cd360d898 100644 --- a/build.gradle +++ b/build.gradle @@ -296,6 +296,8 @@ project(':forge') { workingDirectory project.file('run') environment 'target', 'fmldevdata' + environment 'assetIndex', '{asset_index}' + environment 'assetDirectory', downloadAssets.output environment 'MC_VERSION', MC_VERSION environment 'MCP_VERSION', MCP_VERSION diff --git a/patches/minecraft/net/minecraft/data/Main.java.patch b/patches/minecraft/net/minecraft/data/Main.java.patch index 4b010f38d7..44642ad784 100644 --- a/patches/minecraft/net/minecraft/data/Main.java.patch +++ b/patches/minecraft/net/minecraft/data/Main.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/Main.java +++ b/net/minecraft/data/Main.java -@@ -21,8 +_,13 @@ +@@ -21,8 +_,15 @@ OptionSpec optionspec6 = optionparser.accepts("all", "Include all generators"); OptionSpec optionspec7 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); OptionSpec optionspec8 = optionparser.accepts("input", "Input folder").withRequiredArg(); @@ -9,6 +9,8 @@ + OptionSpec gameDir = optionparser.accepts("gameDir").withRequiredArg().ofType(java.io.File.class).defaultsTo(new java.io.File(".")).required(); //Need by modlauncher, so lets just eat it + OptionSpec mod = optionparser.accepts("mod", "A modid to dump").withRequiredArg().withValuesSeparatedBy(","); + OptionSpec flat = optionparser.accepts("flat", "Do not append modid prefix to output directory when generating for multiple mods"); ++ OptionSpec assetIndex = optionparser.accepts("assetIndex").withRequiredArg(); ++ OptionSpec assetsDir = optionparser.accepts("assetsDir").withRequiredArg().ofType(java.io.File.class); OptionSet optionset = optionparser.parse(p_main_0_); - if (!optionset.has(optionspec) && optionset.hasOptions()) { + if (!optionset.has(optionspec) && optionset.hasOptions() && !(optionset.specs().size() == 1 && optionset.has(gameDir))) { @@ -28,7 +30,7 @@ + java.util.Set existingMods = new java.util.HashSet<>(optionset.valuesOf(existingMod)); + java.util.Set mods = new java.util.HashSet<>(optionset.valuesOf(mod)); + boolean isFlat = mods.isEmpty() || optionset.has(flat); -+ net.minecraftforge.fml.DatagenModLoader.begin(mods, path, inputs, existingPacks, existingMods, flag2, flag1, flag3, flag4, flag5, isFlat); ++ net.minecraftforge.fml.DatagenModLoader.begin(mods, path, inputs, existingPacks, existingMods, flag2, flag1, flag3, flag4, flag5, isFlat, optionset.valueOf(assetIndex), optionset.valueOf(assetsDir)); + if (mods.contains("minecraft") || mods.isEmpty()) + func_200264_a(isFlat ? path : path.resolve("minecraft"), inputs, flag1, flag2, flag3, flag4, flag5).func_200392_c(); } else { diff --git a/src/generated_test/resources/.cache/cache b/src/generated_test/resources/.cache/cache index 8343d95d7a..987d9824b2 100644 --- a/src/generated_test/resources/.cache/cache +++ b/src/generated_test/resources/.cache/cache @@ -49,6 +49,7 @@ db2cd929128c8a6e8e0b02437f90ad8d24238206 assets/data_gen_test/models/block/torch 098d8b38409fff6cc14a4e56355bedb1fc5931d1 assets/data_gen_test/models/item/test_block.json b029993275f16569b0edf093362f55df6ea6f9be assets/data_gen_test/models/item/test_block_model.json 726e1884e53151492ca05bd752c67031603570f6 assets/data_gen_test/models/item/test_generated_model.json +61e57e44de5506da3937499a4fe46f84b856ba52 assets/data_gen_test/sounds.json 1767c874758bd7c3235db446b6219e6e1edd25b4 assets/minecraft/blockstates/acacia_door.json e41383b4c13ec922c0f5cfa2cc313d88fd294685 assets/minecraft/blockstates/acacia_fence.json 967d268bfcf32474b61578bef16e853b6360dd73 assets/minecraft/blockstates/acacia_fence_gate.json diff --git a/src/generated_test/resources/assets/data_gen_test/sounds.json b/src/generated_test/resources/assets/data_gen_test/sounds.json new file mode 100644 index 0000000000..f8600f648c --- /dev/null +++ b/src/generated_test/resources/assets/data_gen_test/sounds.json @@ -0,0 +1,125 @@ +{ + "ambient.underwater.loop.additions": { + "sounds": [ + "ambient/underwater/additions/bubbles1", + "ambient/underwater/additions/bubbles2", + "ambient/underwater/additions/bubbles3", + "ambient/underwater/additions/bubbles4", + "ambient/underwater/additions/bubbles5", + "ambient/underwater/additions/bubbles6", + "ambient/underwater/additions/water1", + "ambient/underwater/additions/water2" + ] + }, + "ambient.underwater.loop.additions.ultra_rare": { + "sounds": [ + "ambient/underwater/additions/animal2", + "ambient/underwater/additions/dark1", + { + "name": "ambient/underwater/additions/dark2", + "volume": 0.7 + }, + "ambient/underwater/additions/dark3", + "ambient/underwater/additions/dark4" + ] + }, + "block.lava.ambient": { + "subtitle": "subtitles.block.lava.ambient", + "sounds": [ + "liquid/lava" + ] + }, + "entity.dolphin.ambient_water": { + "subtitle": "subtitles.entity.dolphin.ambient_water", + "sounds": [ + { + "name": "mob/dolphin/idle_water1", + "volume": 0.8 + }, + "mob/dolphin/idle_water2", + "mob/dolphin/idle_water3", + "mob/dolphin/idle_water4", + "mob/dolphin/idle_water5", + "mob/dolphin/idle_water6", + { + "name": "mob/dolphin/idle_water7", + "volume": 0.75 + }, + { + "name": "mob/dolphin/idle_water8", + "volume": 0.75 + }, + "mob/dolphin/idle_water9", + { + "name": "mob/dolphin/idle_water10", + "volume": 0.8 + } + ] + }, + "entity.parrot.imitate.drowned": { + "subtitle": "subtitles.entity.parrot.imitate.drowned", + "sounds": [ + { + "name": "entity.drowned.ambient", + "type": "event", + "volume": 0.6, + "pitch": 1.8 + } + ] + }, + "item.trident.return": { + "subtitle": "subtitles.item.trident.return", + "sounds": [ + { + "name": "item/trident/return1", + "volume": 0.8 + }, + { + "name": "item/trident/return2", + "volume": 0.8, + "pitch": 1.2 + }, + { + "name": "item/trident/return3", + "volume": 0.8, + "pitch": 0.8 + }, + { + "name": "item/trident/return2", + "volume": 0.8 + }, + { + "name": "item/trident/return2", + "volume": 0.8, + "pitch": 1.2 + }, + { + "name": "item/trident/return2", + "volume": 0.8, + "pitch": 0.8 + }, + { + "name": "item/trident/return3", + "volume": 0.8 + }, + { + "name": "item/trident/return3", + "volume": 0.8, + "pitch": 1.2 + }, + { + "name": "item/trident/return3", + "volume": 0.8, + "pitch": 0.8 + } + ] + }, + "music_disc.blocks": { + "sounds": [ + { + "name": "records/blocks", + "stream": true + } + ] + } +} \ No newline at end of file diff --git a/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java b/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java index 9dd64695ac..1969aa6a46 100644 --- a/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java +++ b/src/main/java/net/minecraftforge/common/data/ExistingFileHelper.java @@ -31,6 +31,8 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import net.minecraft.data.IDataProvider; +import net.minecraft.client.resources.ResourceIndex; +import net.minecraft.client.resources.VirtualAssetsPack; import net.minecraft.resources.FilePack; import net.minecraft.resources.FolderPack; import net.minecraft.resources.IResource; @@ -46,6 +48,8 @@ import net.minecraftforge.fml.event.lifecycle.GatherDataEvent; import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; import net.minecraftforge.fml.packs.ModFileResourcePack; +import javax.annotation.Nullable; + /** * Enables data providers to check if other data files currently exist. The * instance provided in the {@link GatherDataEvent} utilizes the standard @@ -105,11 +109,22 @@ public class ExistingFileHelper { * @param existingMods * @param enable */ + @Deprecated // TODO: Remove in 1.17 public ExistingFileHelper(Collection existingPacks, Set existingMods, boolean enable) { + this(existingPacks, existingMods, enable, null, null); + } + + public ExistingFileHelper(Collection existingPacks, final Set existingMods, boolean enable, @Nullable final String assetIndex, @Nullable final File assetsDir) { this.clientResources = new SimpleReloadableResourceManager(ResourcePackType.CLIENT_RESOURCES); this.serverData = new SimpleReloadableResourceManager(ResourcePackType.SERVER_DATA); + this.clientResources.add(new VanillaPack("minecraft", "realms")); + if (assetIndex != null && assetsDir != null) + { + this.clientResources.add(new VirtualAssetsPack(new ResourceIndex(assetsDir, assetIndex))); + } this.serverData.add(new VanillaPack("minecraft")); + for (Path existing : existingPacks) { File file = existing.toFile(); IResourcePack pack = file.isDirectory() ? new FolderPack(file) : new FilePack(file); diff --git a/src/main/java/net/minecraftforge/common/data/SoundDefinition.java b/src/main/java/net/minecraftforge/common/data/SoundDefinition.java new file mode 100644 index 0000000000..b2e5acd36b --- /dev/null +++ b/src/main/java/net/minecraftforge/common/data/SoundDefinition.java @@ -0,0 +1,422 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2020. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.common.data; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import net.minecraft.util.ResourceLocation; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Contains all the data to completely define a sound event. + */ +public final class SoundDefinition +{ + /** + * Identifies a specific sound that has to be played in a sound event, along with + * all the necessary parameters. + * + *

If any of the optional parameters (i.e. the ones that aren't required to + * obtain an instance of this class) are unset, their default values will be + * used instead. The list of defaults is available in the text that follows:

+ * + *
    + *
  • Volume: 1.0F
  • + *
  • Pitch: 1.0F
  • + *
  • Weight: 1
  • + *
  • Stream: false
  • + *
  • Attenuation Distance: 16
  • + *
  • Preload: false
  • + *
+ */ + public static final class Sound + { + private static final SoundType DEFAULT_TYPE = SoundType.SOUND; + private static final float DEFAULT_VOLUME = 1.0F; + private static final float DEFAULT_PITCH = 1.0F; + private static final int DEFAULT_WEIGHT = 1; + private static final boolean DEFAULT_STREAM = false; + private static final int DEFAULT_ATTENUATION_DISTANCE = 16; + private static final boolean DEFAULT_PRELOAD = false; + + private final ResourceLocation name; + private final SoundType type; + + // Optional parameters, available in specs + private float volume = DEFAULT_VOLUME; + private float pitch = DEFAULT_PITCH; + private int weight = DEFAULT_WEIGHT; + private boolean stream = DEFAULT_STREAM; + private int attenuationDistance = DEFAULT_ATTENUATION_DISTANCE; + private boolean preload = DEFAULT_PRELOAD; + + private Sound(final ResourceLocation name, final SoundType type) + { + this.name = name; + this.type = type; + } + + /** + * Creates a new sound with the given name and type. + * + * @param name The name of the sound to create. + * @param type The type of sound to create. + */ + public static Sound sound(final ResourceLocation name, final SoundType type) + { + return new Sound(name, type); + } + + /** + * Sets the volume of this specific sound. + * + *

The volume of a sound represents how loud the sound is when played.

+ * + * @param volume The volume to set. It must be higher than 0. + * @return This sound for chaining. + */ + public Sound volume(final double volume) + { + return this.volume((float) volume); + } + + /** + * Sets the volume of this specific sound. + * + *

The volume of a sound represents how loud the sound is when played.

+ * + * @param volume The volume to set. It must be higher than 0. + * @return This sound for chaining. + */ + public Sound volume(final float volume) + { + // Wiki specifies that volume cannot be higher than 1.0F, but I don't see any checks in vanilla nor in the + // original specs (https://www.reddit.com/r/Minecraft/comments/1ont25/snapshot_13w42a_has_been_released/cctryvp/) + // Set at own risk + if (volume <= 0.0F) { + throw new IllegalArgumentException("Volume must be positive for sound " + this.name + ", but instead got " + volume); + } + this.volume = volume; + return this; + } + + /** + * Sets the pitch of this specific sound. + * + *

The pitch of a sound represents how high or low the sound is + * when played.

+ * + * @param pitch The pitch to set. It must be higher than 0. + * @return This sound for chaining. + */ + public Sound pitch(final double pitch) + { + return this.pitch((float) pitch); + } + + /** + * Sets the pitch of this specific sound. + * + *

The pitch of a sound represents how high or low the sound is + * when played.

+ * + * @param pitch The pitch to set. It must be higher than 0. + * @return This sound for chaining. + */ + public Sound pitch(final float pitch) + { + if (pitch <= 0.0F) + { + throw new IllegalArgumentException("Pitch must be positive for sound " + this.name + ", but instead got " + pitch); + } + this.pitch = pitch; + return this; + } + + /** + * Sets the weight of this specific sound. + * + *

The weight represents how likely it is for this sound to be played when the respective + * event is triggered. This value is ignored when there is only one sound per event.

+ * + * @param weight The weight to set. It must be higher than 0. + * @return This sound for chaining. + */ + public Sound weight(final int weight) + { + if (weight <= 0) + { + throw new IllegalArgumentException("Weight has to be a positive number in sound " + this.name + ", but instead got " + weight); + } + this.weight = weight; + return this; + } + + /** + * Sets this sound to a streamed sound. + * + *

In this context, streaming refers to reading the file on disk as needed instead of + * loading the whole set in memory. This is useful in case of longer sounds, like records + * and music (usually more than a minute).

+ * + *

This is equivalent to a call to {@link #stream(boolean)} with a value of true.

+ * + * @return This sound for chaining + */ + public Sound stream() + { + return this.stream(true); + } + + /** + * Sets whether this sound should be streamed or not. + * + *

In this context, streaming refers to reading the file on disk as needed instead of + * loading the whole set in memory. This is useful in case of longer sounds, like records + * and music (usually more than a minute).

+ * + * @param stream Whether the sound should be streamed or not. + * @return This sound for chaining. + */ + public Sound stream(final boolean stream) + { + this.stream = stream; + return this; + } + + /** + * Sets the attenuation distance of the sound. + * + *

This represents how far this sound will be heard, in blocks. While the specs don't + * require so, it is suggested to keep this value positive.

+ * + * @param attenuationDistance The attenuation distance to set. + * @return This sound for chaining. + */ + public Sound attenuationDistance(final int attenuationDistance) + { + this.attenuationDistance = attenuationDistance; + return this; + } + + /** + * Marks this sound as needing to be preloaded. + * + *

A preloaded sound identifies a sound that is loaded in memory as soon as the resource + * pack is loaded, without having to wait for the sound to be ready to stream. It is suggested + * to keep this to {@code false}, unless you are using it for a highly recurring sound (e.g. + * underwater ambient sounds).

+ * + *

This is equivalent to a call to {@link #preload(boolean)} with a value of true.

+ * + * @return This sound for chaining. + */ + public Sound preload() + { + return this.preload(true); + } + + /** + * Sets whether this sound should be preloaded or not. + * + *

A preloaded sound identifies a sound that is loaded in memory as soon as the resource + * pack is loaded, without having to wait for the sound to be ready to stream. It is suggested + * to keep this to {@code false}, unless you are using it for a highly recurring sound (e.g. + * underwater ambient sounds).

+ * + * @param preload Whether the sound should be preloaded or not. + * @return This sound for chaining. + */ + public Sound preload(final boolean preload) + { + this.preload = preload; + return this; + } + + ResourceLocation name() + { + return this.name; + } + + SoundType type() + { + return this.type; + } + + JsonElement serialize() + { + if (this.canBeInShortForm()) + { + return new JsonPrimitive(this.stripMcPrefix(this.name)); + } + + final JsonObject object = new JsonObject(); + object.addProperty("name", this.stripMcPrefix(this.name)); + if (this.type != DEFAULT_TYPE) object.addProperty("type", this.type.jsonString); + if (this.volume != DEFAULT_VOLUME) object.addProperty("volume", this.volume); + if (this.pitch != DEFAULT_PITCH) object.addProperty("pitch", this.pitch); + if (this.weight != DEFAULT_WEIGHT) object.addProperty("weight", this.weight); + if (this.stream != DEFAULT_STREAM) object.addProperty("stream", this.stream); + if (this.preload != DEFAULT_PRELOAD) object.addProperty("preload", this.preload); + if (this.attenuationDistance != DEFAULT_ATTENUATION_DISTANCE) object.addProperty("attenuation_distance", this.attenuationDistance); + return object; + } + + private boolean canBeInShortForm() + { + return this.type == DEFAULT_TYPE && + this.volume == DEFAULT_VOLUME && + this.pitch == DEFAULT_PITCH && + this.weight == DEFAULT_WEIGHT && + this.stream == DEFAULT_STREAM && + this.attenuationDistance == DEFAULT_ATTENUATION_DISTANCE && + this.preload == DEFAULT_PRELOAD; + } + + private String stripMcPrefix(final ResourceLocation name) + { + return "minecraft".equals(name.getNamespace()) ? name.getPath() : name.toString(); + } + } + + /** + * Represents the type of sound that the {@link Sound} object represents. + */ + public enum SoundType + { + /** + * Identifies a "normal" sound. + * + *

In a "normal" sound, the {@code name} is considered a file name, which + * the game attempts to load from the currently loaded resource packs.

+ */ + SOUND("sound"), + /** + * Identifies a "redirect" sound. + * + *

In a "redirect" sound, the {@code name} of the sound is treated as the + * name of another {@code SoundEvent}, which will be queried. Processing is + * then deferred to that specific sound event, recursively as needed.

+ */ + EVENT("event"); + + private final String jsonString; + + SoundType(final String jsonString) + { + this.jsonString = jsonString; + } + } + + private final List sounds = new ArrayList<>(); + private boolean replace = false; + private String subtitle = null; + + private SoundDefinition() {} + + /** + * Creates a new {@link SoundDefinition}, which will host a set of + * {@link Sound}s and the necessary parameters. + */ + public static SoundDefinition definition() + { + return new SoundDefinition(); + } + + /** + * Sets whether this definition should replace any other definition for the + * same sound event previously applied, rather than overwriting it. + * + * @param replace Whether this definition replaces or not. + * @return This definition for chaining. + */ + public SoundDefinition replace(final boolean replace) + { + this.replace = replace; + return this; + } + + /** + * Sets the language key for the subtitle that will be displayed whenever this + * sound is being played. + * + *

The subtitle is optional and the game will skip displaying it if it + * isn't present.

+ * + * @param subtitle The subtitle to display, or null to disable. + * @return This definition for chaining. + */ + public SoundDefinition subtitle(@Nullable final String subtitle) + { + this.subtitle = subtitle; + return this; + } + + /** + * Adds the given sound to this sound definition. + * + * @param sound The sound to add. + * @return This definition for chaining. + */ + public SoundDefinition with(final Sound sound) + { + this.sounds.add(sound); + return this; + } + + /** + * Adds the given sounds to this sound definition. + * + * @param sounds The sounds to add. + * @return This definition for chaining. + */ + public SoundDefinition with(final Sound... sounds) + { + this.sounds.addAll(Arrays.asList(sounds)); + return this; + } + + List soundList() + { + return this.sounds; + } + + JsonObject serialize() + { + if (this.sounds.isEmpty()) + { + throw new IllegalStateException("Unable to serialize a sound definition that has no sounds!"); + } + + final JsonObject object = new JsonObject(); + if (this.replace) object.addProperty("replace", true); + if (this.subtitle != null) object.addProperty("subtitle", this.subtitle); + final JsonArray sounds = new JsonArray(); + this.sounds.stream().map(Sound::serialize).forEach(sounds::add); + object.add("sounds", sounds); + return object; + } +} diff --git a/src/main/java/net/minecraftforge/common/data/SoundDefinitionsProvider.java b/src/main/java/net/minecraftforge/common/data/SoundDefinitionsProvider.java new file mode 100644 index 0000000000..60c4a7467d --- /dev/null +++ b/src/main/java/net/minecraftforge/common/data/SoundDefinitionsProvider.java @@ -0,0 +1,283 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2020. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.common.data; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import net.minecraft.data.DataGenerator; +import net.minecraft.data.DirectoryCache; +import net.minecraft.data.IDataProvider; +import net.minecraft.resources.ResourcePackType; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.SoundEvent; +import net.minecraftforge.registries.ForgeRegistries; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +/** + * Data provider for the {@code sounds.json} file, which identifies sound definitions + * for the various sound events in Minecraft. + */ +public abstract class SoundDefinitionsProvider implements IDataProvider +{ + private static final Logger LOGGER = LogManager.getLogger(); + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + private final DataGenerator generator; + private final String modId; + private final ExistingFileHelper helper; + + private final Map sounds = new LinkedHashMap<>(); + + /** + * Creates a new instance of this data provider. + * + * @param generator The data generator instance provided by the event you are initializing this provider in. + * @param modId The mod ID of the current mod. + * @param helper The existing file helper provided by the event you are initializing this provider in. + */ + protected SoundDefinitionsProvider(final DataGenerator generator, final String modId, final ExistingFileHelper helper) + { + this.generator = generator; + this.modId = modId; + this.helper = helper; + } + + /** + * Registers the sound definitions that should be generated via one of the {@code add} methods. + */ + public abstract void registerSounds(); + + @Override + public void run(DirectoryCache cache) throws IOException + { + this.sounds.clear(); + this.registerSounds(); + this.validate(); + if (!this.sounds.isEmpty()) + { + this.save(cache, this.generator.getOutputFolder().resolve("assets/" + this.modId + "/sounds.json")); + } + } + + @Override + public String getName() + { + return "Sound Definitions"; + } + + // Quick helpers + /** + * Creates a new {@link SoundDefinition}, which will host a set of + * {@link SoundDefinition.Sound}s and the necessary parameters. + */ + protected static SoundDefinition definition() + { + return SoundDefinition.definition(); + } + + /** + * Creates a new sound with the given name and type. + * + * @param name The name of the sound to create. + * @param type The type of sound to create. + */ + protected static SoundDefinition.Sound sound(final ResourceLocation name, final SoundDefinition.SoundType type) + { + return SoundDefinition.Sound.sound(name, type); + } + + /** + * Creates a new sound with the given name and {@link SoundDefinition.SoundType#SOUND} as + * sound type. + * + * @param name The name of the sound to create. + */ + protected static SoundDefinition.Sound sound(final ResourceLocation name) + { + return sound(name, SoundDefinition.SoundType.SOUND); + } + + /** + * Creates a new sound with the given name and type. + * + * @param name The name of the sound to create. + * @param type The type of sound to create. + */ + protected static SoundDefinition.Sound sound(final String name, final SoundDefinition.SoundType type) + { + return sound(new ResourceLocation(name), type); + } + + /** + * Creates a new sound with the given name and {@link SoundDefinition.SoundType#SOUND} as + * sound type. + * + * @param name The name of the sound to create. + */ + protected static SoundDefinition.Sound sound(final String name) + { + return sound(new ResourceLocation(name)); + } + + // Addition methods + /** + * Adds the entry name associated with the supplied {@link SoundEvent} with the given + * {@link SoundDefinition} to the list. + * + *

This method should be preferred when dealing with a {@code RegistryObject} or + * {@code RegistryDelegate}.

+ * + * @param soundEvent A {@code Supplier} for the given {@link SoundEvent}. + * @param definition A {@link SoundDefinition} that defines the given sound. + */ + protected void add(final Supplier soundEvent, final SoundDefinition definition) + { + this.add(soundEvent.get(), definition); + } + + /** + * Adds the entry name associated with the given {@link SoundEvent} with the + * {@link SoundDefinition} to the list. + * + *

This method should be preferred when a {@code SoundEvent} is already + * available in the method context. If you already have a {@code Supplier} for + * it, refer to {@link #add(Supplier, SoundDefinition)}.

+ * + * @param soundEvent A {@link SoundEvent}. + * @param definition The {@link SoundDefinition} that defines the given event. + */ + protected void add(final SoundEvent soundEvent, final SoundDefinition definition) + { + this.add(soundEvent.getLocation(), definition); + } + + /** + * Adds the {@link SoundEvent} referenced by the given {@link ResourceLocation} with the + * {@link SoundDefinition} to the list. + * + * @param soundEvent The {@link ResourceLocation} that identifies the event. + * @param definition The {@link SoundDefinition} that defines the given event. + */ + protected void add(final ResourceLocation soundEvent, final SoundDefinition definition) + { + this.addSounds(soundEvent.getPath(), definition); + } + + /** + * Adds the {@link SoundEvent} with the specified name along with its {@link SoundDefinition} + * to the list. + * + *

The given sound event must NOT contain the namespace the name is a part of, since + * the sound definition specification doesn't allow sounds to be defined outside the + * namespace they're in. For this reason, any namespace will automatically be stripped + * from the name.

+ * + * @param soundEvent The name of the {@link SoundEvent}. + * @param definition The {@link SoundDefinition} that defines the given event. + */ + protected void add(final String soundEvent, final SoundDefinition definition) + { + this.add(new ResourceLocation(soundEvent), definition); + } + + private void addSounds(final String soundEvent, final SoundDefinition definition) + { + if (this.sounds.put(soundEvent, definition) != null) + { + throw new IllegalStateException("Sound event '" + this.modId + ":" + soundEvent + "' already exists"); + } + } + + // Internal handling stuff + private void validate() + { + final List notValid = this.sounds.entrySet().stream() + .filter(it -> !this.validate(it.getKey(), it.getValue())) + .map(Map.Entry::getKey) + .map(it -> this.modId + ":" + it) + .collect(Collectors.toList()); + if (!notValid.isEmpty()) + { + throw new IllegalStateException("Found invalid sound events: " + notValid); + } + } + + private boolean validate(final String name, final SoundDefinition def) + { + return def.soundList().stream().allMatch(it -> this.validate(name,it)); + } + + private boolean validate(final String name, final SoundDefinition.Sound sound) + { + switch (sound.type()) + { + case SOUND: return this.validateSound(name, sound.name()); + case EVENT: return this.validateEvent(name, sound.name()); + } + // Differently from all the other errors, this is not a 'missing sound' but rather something completely different + // that has broken the invariants of this sound definitions provider. In fact, a sound may only be either of + // SOUND or EVENT type. Any other values is somebody messing with the internals, reflectively adding something + // to an enum or passing `null` to a parameter annotated with `@Nonnull`. + throw new IllegalArgumentException("The given sound '" + sound.name() + "' does not have a valid type: expected either SOUND or EVENT, but found " + sound.type()); + } + + private boolean validateSound(final String soundName, final ResourceLocation name) + { + final boolean valid = this.helper.exists(name, ResourcePackType.CLIENT_RESOURCES, ".ogg", "sounds"); + if (!valid) + { + final String path = name.getNamespace() + ":sounds/" + name.getPath() + ".ogg"; + LOGGER.warn("Unable to find corresponding OGG file '{}' for sound event '{}'", path, soundName); + } + return valid; + } + + private boolean validateEvent(final String soundName, final ResourceLocation name) + { + final boolean valid = this.sounds.containsKey(soundName) || ForgeRegistries.SOUND_EVENTS.containsKey(name); + if (!valid) + { + LOGGER.warn("Unable to find event '{}' referenced from '{}'", name, soundName); + } + return valid; + } + + private void save(final DirectoryCache cache, final Path targetFile) throws IOException + { + IDataProvider.save(GSON, cache, this.mapToJson(this.sounds), targetFile); + } + + private JsonObject mapToJson(final Map map) + { + final JsonObject obj = new JsonObject(); + // namespaces are ignored when serializing + map.forEach((k, v) -> obj.add(k, v.serialize())); + return obj; + } +} diff --git a/src/main/java/net/minecraftforge/common/data/package-info.java b/src/main/java/net/minecraftforge/common/data/package-info.java new file mode 100644 index 0000000000..136da9bdf5 --- /dev/null +++ b/src/main/java/net/minecraftforge/common/data/package-info.java @@ -0,0 +1,25 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2020. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault +package net.minecraftforge.common.data; + +import mcp.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/net/minecraftforge/fml/DatagenModLoader.java b/src/main/java/net/minecraftforge/fml/DatagenModLoader.java index b14e9dfc39..3d4ec7e94a 100644 --- a/src/main/java/net/minecraftforge/fml/DatagenModLoader.java +++ b/src/main/java/net/minecraftforge/fml/DatagenModLoader.java @@ -26,6 +26,7 @@ import net.minecraftforge.fml.event.lifecycle.GatherDataEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import java.io.File; import java.nio.file.Path; import java.util.Collection; import java.util.Set; @@ -45,7 +46,12 @@ public class DatagenModLoader { begin(mods, path, inputs, existingPacks, Collections.emptySet(), serverGenerators, clientGenerators, devToolGenerators, reportsGenerator, structureValidator, flat); } + @Deprecated //TODO: Remove in 1.17 public static void begin(final Set mods, final Path path, final Collection inputs, Collection existingPacks, Set existingMods, final boolean serverGenerators, final boolean clientGenerators, final boolean devToolGenerators, final boolean reportsGenerator, final boolean structureValidator, final boolean flat) { + begin(mods, path, inputs, existingPacks, existingMods, serverGenerators, clientGenerators, devToolGenerators, reportsGenerator, structureValidator, flat, null, null); + } + + public static void begin(final Set mods, final Path path, final Collection inputs, Collection existingPacks, Set existingMods, final boolean serverGenerators, final boolean clientGenerators, final boolean devToolGenerators, final boolean reportsGenerator, final boolean structureValidator, final boolean flat, final String assetIndex, final File assetsDir) { if (mods.contains("minecraft") && mods.size() == 1) return; LOGGER.info("Initializing Data Gatherer for mods {}", mods); runningDataGen = true; @@ -56,7 +62,7 @@ public class DatagenModLoader { //If we aren't generating data for forge, automatically add forge as an existing so mods can access forge's data existingMods.add("forge"); } - existingFileHelper = new ExistingFileHelper(existingPacks, existingMods, structureValidator); + existingFileHelper = new ExistingFileHelper(existingPacks, existingMods, structureValidator, assetIndex, assetsDir); ModLoader.get().runEventGenerator(mc->new GatherDataEvent(mc, dataGeneratorConfig.makeGenerator(p->dataGeneratorConfig.isFlat() ? p : p.resolve(mc.getModId()), dataGeneratorConfig.getMods().contains(mc.getModId())), dataGeneratorConfig, existingFileHelper)); dataGeneratorConfig.runAll(); } diff --git a/src/main/java/net/minecraftforge/fml/ModLoader.java b/src/main/java/net/minecraftforge/fml/ModLoader.java index a3e3fb6a6a..0462b28d3d 100644 --- a/src/main/java/net/minecraftforge/fml/ModLoader.java +++ b/src/main/java/net/minecraftforge/fml/ModLoader.java @@ -45,7 +45,13 @@ import net.minecraftforge.versions.forge.ForgeVersion; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; diff --git a/src/test/java/net/minecraftforge/debug/DataGeneratorTest.java b/src/test/java/net/minecraftforge/debug/DataGeneratorTest.java index 5d25f6b137..0897ac387a 100644 --- a/src/test/java/net/minecraftforge/debug/DataGeneratorTest.java +++ b/src/test/java/net/minecraftforge/debug/DataGeneratorTest.java @@ -22,17 +22,29 @@ package net.minecraftforge.debug; import static net.minecraftforge.debug.DataGeneratorTest.MODID; import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; +import com.google.gson.JsonNull; +import com.google.gson.JsonPrimitive; import net.minecraft.block.*; +import net.minecraft.util.SoundEvents; +import net.minecraftforge.common.data.SoundDefinition; +import net.minecraftforge.common.data.SoundDefinitionsProvider; +import org.apache.commons.lang3.tuple.Triple; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jline.utils.InputStreamReader; @@ -117,6 +129,7 @@ public class DataGeneratorTest ItemModelProvider itemModels = new ItemModels(gen, event.getExistingFileHelper()); gen.addProvider(itemModels); gen.addProvider(new BlockStates(gen, itemModels.existingFileHelper)); + gen.addProvider(new SoundDefinitions(gen, event.getExistingFileHelper())); } if (event.includeServer()) { @@ -202,6 +215,224 @@ public class DataGeneratorTest } } + public static class SoundDefinitions extends SoundDefinitionsProvider + { + private static final Logger LOGGER = LogManager.getLogger(); + private final ExistingFileHelper helper; + + public SoundDefinitions(final DataGenerator generator, final ExistingFileHelper helper) + { + super(generator, MODID, helper); + this.helper = helper; + } + + @Override + public void registerSounds() + { + // ambient.underwater.loop.additions + this.add(SoundEvents.AMBIENT_UNDERWATER_LOOP_ADDITIONS, definition().with( + sound("ambient/underwater/additions/bubbles1"), + sound("ambient/underwater/additions/bubbles2"), + sound("ambient/underwater/additions/bubbles3"), + sound("ambient/underwater/additions/bubbles4"), + sound("ambient/underwater/additions/bubbles5"), + sound("ambient/underwater/additions/bubbles6"), + sound("ambient/underwater/additions/water1"), + sound("ambient/underwater/additions/water2") + )); + + //ambient.underwater.loop.additions.ultra_rare + this.add(SoundEvents.AMBIENT_UNDERWATER_LOOP_ADDITIONS_ULTRA_RARE, definition().with( + sound("ambient/underwater/additions/animal2"), + sound("ambient/underwater/additions/dark1"), + sound("ambient/underwater/additions/dark2").volume(0.7), + sound("ambient/underwater/additions/dark3"), + sound("ambient/underwater/additions/dark4") + )); + + //block.lava.ambient + this.add(SoundEvents.LAVA_AMBIENT, definition().with(sound("liquid/lava")).subtitle("subtitles.block.lava.ambient")); + + //entity.dolphin.ambient_water + this.add(SoundEvents.DOLPHIN_AMBIENT_WATER, definition().with( + sound("mob/dolphin/idle_water1").volume(0.8), + sound("mob/dolphin/idle_water2"), + sound("mob/dolphin/idle_water3"), + sound("mob/dolphin/idle_water4"), + sound("mob/dolphin/idle_water5"), + sound("mob/dolphin/idle_water6"), + sound("mob/dolphin/idle_water7").volume(0.75), + sound("mob/dolphin/idle_water8").volume(0.75), + sound("mob/dolphin/idle_water9"), + sound("mob/dolphin/idle_water10").volume(0.8) + ).subtitle("subtitles.entity.dolphin.ambient_water")); + + //entity.parrot.imitate.drowned + this.add(SoundEvents.PARROT_IMITATE_DROWNED, definition().with( + sound("entity.drowned.ambient", SoundDefinition.SoundType.EVENT).pitch(1.8).volume(0.6) + ).subtitle("subtitles.entity.parrot.imitate.drowned")); + + //item.trident.return + this.add(SoundEvents.TRIDENT_RETURN, definition().with( + sound("item/trident/return1").volume(0.8), + sound("item/trident/return2").pitch(1.2).volume(0.8), + sound("item/trident/return3").pitch(0.8).volume(0.8), + sound("item/trident/return2").volume(0.8), + sound("item/trident/return2").pitch(1.2).volume(0.8), + sound("item/trident/return2").pitch(0.8).volume(0.8), + sound("item/trident/return3").volume(0.8), + sound("item/trident/return3").pitch(1.2).volume(0.8), + sound("item/trident/return3").pitch(0.8).volume(0.8) + ).subtitle("subtitles.item.trident.return")); + + //music_disc.blocks + this.add(SoundEvents.MUSIC_DISC_BLOCKS, definition().with(sound("records/blocks").stream())); + } + + @Override + public void run(DirectoryCache cache) throws IOException + { + super.run(cache); + test(); + } + + private void test() throws IOException + { + final JsonObject generated; + try + { + generated = reflect(); + } + catch (ReflectiveOperationException e) + { + throw new RuntimeException("Unable to test for errors due to reflection error", e); + } + final JsonObject actual = GSON.fromJson( + new InputStreamReader(this.helper.getResource(new ResourceLocation("sounds.json"), ResourcePackType.CLIENT_RESOURCES).getInputStream()), + JsonObject.class + ); + + final JsonObject filtered = new JsonObject(); + generated.entrySet().forEach(it -> filtered.add(it.getKey(), Optional.ofNullable(actual.get(it.getKey())).orElseGet(JsonNull::new))); + + final List errors = this.compareObjects(filtered, generated); + + if (!errors.isEmpty()) { + LOGGER.error("Found {} discrepancies between generated and vanilla sound definitions: ", errors.size()); + for (String s : errors) { + LOGGER.error(" {}", s); + } + throw new RuntimeException("Generated sounds.json differed from vanilla equivalent, check above errors."); + } + } + + private JsonObject reflect() throws ReflectiveOperationException + { + // This is not supposed to be done by client code, so we just run with reflection to avoid exposing + // something that shouldn't be exposed in the first place + final Method mapToJson = this.getClass().getSuperclass().getDeclaredMethod("mapToJson", Map.class); + mapToJson.setAccessible(true); + final Field map = this.getClass().getSuperclass().getDeclaredField("sounds"); + map.setAccessible(true); + //noinspection JavaReflectionInvocation + return (JsonObject) mapToJson.invoke(this, map.get(this)); + } + + private List compareAndGatherErrors(final Triple triple) + { + return this.compare(triple.getRight(), triple.getMiddle()).stream().map(it -> triple.getLeft() + ": " + it).collect(Collectors.toList()); + } + + private List compare(final JsonElement vanilla, final JsonElement generated) + { + if (vanilla.isJsonPrimitive()) + { + return this.comparePrimitives(vanilla.getAsJsonPrimitive(), generated); + } + else if (vanilla.isJsonObject()) + { + return this.compareObjects(vanilla.getAsJsonObject(), generated); + } + else if (vanilla.isJsonArray()) + { + return this.compareArrays(vanilla.getAsJsonArray(), generated); + } + else if (vanilla.isJsonNull() && !generated.isJsonNull()) + { + return Collections.singletonList("null value in vanilla doesn't match non-null value in generated"); + } + throw new RuntimeException("Unable to match " + vanilla + " to any JSON type"); + } + + private List comparePrimitives(final JsonPrimitive vanilla, final JsonElement generated) + { + if (!generated.isJsonPrimitive()) return Collections.singletonList("Primitive in vanilla isn't matched by generated " + generated); + + final JsonPrimitive generatedPrimitive = generated.getAsJsonPrimitive(); + + if (vanilla.isBoolean()) + { + if (!generatedPrimitive.isBoolean()) return Collections.singletonList("Boolean in vanilla isn't matched by non-boolean " + generatedPrimitive); + + if (vanilla.getAsBoolean() != generated.getAsBoolean()) + { + return Collections.singletonList("Boolean '" + vanilla.getAsBoolean() + "' does not match generated '" + generatedPrimitive.getAsBoolean() + "'"); + } + } + else if (vanilla.isNumber()) + { + if (!generatedPrimitive.isNumber()) return Collections.singletonList("Number in vanilla isn't matched by non-number " + generatedPrimitive); + + // Handle numbers via big decimal so we are sure there isn't any sort of errors due to float/long + final BigDecimal vanillaNumber = vanilla.getAsBigDecimal(); + final BigDecimal generatedNumber = vanilla.getAsBigDecimal(); + + if (vanillaNumber.compareTo(generatedNumber) != 0) + { + return Collections.singletonList("Number '" + vanillaNumber + "' does not match generated '" + generatedNumber + "'"); + } + } + else if (vanilla.isString()) + { + if (!generatedPrimitive.isString()) return Collections.singletonList("String in vanilla isn't matched by non-string " + generatedPrimitive); + + if (!vanilla.getAsString().equals(generatedPrimitive.getAsString())) + { + return Collections.singletonList("String '" + vanilla.getAsString() + "' does not match generated '" + generatedPrimitive.getAsString() + "'"); + } + } + + return new ArrayList<>(); + } + + private List compareObjects(final JsonObject vanilla, final JsonElement generated) + { + if (!generated.isJsonObject()) return Collections.singletonList("Object in vanilla isn't matched by generated " + generated); + + final JsonObject generatedObject = generated.getAsJsonObject(); + + return vanilla.entrySet().stream() + .map(it -> Triple.of(it.getKey(), it.getValue(), generatedObject.get(it.getKey()))) + .map(this::compareAndGatherErrors) + .flatMap(List::stream) + .collect(Collectors.toList()); + } + + private List compareArrays(final JsonArray vanilla, final JsonElement generated) + { + if (!generated.isJsonArray()) return Collections.singletonList("Array in vanilla isn't matched by generated " + generated); + + final JsonArray generatedArray = generated.getAsJsonArray(); + + return IntStream.range(0, vanilla.size()) + .mapToObj(it -> Triple.of("[" + it + "]", vanilla.get(it), generatedArray.get(it))) + .map(this::compareAndGatherErrors) + .flatMap(List::stream) + .collect(Collectors.toList()); + } + } + + public static class Tags extends BlockTagsProvider { public Tags(DataGenerator gen, ExistingFileHelper existingFileHelper) diff --git a/src/userdev/java/net/minecraftforge/userdev/LaunchTesting.java b/src/userdev/java/net/minecraftforge/userdev/LaunchTesting.java index 7a64a9d83d..058f161376 100644 --- a/src/userdev/java/net/minecraftforge/userdev/LaunchTesting.java +++ b/src/userdev/java/net/minecraftforge/userdev/LaunchTesting.java @@ -62,11 +62,14 @@ public class LaunchTesting lst.putLazy("fml.forgeGroup", System.getenv("FORGE_GROUP")); lst.putLazy("fml.forgeVersion", System.getenv("FORGE_VERSION")); + if (target.contains("client") || target.contains("data")) { + lst.putLazy("assetIndex", System.getenv("assetIndex")); + lst.putLazy("assetsDir", System.getenv().getOrDefault("assetDirectory", "assets")); + } + if (target.contains("client")) { hackNatives(); lst.putLazy("version", "MOD_DEV"); - lst.putLazy("assetIndex", System.getenv("assetIndex")); - lst.putLazy("assetsDir", System.getenv().getOrDefault("assetDirectory", "assets")); String assets = lst.get("assetsDir"); if (assets == null || !new File(assets).exists()) {