Jump to content

Recommended Posts

Posted

Do any of our illustrious moderators or fellow modders have some basic suggestions on performance optimizations? Especially when it comes to particularly sensitive areas such as Structure Generation, Player Tick, and other Event Handlers, onUpdates in Items/Blocks. Basically, a list of common mistakes to avoid. Seems like something that many modders could benefit from.

 

 

Posted

Just don't create any excessive loops or large frequent packet movement. 

 

If you do have to do something really big you can jump out of the thread and back in, but you really need to know what you are doing and understand things or it will go poorly.

 

 

Long time Bukkit & Forge Programmer

Happy to try and help

Posted

Ok, getting more specific:

 

@delpi, I don't have many packets, but I do have lots of loops.

@diesieben07, my mod appears to be causing some Block Lag for users when running on a Cauldron Server in a large modpack with high usage. Never been in this position before, so trying to identify the source.

 

I will focus on streamlining some of the loops in the handlers as a first effort. I'm using several handlers and several events:

 

LivingUpdateEvent

LivingHurtEvent (several here)

BreakSpeed

HarvestDropsEvent

LivingDropsEvent

 

And a few other minor events, which are only called occasionally. If I learn anything, will post it back here.

 

 

Posted

your blocks are regular blocks? tile_entities?  or do you have a really big resolution on your block texture?

Long time Bukkit & Forge Programmer

Happy to try and help

Posted

your blocks are regular blocks? tile_entities?  or do you have a really big resolution on your block texture?

 

Very few blocks. And they only spawn in the four dungeons. No tile entities and block texture is small. The mod is all about the items.

Posted

It would be much, much better if you would just post those (in question) parts of code and say what is expected outcome.

We might be able to tell you - what to not do, or maybe a better way.

1.7.10 is no longer supported by forge, you are on your own.

Posted

You can actually time the various parts of the code that you suspect using something like this:

 

final long startTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
  // Do something
}
final long endTime = System.currentTimeMillis();

System.out.println("Total execution time: " + (endTime - startTime) );

 

