Jump to content

[1.15.2] Custom Model Loader


immortalmice

Recommended Posts

What I need, is a custom itemstack texture present base on some information(Currently I save these information in CompoundNBT).

These information decide and pick several textures and I need to combine them just like what vanilla "layer#" do.

These information isn't and won't be a float, so vanilla itemoverride can't solve it.

 

I'm searching a way to solve it for several days, but I got stuck in something due to leak tutorial of this kind of things.

I already read this intro to advance models in forge wesite, but it's hard to understand because I can't find things like IModel, ICustomModelLoader in this version.(But I found something like them)

And I tried hard to read DynamicBucketModel and write my code, but now I'm stuck in loading picture to Material, which I can get TextureAtlasSprite to construct a BakedModel.

 

What I already done/tried/planed:

 

I defined a new IModelLoader called MealModelLoader

public enum MealModelLoader implements IModelLoader<MealModel>{
	INSTANCE;

	@Override
	public void onResourceManagerReload(IResourceManager resourceManager){
			
	}

	@Override
	public MealModel read(JsonDeserializationContext deserializationContext, JsonObject modelContents){
		System.out.println(modelContents);

		String pathName = modelContents.has("path_name") ? modelContents.get("path_name").getAsString() : "";
		String baseFilePath = modelContents.has("base") ? modelContents.get("base").getAsString() : "";
		JsonArray parts = modelContents.has("part") ? modelContents.get("part").getAsJsonArray() : new JsonArray();
		//TODO
		return new MealModel(pathName, baseFilePath, parts);
	}
}

It return a MealModel which implement IModelGeometry<MealModel> (I'll talk about MealBakedModel which return in bake method later.)

public class MealModel implements IModelGeometry<MealModel>{
	private String pathName, baseFilePath;
	private JsonArray parts;

	public MealModel(String pathNameIn, String baseFilePathIn, JsonArray partsIn){
		this.pathName = pathNameIn;
		this.baseFilePath = baseFilePathIn;
		this.parts = partsIn;
	}

	@Override
	public IBakedModel bake(IModelConfiguration owner, ModelBakery bakery
			, Function<Material, TextureAtlasSprite> spriteGetter, IModelTransform modelTransform
			, ItemOverrideList overrides, ResourceLocation modelLocation){

		TransformationMatrix transform = modelTransform.func_225615_b_();
		TextureAtlasSprite particle = spriteGetter.apply(owner.resolveTexture("particle"));//Just using something and make game can launch successful
		ImmutableMap<TransformType, TransformationMatrix> map = PerspectiveMapWrapper.getTransforms(modelTransform);
		// TODO
		return new MealBakedModel(ImmutableList.of(), particle, map, transform.isIdentity(), owner.isSideLit());
	}

	@Override
	public Collection<Material> getTextures(IModelConfiguration owner
		, Function<ResourceLocation, IUnbakedModel> modelGetter
		, Set<Pair<String, String>> missingTextureErrors){

		Set<Material> texs = Sets.newHashSet();

		// TODO
		return texs;
	}
	
}

And I registed my MealModelLoader using ModelLoaderRegistry in FMLClientSetupEvent.

@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event){
	Containers.registAllScreen();
	RenderHandler.setup();
	ModelLoaderRegistry.registerLoader(new ResourceLocation(FoodPower.MODID, "meal"), MealModelLoader.INSTANCE);
}

Then I write json model using this loader, and try to add some information I may need to make a model.

{
	"parent": "item/generated",
	"loader": "foodpower:meal",

	"path_name": "salad",
	"base": "foodpower:meals/salad/salad_base",
	"part": [{
		"slot": "VEGETABLE",
		"textures": {
			"cabbage": "foodpower:meals/salad/salad_cabbage",
			"tomato": "foodpower:meals/salad/salad_tomato"
		}
	}, {
		"slot": "MEAT",
		"textures": {
			"beef": "foodpower:meals/salad/salad_beef",
			"chicken": "foodpower:meals/salad/salad_chicken"
		}
	}, {
		"slot": "SEASONING",
		"textures": {
			"ketchop": "foodpower:meals/salad/salad_ketchop",
			"sauce": "foodpower:meals/salad/salad_sauce"
		}
	}]
}

