Skip to content

Commit

Permalink
Use new "extraData" for material tier sections
Browse files Browse the repository at this point in the history
Means books can now use any tier instead of needing to register one per tier
  • Loading branch information
KnightMiner committed Sep 19, 2022
1 parent 2c57e22 commit 18cc46f
Show file tree
Hide file tree
Showing 35 changed files with 211 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import slimeknights.tconstruct.library.client.book.sectiontransformer.ModifierSectionTransformer;
import slimeknights.tconstruct.library.client.book.sectiontransformer.ToolSectionTransformer;
import slimeknights.tconstruct.library.client.book.sectiontransformer.materials.SkullMaterialSectionTransformer;
import slimeknights.tconstruct.library.client.book.sectiontransformer.materials.TierRangeMaterialSectionTransformer;
import slimeknights.tconstruct.library.client.book.sectiontransformer.materials.TieredMaterialSectionTransformer;
import slimeknights.tconstruct.shared.item.TinkerBookItem.BookType;

Expand Down Expand Up @@ -50,6 +51,7 @@ public static void initBook() {
ENCYCLOPEDIA.addTransformer(armorTransformer);

// material tier transformers
// TODO 1.19: remove old materail section transformers
MATERIALS_AND_YOU.addTransformer(new TieredMaterialSectionTransformer("tier_one_materials", 1, false));
PUNY_SMELTING.addTransformer(new TieredMaterialSectionTransformer("tier_two_materials", 2, false));
MIGHTY_SMELTING.addTransformer(new TieredMaterialSectionTransformer("tier_three_materials", 3, false));
Expand Down Expand Up @@ -96,6 +98,7 @@ private static void addStandardData(BookData book, ResourceLocation id) {
book.addTransformer(BookTransformer.indexTranformer());
// padding needs to be last to ensure page counts are right
book.addTransformer(BookTransformer.paddingTransformer());
book.addTransformer(TierRangeMaterialSectionTransformer.INSTANCE);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package slimeknights.tconstruct.library.client.book.sectiontransformer.materials;

import net.minecraft.resources.ResourceLocation;
import slimeknights.mantle.client.book.data.BookData;
import slimeknights.mantle.client.book.data.PageData;
import slimeknights.mantle.client.book.data.SectionData;
import slimeknights.mantle.client.book.data.content.PageContent;
import slimeknights.mantle.client.book.repository.BookRepository;
import slimeknights.mantle.client.book.transformer.SectionTransformer;
import slimeknights.mantle.client.screen.book.element.ItemElement;
Expand All @@ -16,6 +18,8 @@

import java.util.List;
import java.util.ListIterator;
import java.util.function.Function;
import java.util.function.Predicate;

public abstract class AbstractMaterialSectionTransformer extends SectionTransformer {

Expand Down Expand Up @@ -43,24 +47,50 @@ protected ContentMaterial getPageContent(MaterialVariantId material) {

@Override
public void transform(BookData book, SectionData sectionData) {
createPages(book, sectionData, this::isValidMaterial, this::getPageContent);
}

/** Helper to add a page to the section */
private static PageData addPageStatic(SectionData data, String name, ResourceLocation type, PageContent content) {
PageData page = new PageData(true);
page.source = data.source;
page.parent = data;
page.name = name;
page.type = type;
page.content = content;
page.load();

data.pages.add(page);

return page;
}

/**
* Creates all the pages for the materials
* @param book Book data
* @param sectionData Section data
* @param validMaterial Predicate to validate materials
* @param pageCreator Logic to create a page
*/
public static void createPages(BookData book, SectionData sectionData, Predicate<IMaterial> validMaterial, Function<MaterialVariantId, ContentMaterial> pageCreator) {
sectionData.source = BookRepository.DUMMY;
sectionData.parent = book;

List<IMaterial> materialList = MaterialRegistry.getMaterials().stream().filter(this::isValidMaterial).toList();
List<IMaterial> materialList = MaterialRegistry.getMaterials().stream().filter(validMaterial).toList();
if (materialList.isEmpty()) {
return;
}

// calculate pages needed
List<ContentPageIconList> listPages = ContentPageIconList.getPagesNeededForItemCount(materialList.size(), sectionData, book.translate(this.sectionName), book.strings.get(String.format("%s.subtext", this.sectionName)));
List<ContentPageIconList> listPages = ContentPageIconList.getPagesNeededForItemCount(materialList.size(), sectionData, book.translate(sectionData.name), book.strings.get(String.format("%s.subtext", sectionData.name)));

ListIterator<ContentPageIconList> iter = listPages.listIterator();
ContentPageIconList overview = iter.next();

for (IMaterial material : materialList) {
MaterialId materialId = material.getIdentifier();
ContentMaterial contentMaterial = this.getPageContent(materialId);
PageData page = this.addPage(sectionData, materialId.toString(), ContentMaterial.ID, contentMaterial);
ContentMaterial contentMaterial = pageCreator.apply(materialId);
PageData page = addPageStatic(sectionData, materialId.toString(), ContentMaterial.ID, contentMaterial);

SizedBookElement icon = new ItemElement(0, 0, 1f, contentMaterial.getDisplayStacks());
while (!overview.addLink(icon, contentMaterial.getTitleComponent(), page)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package slimeknights.tconstruct.library.client.book.sectiontransformer.materials;

import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import slimeknights.mantle.client.book.data.BookData;
import slimeknights.mantle.client.book.data.SectionData;
import slimeknights.mantle.client.book.transformer.BookTransformer;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.library.client.book.content.ContentMaterial;
import slimeknights.tconstruct.library.materials.MaterialRegistry;
import slimeknights.tconstruct.library.materials.definition.IMaterial;
import slimeknights.tconstruct.library.materials.stats.IMaterialStats;
import slimeknights.tconstruct.library.materials.stats.MaterialStatsId;
import slimeknights.tconstruct.tools.stats.ExtraMaterialStats;
import slimeknights.tconstruct.tools.stats.HandleMaterialStats;
import slimeknights.tconstruct.tools.stats.HeadMaterialStats;

import java.util.Set;
import java.util.function.Predicate;

/**
* Section transformer to show a range of materials tiers in the book
*/
public class TierRangeMaterialSectionTransformer extends BookTransformer {
private static final Set<MaterialStatsId> VISIBLE_STATS = ImmutableSet.of(HeadMaterialStats.ID, HandleMaterialStats.ID, ExtraMaterialStats.ID);
private static final ResourceLocation KEY = TConstruct.getResource("material_tier");

public static final TierRangeMaterialSectionTransformer INSTANCE = new TierRangeMaterialSectionTransformer();

@Override
public void transform(BookData book) {
for (SectionData section : book.sections) {
JsonElement json = section.extraData.get(KEY);
if (json != null) {
try {
int min, max;
boolean detailed;
if (json.isJsonPrimitive()) {
min = json.getAsInt();
max = min;
detailed = false;
} else if (json.isJsonObject()) {
JsonObject jsonObject = json.getAsJsonObject();
if (jsonObject.has("tier")) {
min = GsonHelper.getAsInt(jsonObject, "tier");
max = min;
} else {
min = GsonHelper.getAsInt(jsonObject, "min", 0);
max = GsonHelper.getAsInt(jsonObject, "max", Integer.MAX_VALUE);
}
detailed = GsonHelper.getAsBoolean(jsonObject, "detailed", false);
} else {
throw new JsonSyntaxException("Invalid tconstruct:material_tier, expected number or JSON object");
}
AbstractMaterialSectionTransformer.createPages(book, section, new ValidMaterial(VISIBLE_STATS, min, max), id -> new ContentMaterial(id, detailed));
} catch (JsonSyntaxException e) {
TConstruct.LOG.error("Failed to parse material tier section data", e);
}
}
}
}

/** Helper to create a material predicate */
public record ValidMaterial(Set<MaterialStatsId> visibleStats, int min, int max) implements Predicate<IMaterial> {
@Override
public boolean test(IMaterial material) {
int tier = material.getTier();
if (tier < min || tier > max) {
return false;
}
// only show material stats for types with the proper stat types, as otherwise the page will be empty
// if you want to show another stat type, just override this method/implement the parent class
for (IMaterialStats stats : MaterialRegistry.getInstance().getAllStats(material.getIdentifier())) {
if (visibleStats.contains(stats.getIdentifier())) {
return true;
}
}
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@

import java.util.Set;

/** Material section transformer for a given tier and material set */
/** @deprecated use {@link TierRangeMaterialSectionTransformer} */
@Deprecated
public class TieredMaterialSectionTransformer extends AbstractMaterialSectionTransformer {
private static final Set<MaterialStatsId> VISIBLE_STATS = ImmutableSet.of(HeadMaterialStats.ID, HandleMaterialStats.ID, ExtraMaterialStats.ID);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ tools.group_small=Small Tools
tools.group_large=Broad Tools
armor=Armor

tier_one_materials=Tier 1 Materials
tier_one_materials.subtext=These materials are easy to find, and can be placed in the part builder to create tool parts
tier_two_materials=Tier 2 Materials
tier_two_materials.subtext=These materials require melting and casting to create, and may be a bit more rare
tier_three_materials=Tier 3 Materials
tier_three_materials.subtext=These materials require alloying, either through an alloyer or a smeltery
tier_four_materials=Tier 4 Materials
tier_four_materials.subtext=These materials cannot be found without traveling to the Nether
materials_1=Tier 1 Materials
materials_1.subtext=These materials are easy to find, and can be placed in the part builder to create tool parts
materials_2=Tier 2 Materials
materials_2.subtext=These materials require melting and casting to create, and may be a bit more rare
materials_3=Tier 3 Materials
materials_3.subtext=These materials require alloying, either through an alloyer or a smeltery
materials_4=Tier 4 Materials
materials_4.subtext=These materials cannot be found without traveling to the Nether
skull_materials=Slimeskulls
skull_materials.subtext=This section describes the effects of all types of skulls in creating a slimeskull

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,31 +42,35 @@
}
},
{
"name": "tier_one_materials",
"name": "materials_1",
"extraData": { "tconstruct:material_tier": { "tier": 1, "detailed": true }},
"requirements": [ "tconstruct:tools/materials_and_you" ],
"hideWhenLocked": true,
"icon": {
"item": "minecraft:stone"
}
},
{
"name": "tier_two_materials",
"name": "materials_2",
"extraData": { "tconstruct:material_tier": { "tier": 2, "detailed": true }},
"requirements": [ "tconstruct:smeltery/puny_smelting" ],
"hideWhenLocked": true,
"icon": {
"item": "minecraft:iron_ingot"
}
},
{
"name": "tier_three_materials",
"name": "materials_3",
"extraData": { "tconstruct:material_tier": { "tier": 3, "detailed": true }},
"requirements": [ "tconstruct:smeltery/mighty_smelting" ],
"hideWhenLocked": true,
"icon": {
"item": "tconstruct:slimesteel_ingot"
}
},
{
"name": "tier_four_materials",
"name": "materials_4",
"extraData": { "tconstruct:material_tier": { "tier": 4, "detailed": true }},
"requirements": [ "tconstruct:foundry/fantastic_foundry" ],
"hideWhenLocked": true,
"icon": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ small_tools=작은 도구
large_tools=넓은 도구
armor=갑옷

tier_one_materials=1등급 재료
tier_one_materials.subtext=재료는 도구를 만들 때 가장 중요한 요소입니다. 이러한 재료들은 부품 제작대로 가공할 수 있습니다
tier_two_materials=2등급 재료
tier_two_materials.subtext=이러한 재료들은 용해와 주조로 가공할 수 있습니다
tier_three_materials=3등급 재료
tier_three_materials.subtext=이러한 재료들은 합금기나 제련소로 금속을 합쳐서 가공할 수 있습니다
tier_four_materials=4등급 재료
tier_four_materials.subtext=이러한 재료들은 네더를 여행해야 가공할 수 있습니다
materials_1=1등급 재료
materials_1.subtext=재료는 도구를 만들 때 가장 중요한 요소입니다. 이러한 재료들은 부품 제작대로 가공할 수 있습니다
materials_2=2등급 재료
materials_2.subtext=이러한 재료들은 용해와 주조로 가공할 수 있습니다
materials_3=3등급 재료
materials_3.subtext=이러한 재료들은 합금기나 제련소로 금속을 합쳐서 가공할 수 있습니다
materials_4=4등급 재료
materials_4.subtext=이러한 재료들은 네더를 여행해야 가공할 수 있습니다
skull_materials=슬라임머리
skull_materials.subtext=여기에서는 슬라임머리에 사용할 수 있는 모든 종류의 머리 효과를 설명합니다

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ small_tools=Ferramentas Pequenas
large_tools=Ferramentas Grandes
armor=Armadura

tier_one_materials=Materiais Nivel 1
tier_one_materials.subtext=Estes materiais são fáceis de encontrar, e podem ser colocados no montador de peças para criar peças de ferramentas
tier_two_materials=Materiais Nivel 2
tier_two_materials.subtext=Estes materiais requerem fundição e moldagem para sua fabricação, e podem ser um pouco mais raros
tier_three_materials=Materiais Nivel 3
tier_three_materials.subtext=Estes materiais requerem ligas, seja através de um fundidor de ligas ou de uma fundição
tier_four_materials=Materiais Nivel 4
tier_four_materials.subtext=Estes materiais não podem ser encontrados sem viajar para o Nether
materials_1=Materiais Nivel 1
materials_1.subtext=Estes materiais são fáceis de encontrar, e podem ser colocados no montador de peças para criar peças de ferramentas
materials_2=Materiais Nivel 2
materials_2.subtext=Estes materiais requerem fundição e moldagem para sua fabricação, e podem ser um pouco mais raros
materials_3=Materiais Nivel 3
materials_3.subtext=Estes materiais requerem ligas, seja através de um fundidor de ligas ou de uma fundição
materials_4=Materiais Nivel 4
materials_4.subtext=Estes materiais não podem ser encontrados sem viajar para o Nether
skull_materials=Slimeskulls
skull_materials.subtext=Este capitulo descreve os efeitos de todos os tipos de caveiras na criação de um slimeskull

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Sections
intro=Introduction

small_tools=Малые инструменты
Expand All @@ -9,17 +8,17 @@ large_tools.info=Информация об инструментах
armor=Броня
armor.info=Информация о броне

tier_one_materials=Материалы 1-го уровня
tier_one_materials.subtext=Эти материалы легко найти, и их можно поместить в формирователь частей для создания частей инструментов
materials_1=Материалы 1-го уровня
materials_1.subtext=Эти материалы легко найти, и их можно поместить в формирователь частей для создания частей инструментов

tier_two_materials=Материалы 2-го уровня
tier_two_materials.subtext=Эти материалы требуют плавки и литья для создания, и могут быть немного более редкими
materials_2=Материалы 2-го уровня
materials_2.subtext=Эти материалы требуют плавки и литья для создания, и могут быть немного более редкими

tier_three_materials=Материалы 3-го уровня
tier_three_materials.subtext=Эти материалы создаются смешиванием, либо в смешивателе или в плавильне
materials_3=Материалы 3-го уровня
materials_3.subtext=Эти материалы создаются смешиванием, либо в смешивателе или в плавильне

tier_four_materials=Материалы 4-го уровня
tier_four_materials.subtext=Эти материалы невозможно найти без путешествия в Незер
materials_4=Материалы 4-го уровня
materials_4.subtext=Эти материалы невозможно найти без путешествия в Незер
skull_materials=Слизечерепа
skull_materials.subtext=В этом разделе описаные все эффекты, которые имеют слизечерепа после создания

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ tools.group_small=小型工具
tools.group_large=宽型工具
armor=盔甲

tier_one_materials=一级材料
tier_one_materials.subtext=这些材料都十分常见,并且可以直接在部件制造台上打造成工具部件。
tier_two_materials=二级材料
tier_two_materials.subtext=这些材料并不那么常见,并且需要进行熔融和铸造才能制成工具部件。
tier_three_materials=三级材料
tier_three_materials.subtext=这些材料需要通过合金来获得。你可以用焦褐合金炉或冶炼炉进行合金。
tier_four_materials=四级材料
tier_four_materials.subtext=这些材料必须前往下界才能获得。
materials_1=一级材料
materials_1.subtext=这些材料都十分常见,并且可以直接在部件制造台上打造成工具部件。
materials_2=二级材料
materials_2.subtext=这些材料并不那么常见,并且需要进行熔融和铸造才能制成工具部件。
materials_3=三级材料
materials_3.subtext=这些材料需要通过合金来获得。你可以用焦褐合金炉或冶炼炉进行合金。
materials_4=四级材料
materials_4.subtext=这些材料必须前往下界才能获得。
skull_materials=黏液头颅
skull_materials.subtext=本章节介绍了所有类型的头颅制成的黏液头颅的效果。

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ blazing_blood=Blazing Blood
armor=Plate Armor
armor.subtext=Armor is crafted in the Crafting Station instead of the Tinker Station or Anvil. The mighty plate armor boasts a high defense, but less modifiability. Who needs extra features when you can be protected?

tier_four_materials=Tier 4 Materials
tier_four_materials.subtext=Materials which require blazing blood to craft.
materials=Tier 4 Materials
materials.subtext=Materials which require blazing blood to craft.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
}
},
{
"name": "tier_four_materials",
"name": "materials",
"extraData": { "tconstruct:material_tier": 4 },
"icon": {
"item": "tconstruct:manyullyn_ingot"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ blazing_blood=불타오르는 피
armor=판금 갑옷
armor.subtext=판금 갑옷은 제작대 대신에 팅커 작업대나 모루를 사용하여 제작할 수 있습니다! 강력한 판금 갑옷은 높은 방어력을 자랑하지만, 변형성이 떨어집니다. 안전히 보호할 수 있는데, 추가 기능까지 필요한가요?

tier_four_materials=4등급 재료
tier_four_materials.subtext=불타오르는 피가 필요한 재료입니다.
materials=4등급 재료
materials.subtext=불타오르는 피가 필요한 재료입니다.
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ blazing_blood=Sangue de Blaze
armor=Armadura de Placas
armor.subtext=A armadura é fabricada na Estação de Fabricação ao invés da Estação Tinker ou da Bigorna. A poderosa armadura de placa ostenta uma alta defesa, porém é menos modificável. Quem precisa de recursos extras quando você esta protegido por uma armadura de placas?

tier_four_materials=Materiais Nivel 4
tier_four_materials.subtext=Materiais que requerem sangue de blaze para sua fabricação
materials=Materiais Nivel 4
materials.subtext=Materiais que requerem sangue de blaze para sua fabricação

0 comments on commit 18cc46f

Please sign in to comment.