A Minecraft tick is 1/20th of a second which is 50 milliseconds, and usually the code should finish before that (otherwise you'll see lag). So anything over 1 millisecond can start to be considered significant.

 

You can get more precision us9ing System.nanoTime() but in some cases it might have trouble on multi-threaded situations.

 

Anyway, with such an approach you can actually time your code and determine what is taking significant time and furthermore prove to yourself that your attempts to fix it are working.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

It would be much, much better if you would just post those (in question) parts of code and say what is expected outcome.

We might be able to tell you - what to not do, or maybe a better way.

 

Sure. Here's a typical example in my PlayerTickHandler. The structure is repeated several times (for several different items) within other Handlers and within the ItemUpdate. This is the only way I've found to get it to work (verifying if the item is in the hotbar first using a loop, and then acting upon it).

 

if (event.entity instanceof EntityPlayer) {

 

EntityPlayer entityplayer = (EntityPlayer) event.entity;

for(int i = 0; i <= 8; i++)

{

ItemStack itemchk = entityplayer.inventory.getStackInSlot(i);

if (itemchk != null && itemchk.getItem() == InventoryPets.petSpider && itemchk.getItemDamage() == 0) {

 

//do magic stuff

 

break;

}

}

 

 

First question: Is there a more efficient way to verify the existence of an item in the hotbar? It seems a waste to constantly check the hotbar using a loop.

Second question: For PlayerTickHandler, would it be more efficient to put a check of the entire hotbar first for any Items up front, and then execute on a case by case basis depending on what items are found, instead of checking one by one? (Just thought of this...)

 

For the record, the PlayerTickHandler is only used where absolutely necessary, most abilities/effects are handled in Item onUpdate.

 

Posted

onUpdate in your Item class will be called every tick as long as the Item is in a player's inventory... But you already seem to know that.

 

Yes... but I could put in a counter and have it check less frequently for the items that don't need constant attention. I'll test on a couple of items and see what it saves in cycles. Thx.

Posted

You are not going to bog down the minecraft tick with checking a 0-8 list unless you are doing it thousands and thousands of time a tick.

 

 

Long time Bukkit & Forge Programmer

Happy to try and help

Posted

You are not going to bog down the minecraft tick with checking a 0-8 list unless you are doing it thousands and thousands of time a tick.

 

Perfect. Yeah, not seeing any more gains here, using Jabelar's tester. Once per pet in inventory, per tick. Worst case scenario, that's likely several hundred on the server mentioned.

 

Ok, maybe I was too quick to dismiss the 'packet' discussion. What about NBT Data? Right now, my achievement system leverages NBT Data and is checking (and then storing) NBT Data every tick for every item in onUpdate. Could this be a contributor? Here's what I'm going to do, regardless:

 

- Only have it check every 20 ticks

- Read only to check and then only store if something has changed (duh)

 

 

Posted

Hold on. "my achievement system" - so where are you running this?

 

Achievements are one-time events which should be operated kinda like:

* You do something

* You get it

* You save it

* You read it

 

Why ticking-checks? (you said you have them somewhere)

 

EDIT:

Also, many people seem to NOT know that - NBT are LITERALLY Map<key,value>. They are just represented that way.

And yeah - they are pretty fast.

1.7.10 is no longer supported by forge, you are on your own.

Posted

Hold on. "my achievement system" - so where are you running this?

 

Achievements are one-time events which should be operated kinda like:

* You do something

* You get it

* You save it

* You read it

 

Why ticking-checks? (you said you have them somewhere)

 

The typical Minecraft triggers didn't allow for a way for me check accurately the information I wanted for the achievements. The only reliable way I could find was through Item onUpdate, though I wasn't very efficient about it. By my 'achievement system,' I mean I needed a way to check if a user had:

- collected an item (through finding or crafting)

- collected all of the items in the same group

- collected all of the groups

- collected one item from each of the groups

- collected a certain number of items, triggers at 1, 5, 10, 20, All

 

As far as I know, there's no way to track this without using NBT Data. And it went into the Item, as onUpdate in the Item is the first time we see the item appear in an Inventory (which was what I was looking for. If you have an alternate solution, I am all ears...).

 

However, there is absolutely no reason this needs to be checked every tick. Nor stored every tick. Both of these things will be changed.

 

EDIT: Saw a decent uptick in the 'onUpdate' performance (using Jabelar's timer) by making the above change. Will definitely help overall, but will keep hunting.

 

 

 

 

 

 

Posted

Just off the top of my head, I would create extendedproperties for the player and track it all in there.

 

If you don't want to do that, use the persistent NBT tag on the player to store it.

Long time Bukkit & Forge Programmer

Happy to try and help

Posted

Just off the top of my head, I would create extendedproperties for the player and track it all in there.

 

Sorry I wasn't clear. This is exactly what I'm doing. I update extendedproperties during onUpdate in the Item.

Posted

FWIW, and for those tracking this one, here are the optimizations I found and implemented:

 

- The change to the achievement check shown above (medium gain, across all items)

- I re-organized the player tick so it had to go through fewer conditions and fewer loops (this turned out only to be a tiny gain)

- Items were checking in onUpdate every tick to see if they needed fuel. Changed this to every 20 ticks. No perceptible difference to user. (medium gain, over several items)

- One item was mistakenly looping through OreDictionary every tick in onUpdate if durability was 0. This would have only caused lag if multiple people were using it in their hotbar and the item was at 0 durability. But still. (Lex has warned me about this before, so I only have myself to blame). (small gain, when using this item only)

- Optimized loops in WorldGen structures (combining checks into one conditional) - small gain

- Removed a BreakSpeed Handler which was slow (during testing) - small gain

 

Performance is much better after these and the above optimizations. If I had to summarize, the big fixes consisted of changing checks in onUpdate: if a routine wasn't absolutely necessary to check every tick in the Item onUpdate, then I added a loop counter so it checked between 10-20 ticks instead.

 

Note that the performance problem did not surface until the mod was being put into large modpacks and played on moderately trafficked servers.

 

Will find out more after the update is published, but I am calling this one closed. Thanks to delpi, diesieben07, Ernio, and Jabelar for the ideas and assistance.

 

Edit: Added two more optimizations I had forgotten to list

Posted

I know this forum can't get enough of this topic ;) , so one more thing to add, building on Jabelar's idea above. You can use the below as your PlayerTick Handler (or just add the code to your own) and see the overall tick performance of your mod. It basically checks the system time every loop through the player tick, and shows the difference since last loop. Using this while playing the game may give you clues as to where a performance issue could be. For the most part, the number is a steady 0. If you see it spike above 1 for a few ticks in a row, it could be a clue there is something else going on. Please note, I see a regular spike every second or so, even in Vanilla, so keep that in mind. This is not definitive by any means, just something to help if you are looking.

 

Please also note, as diesieben07 pointed out, if it ain't broke, don't fix it. There's no need to go down this route unless you are seeing or hearing about problems.

 

 

public class PlayerTickHandler 
{

   private long millStore = 0;

   @SubscribeEvent
   public void onLivingUpdateEvent(LivingUpdateEvent event)
   {      
      
      System.out.println("Total loop execution time: " + (System.currentTimeMillis() - millStore) );
      millStore = System.currentTimeMillis();
   }
}

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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • After some time minecraft crashes with an error. Here is the log https://drive.google.com/file/d/1o-2R6KZaC8sxjtLaw5qj0A-GkG_SuoB5/view?usp=sharing
    • The specific issue is that items in my inventory wont stack properly. For instance, if I punch a tree down to collect wood, the first block I collected goes to my hand. So when I punch the second block of wood to collect it, it drops, but instead of stacking with the piece of wood already in my hand, it goes to the second slot in my hotbar instead. Another example is that I'll get some dirt, and then when I'm placing it down later I'll accidentally place a block where I don't want it. When I harvest it again, it doesn't go back to the stack that it came from on my hotbar, where it should have gone, but rather into my inventory. That means that if my inventory is full, then the dirt wont be picked up even though there should be space available in the stack I'm holding. The forge version I'm using is 40.3.0, for java 1.18.2. I'll leave the mods I'm using here, and I'd appreciate it if anybody can point me in the right direction in regards to figuring out how to fix this. I forgot to mention that I think it only happens on my server but I&#39;m not entirely sure. PLEASE HELP ME! LIST OF THE MODS. aaa_particles Adorn AdvancementPlaques AI-Improvements AkashicTome alexsdelight alexsmobs AmbientSounds amwplushies Animalistic another_furniture AppleSkin Aquaculture aquamirae architectury artifacts Atlas-Lib AutoLeveling AutoRegLib auudio balm betterfpsdist biggerstacks biomancy BiomesOPlenty blockui blueprint Bookshelf born_in_chaos Botania braincell BrassAmberBattleTowers brutalbosses camera CasinoCraft cfm (MrCrayfish’s Furniture Mod) chat_heads citadel cloth-config Clumps CMDCam CNB cobweb collective comforts convenientcurioscontainer cookingforblockheads coroutil CosmeticArmorReworked CozyHome CrabbersDelight crashexploitfixer crashutilities Create CreativeCore creeperoverhaul cristellib crittersandcompanions Croptopia CroptopiaAdditions CullLessLeaves curios curiouslanterns curiouslights Curses' Naturals CustomNPCs CyclopsCore dannys_expansion decocraft Decoration Mod DecorationDelightRefurbished Decorative Blocks Disenchanting DistantHorizons doubledoors DramaticDoors drippyloadingscreen durabilitytooltip dynamic-fps dynamiclights DynamicTrees DynamicTreesBOP DynamicTreesPlus Easy Dungeons EasyAnvils EasyMagic easy_npc eatinganimation ecologics effective_fg elevatorid embeddium emotecraft enchantlimiter EnchantmentDescriptions EnderMail engineersdecor entityculling entity_model_features entity_texture_features epicfight EvilCraft exlinefurniture expandability explosiveenhancement factory-blocks fairylights fancymenu FancyVideo FarmersDelight fast-ip-ping FastSuite ferritecore finsandtails FixMySpawnR Forge Middle Ages fossil FpsReducer2 furnish GamingDeco geckolib goblintraders goldenfood goodall H.e.b habitat harvest-with-ease hexerei hole_filler huge-structure-blocks HunterIllager iammusicplayer Iceberg illuminations immersive_paintings incubation infinitybuttons inventoryhud InventoryProfilesNext invocore ItemBorders itemzoom Jade jei (Just Enough Items) JetAndEliasArmors journeymap JRFTL justzoom kiwiboi Kobolds konkrete kotlinforforge lazydfu LegendaryTooltips libIPN lightspeed lmft lodestone LongNbtKiller LuckPerms Lucky77 MagmaMonsters malum ManyIdeasCore ManyIdeasDoors marbledsarsenal marg mcw-furniture mcw-lights mcw-paths mcw-stairs mcw-trapdoors mcw-windows meetyourfight melody memoryleakfix Mimic minecraft-comes-alive MineTraps minibosses MmmMmmMmmMmm MOAdecor (ART, BATH, COOKERY, GARDEN, HOLIDAYS, LIGHTS, SCIENCE) MobCatcher modonomicon mods_optimizer morehitboxes mowziesmobs MutantMonsters mysticalworld naturalist NaturesAura neapolitan NekosEnchantedBooks neoncraft2 nerb nifty NightConfigFixes nightlights nocube's_villagers_sell_animals NoSeeNoTick notenoughanimations obscure_api oculus oresabovediamonds otyacraftengine Paraglider Patchouli physics-mod Pillagers Gun PizzaCraft placeableitems Placebo player-animation-lib pneumaticcraft-repressurized polymorph PrettyPipes Prism projectbrazier Psychadelic-Chemistry PuzzlesLib realmrpg_imps_and_demons RecipesLibrary reeves-furniture RegionsUnexplored restrictedportals revive-me Scary_Mobs_And_Bosses selene shetiphiancore ShoulderSurfing smoothboot
    • Hi everyone, I'm currently developing a Forge 1.21 mod for Minecraft and I want to display a custom HUD overlay for a minigame. My goal: When the game starts, all players should see an item/block icon (from the base game, not a custom texture) plus its name/text in the HUD – similar to how the bossbar overlay works. The HUD should appear centered above the hotbar (or at a similar prominent spot), and update dynamically (icon and name change as the target item changes). What I've tried: I looked at many online tutorials and several GitHub repos (e.g. SeasonHUD, MiniHUD), but most of them use NeoForge or Forge versions <1.20 that provide the IGuiOverlay API (e.g. implements IGuiOverlay, RegisterGuiOverlaysEvent). In Forge 1.21, it seems that neither IGuiOverlay nor RegisterGuiOverlaysEvent exist anymore – at least, I can't import them and they are missing from the docs and code completion. I tried using RenderLevelStageEvent as a workaround but it is probably not intended for custom HUDs. I am not using NeoForge, and switching the project to NeoForge is currently not an option for me. I tried to look at the original minecraft source code to see how elements like hearts, hotbar etc are drawn on the screen but I am too new to Minecraft modding to understand. What I'm looking for: What is the correct way to add a custom HUD element (icon + text) in Forge 1.21, given that the previous overlay API is missing? Is there a new recommended event, callback, or method in Forge 1.21 for custom HUD overlays, or is everyone just using a workaround? Is there a minimal open-source example repo for Forge 1.21 that demonstrates a working HUD overlay without relying on NeoForge or deprecated Forge APIs? My ideal solution: Centered HUD element with an in-game item/block icon (from the base game's assets, e.g. a diamond or any ItemStack / Item) and its name as text, with a transparent background rectangle. It should be visible to the players when the mini game is running. Easy to update the item (e.g. static variable or other method), so it can change dynamically during the game. Any help, code snippets, or up-to-date references would be really appreciated! If this is simply not possible right now in Forge 1.21, it would also help to know that for sure. Thank you very much in advance!
    • The simple answer is there is not an easy way. You would need to know how to program in Java, as well as at least some familiarity with how Forge works so you could port the differences. You would also need the sourcecode for the original mod, and permission from the author to modify it, if they did not use some sort of open source license. So it's not impossible, but it would take some effort, but doing so would open up a whole new world of possibilities for you!
  • Topics

×
×
  • Create New...

Important Information

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