Now I can successfully load these json information in MealModelLoader#read, and using them to construct a MealModel.
(Maybe it's a bad idea to pass a JsonArray to MealModel? I may change it to be a something like Map<String, Map<String, String>>).

 

I'm now stuck in MealModel#bake.

I can get the path string in json file, but how can I using this to get Material?

If I get Material, I plan to get TextureAtlasSprite using parameter spriteGetter, then pass it to my MealBakedModel, is that right?

public class MealBakedModel extends BakedItemModel{

	public MealBakedModel(ImmutableList<BakedQuad> quads, TextureAtlasSprite particle,
			ImmutableMap<TransformType, TransformationMatrix> transforms,
			boolean untransformed, boolean isSideLit){
		super(quads, particle, transforms, new MealItemOverrideList(), untransformed, isSideLit);
		// TODO
	}
}

I found a method IModelConfiguration#resolveTexture, I think it may be a key, but I don't know how to use it.

/**
  * Resolves the final texture name, taking into account texture aliases and replacements.
  * @param name The name of a texture channel.
  * @return The location of the texture, or the missing texture if not found.
  */
Material resolveTexture(String name)

What does "texture channel" mean? A folder under asset/modid/textures?

I tried pass in a lot of String including name of folder which I construct under asset/modid/textures to it, but it always return the "missing texture".

 

Finally, I define a MealItemOverrideList which extends ItemOverrideList.

Because I need method ItemOverrideList#getModelWithOverrides, I override it.

public class MealItemOverrideList extends ItemOverrideList{
	public MealItemOverrideList(){
		//TODO
	}
	@Override
	public IBakedModel getModelWithOverrides(IBakedModel model, ItemStack stack, @Nullable World worldIn, @Nullable LivingEntity entityIn){
		//TODO
		return null;
	}
}

This method pass in a ItemStack, which I can get information in CompoundNBT I stored.

Then I'll use this information to make a final MealBakedModel to return.

 

Ok, that all.

So how can I make a Material using path string in json file?

And is there anything I did/planed is wrong or a bad idea? Or it has another better way to do that.

Thanks for reading these.

Link to comment
Share on other sites

OK, now I know something more.

 

23 hours ago, immortalmice said:

I found a method IModelConfiguration#resolveTexture, I think it may be a key, but I don't know how to use it.


/**
  * Resolves the final texture name, taking into account texture aliases and replacements.
  * @param name The name of a texture channel.
  * @return The location of the texture, or the missing texture if not found.
  */
Material resolveTexture(String name)

What does "texture channel" mean? A folder under asset/modid/textures?

I tried pass in a lot of String including name of folder which I construct under asset/modid/textures to it, but it always return the "missing texture".

 

Texture channel is the thing you write under "textures" in your json file.

{
	"parent": "item/generated",
	"textures": {
		"layer0": "foodpower:blocks/juicer_top"
	},
	"loader": "foodpower:meal"
}

I pass in "layer0", it finally return a normal Material instead of missing texture. IModelConfiguration#isTexturePresent also return true.

 

But now I have another problem, if I change "layer0" to another key name, it won't work.

And I found that BlockModelConfiguration#isTexturePresent called BlockModel#isTexturePresent.

(net.minecraftforge.client.model.BlockModelConfiguration is the only one who implement IModelConfiguration)

BlockModel has its own JsonDeserializer, and call BlockModel#getTextures to construct a Map<String, Either<Material, String>> textures, and this field is used in BlockModel#isTexturePresent.

Code is here. the JsonObject passed in is the whole json file. The map it return is used in construct BlockModel and place in textures field directly.

private Map<String, Either<Material, String>> getTextures(JsonObject object) {
      ResourceLocation resourcelocation = AtlasTexture.LOCATION_BLOCKS_TEXTURE;
      Map<String, Either<Material, String>> map = Maps.newHashMap();
      if (object.has("textures")) {
         JsonObject jsonobject = JSONUtils.getJsonObject(object, "textures");

         for(Entry<String, JsonElement> entry : jsonobject.entrySet()) {
            map.put(entry.getKey(), func_228819_a_(resourcelocation, entry.getValue().getAsString()));
         }
      }

      return map;
}

 

So, I think it will take every key under textures, but it don't.

What I missed?

 

And I saw code in DynamicBucketModel#bake.

Material baseLocation = owner.resolveTexture("base");
if (MissingTextureSprite.getLocation().equals(baseLocation.func_229313_b_()))
{
   baseLocation = null;
}

Then I tried change the key name to "bake", but it didn't work too.

I really need some help. Thx.

Link to comment
Share on other sites

2 hours ago, DragonITA said:

Why not use Blockbench? Here you can create your Object and then play around with the Position, rotation, and how it will be look in the Inventory, …. Hope it help.

 

What I need is the itemstack texture depend on its nbt, nbt will store some information about what ingredient player used to make this itemstack.

For example, I may need a.png, b.png, c.png 3 picture and stack them together to display this itemstack.

But according by how player maked this itemstack, I may need to stack a.png, d.png and e.png together now.

I think it's not just a single json file can solve it.

 

Thx for reply :).

Link to comment
Share on other sites

9 hours ago, DragonITA said:

@immortalmice, sorry, i not really work with NBT Datas, and i not know it and it utility, but then it should be like a Bow, only that you use a NBT Data, no? Hope it help you.

Bow use a thing called ItemOverride, it can use key word "overrides" in json file to select a model depend on a float value.

For example, how hard is the bow pulled, where should compass point to and what time is it now(Vanilla clock).

To use your own float value, just call Item#addPropertyOverride and write the "predicate" field in the "overrides" section in json file that will be fine.

This is what vanilla bow model json file like.

{
    "parent": "item/generated",
    "textures": {
        "layer0": "item/bow"
    },
    "display": {
        //...
    },
    "overrides": [
        {
            "predicate": {
                "pulling": 1
            },
            "model": "item/bow_pulling_0"
        },
        {
            "predicate": {
                "pulling": 1,
                "pull": 0.65
            },
            "model": "item/bow_pulling_1"
        },
        {
            "predicate": {
                "pulling": 1,
                "pull": 0.9
            },
            "model": "item/bow_pulling_2"
        }
    ]
}

 

But my case is a combination of Strings, not a float.

Yes, I can map them to each float, however, a salad, the possible combination will be 3*13*5.(Salad is made with three kinds of ingredient, each kind has its possible choices)

That means I need to wirte 195 model file, I think it will make things worst and terrible.

 

Currently I planed to do, is extend ItemOverrideList to my custom MealItemOverrideList, and override ItemOverrideList#getModelWithOverrides, so that I can generate my model depend on my itemstack.

And it seems that I need to make my own model geometry, baked mode and model loader too, and I encounter a problem in IModelGeometry#bake, then this post spawn.

 

7 hours ago, The_Wabbit said:

Perhaps you can try looking at how the Culinary Construct Mod does its dynamic sandwich itemstack rendering: https://github.com/TheIllusiveC4/CulinaryConstruct.git.

HTH

Oh, thx.

1.12.2 is a lot different to 1.15.2 now, but its may be helpful to me in sometimes~ 

Edited by immortalmice
typo
Link to comment
Share on other sites

It seem that I solve my problem in someway.

 

I still don't know how IModelConfiguration#resolveTexture worked, and I can't get a Material from it now too.

But, now I found I can directly call new Material to solve my need.

I tried new Material before but it fail at that point in time, because I missed a thing.

I need to subscribe TextureStitchEvent, so that I can add my texture to AtlasTexture.

@SubscribeEvent
public static void onTextureStitch(TextureStitchEvent.Pre event){
	if(event.getMap().func_229223_g_().equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)){
		event.addSprite(new ResourceLocation(FoodPower.MODID, "meals/salad/salad_base"));
	}
}

So now directly new a Material and transform it to TextureAtlasSprite will work.

Material m = new Material(AtlasTexture.LOCATION_BLOCKS_TEXTURE, new ResourceLocation(FoodPower.MODID, "meals/salad/salad_base"));

 

Thx from everyone who replied this post.

But I still open for any better suggestion :)

Edited by immortalmice
typo
  • Like 1
Link to comment
Share on other sites

23 hours ago, DragonITA said:

Can you make a Github repo for this? I am sure that it will be help others modders, and as it was in the 1.15.2, this would really help. 

P.S.: I not understand your system, can you explain it? It looks very interesing.

Ok, here's repo. I set it public now.

https://github.com/immortalmice/FoodPower

This mod is under construction, so everything will be what I mention in README.txt.

 

My mod have many parts.

About making food, this mod has some cooking patterns, such as cake, pizza, salad...etc.

You can select a pattern to make a recipe, pattern will tell you what ingredients is necessary, and what is optional(with certain food types).

With recipe, you can follow cooking steps on it to make your food by using oven, frying pan, juicer...etc.

 

Depend on what you used in this food, after eating it will give you some buff and some special experience.

Experience will help you on cooking new meals, and most important - some special power for you in gaming minecraft.

And there some other features in this mod, so I still working hard for it :)

Edited by immortalmice
forgot giving repo link
  • Thanks 2
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.