Jump to content

Limit frame rate code-side only


Oen44

Recommended Posts

Hi,

I've made fading and floating text effect like this:

38622211_439668059856433_3442053363007488000_n.gif.513a2bdafc4d7c5f09fd2ab4c0fb68ba.gif

It's cool, I like how it ended up but... There is framerate issue. When making this, I was at 75FPS cap (VSync) and after unlocking to unlimited FPS, text started moving way too fast.

Here is the code

@SubscribeEvent
public void onRenderOverlayText(RenderGameOverlayEvent.Text event) {
	ScaledResolution sr = event.getResolution();
	EntityPlayer player = Minecraft.getMinecraft().player;
  
	GL11.glPushMatrix();
	GL11.glScalef(1.0F, 1.0F, 1.0F);

	for (int i = 0; i < 12; i++) {
		if (!this.isVisible(i))
			continue;

		this.alpha[i] -= 3;

		this.height[i] += 0.6f;
		if (this.height[i] > 50.0f) {
			this.hide(i);
			continue;
		}

		Minecraft.getMinecraft().fontRenderer.drawStringWithShadow("+" + this.xp[i] + " XP",
				sr.getScaledWidth() / 2 + 50, sr.getScaledHeight() / 2 - this.height[i],
				0xFFFFFF | (this.alpha[i] << 24));

		GL11.glScalef(0.5f, 0.5f, 0.5f);
		Minecraft.getMinecraft().renderEngine.bindTexture(icon);
		this.drawTexturedModalRect((sr.getScaledWidth() / 2 + 32) * 2,
				((sr.getScaledHeight() / 2) - 5 - this.height[i]) * 2, i * 32, (i > 7 ? 1 : 0) * 32, 32, 32);
	}

	GL11.glPopMatrix();
}

 

Is there any way to make this run at same pace? Like deltaTime?

Edited by Oen44
Link to comment
Share on other sites

6 minutes ago, Oen44 said:

this.height[i] += 0.6f;

You need to multiply this value by the deltaTime between frames (after dividing out the deltaTime at 75 fps).

I'm not sure where you'd get that value, though.

  • Like 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

long oldTime = newTime;
long newTime = Minecraft.getMinecraft().getSystemTime();
long deltaTime = newTime - oldTime;

deltaTime ready.

this.alpha[i] -= 0.3 * deltaTime;
this.height[i] += 0.06f * deltaTime;

Calculations ready.

 

Working perfectly :)

Link to comment
Share on other sites

Doing your own delta time works, but there is another more common approach which I figured is worth mentioning. The game logic runs in a loop that "ticks" 20 frames per second. The render refresh rate can vary depending on your monitor, settings and power of your GPU.

 

So whenever you're doing animations in Minecraft you should set the positions and angles based on the game ticks, not the refresh rate. So you would really increment the position every tick rather than every event (which fires at the refresh rate). However, doing that has the side effect that it will look a bit jerky because it will only update position 20 times per second which is a bit less than needed for perception of smooth motion (traditional movie film used 24 fps). So to smooth it out, there is the concept of "partial ticks" that are passed to the rendering methods (and events).

 

So an alternative, arguably more common, way to do animations is to update the position using the ticks plus a bit of adjustment using the partial tick. For example, the game overlay event has a getPartialTicks() method to help with this.

 

Just thought you'd be interested. Point is that partial ticks are used to communicate difference between refresh rate and tick rate and are commonly used to control animation speed.

  • Like 1

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

Link to comment
Share on other sites

14 minutes ago, jabelar said:

Doing your own delta time works, but there is another more common approach which I figured is worth mentioning. The game logic runs in a loop that "ticks" 20 frames per second. The render refresh rate can vary depending on your monitor, settings and power of your GPU.

 

So whenever you're doing animations in Minecraft you should set the positions and angles based on the game ticks, not the refresh rate. So you would really increment the position every tick rather than every event (which fires at the refresh rate). However, doing that has the side effect that it will look a bit jerky because it will only update position 20 times per second which is a bit less than needed for perception of smooth motion (traditional movie film used 24 fps). So to smooth it out, there is the concept of "partial ticks" that are passed to the rendering methods (and events).

 

So an alternative, arguably more common, way to do animations is to update the position using the ticks plus a bit of adjustment using the partial tick. For example, the game overlay event has a getPartialTicks() method to help with this.

 

Just thought you'd be interested. Point is that partial ticks are used to communicate difference between refresh rate and tick rate and are commonly used to control animation speed.

So how ticks work compared to deltaTime?

Lower FPS (30):

Ticks - text is adapting to FPS and moves slow - not cool

Delta - text is smooth as for such low FPS and stays the same time as with high FPS - what I want

 

Higher FPS (around 600):

Ticks - text is smooth and very fast, again, adapting to FPS - not cool

Delta - text is smooth, perfect pace - what I want

 

Conclusion? Ticks are not good for that kind of animations.

Edited by Oen44
Link to comment
Share on other sites

10 minutes ago, Oen44 said:

That doesn't change anything. Ticks are not helpful here, it's just looking bad.

Since they happen at a set period of time after each other the game has a deltaTime(partialTicks) variable between each tick that is used for rendering things smoothly. So the game would update the position as to where it should be every tick and then render at that position with the partialTicks. Though your way of doing it works this is just the way minecraft handles these things.

  • Like 1

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

1 hour ago, diesieben07 said:

If it looks bad, then you are doing something wrong.

All I did was

this.alpha[i] -= (int) (0.4f * event.getPartialTicks());
this.height[i] += 0.1f * event.getPartialTicks();

And it's very slow on low FPS and getting faster with more FPS.

 

1 hour ago, diesieben07 said:

It is a very simple process:


float currentValue = 0
float prevValue = 0

tick() { // 20 times a second, always, that's what ticks are
    prevValue = currentValue;
    currentValue = (currentValue + 1) % 100;
}

render(float partialTicks) {
    float actual = prevValue + (currentValue - prevValue) * partialTicks;
    // render at position actual
}

Yeah, no idea where to put prevValue and currentValue. Should I make thread like this?

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    prevValue = currentValue;
    currentValue = (currentValue + 1) % 100;
  }
}, 0, 20, TimeUnit.SECONDS);

 

I just want to check how is that going to look like with what you wrote.

The thing is that RenderGameOverlayEvent is executed more times based on FPS so deltaTime is doing something to balance and it's easy to accomplish.

Edited by Oen44
Link to comment
Share on other sites

Maybe this would be clearer. 

 

In a tick handling event like ClientTickEvent, in one phase of that event, you would update the position in a public static field. This would have a very regular steady movement.

 

In the render handling event, you would get the position from that public static field and add a multiple of the partial ticks times the increment. 

 

Note that the tick value can be also updated in other ways. For example, the world keeps track of total time, so you could record the world time when the GUI was just opened and then calculate how many ticks it was open in the render event. 

 

I didn't mean to cause confusion. Just wanted to point out the way Minecraft normally handles the conversion from ticks to render frames for animations.

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

Link to comment
Share on other sites

15 minutes ago, diesieben07 said:

RenderGameOverlayEvent (careful: this fires many many times every frame!) is the render part in my code. You would need ClientTickEvent (check TickEvent#phase or your code will run twice per tick) for the tick part. 

Of course there is TickEvent... I should have think about that before, ohh my.

 

float prevValue;
float currentValue;

@SubscribeEvent
public void onClientTick(ClientTickEvent event) {
	if(event.phase == Phase.END) {
		prevValue = currentValue;
		currentValue = (currentValue + 1) % 100;
	}
}

float actual = prevValue + (currentValue - prevValue) * event.getPartialTicks(); // in RenderGameOverlayEvent.Text

Well... It's not working well. It's starting slow and then goes very fast and then slow again and so on (because of modulo i guess).

Edited by Oen44
Link to comment
Share on other sites

Not quite. If you assign previous value to current value, the increase current value and take modulo, then every once in a while the prev value is going to be way higher. Basically the previous value will roll over to zero one tick after the current value. 

 

What it should be is more like this:

- forget the previous value, you just need current value. So start current value at zero, and keep your line where you add one and do modulo. So current value is going to cycle from 0 to 99 over and over.

- just add partial ticks to current value. That will give the total number of ticks (the current value has the whole number of ticks, plus the partial ticks).

- multiply that result by whatever speed you want.

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

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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Add crash-reports with sites like https://paste.ee/ Maybe an issue with blur, essentials or cumulus_menus
    • Add the crash-report or latest.log (logs-folder) with sites like https://paste.ee/ and paste the link to it here  
    • I have a problem, I am trying to put two different effects to two different armors but when I run it only the emerald armor effect works. This is the code public class ModArmorItem extends ArmorItem{ private static final Map<ArmorMaterial, MobEffectInstance> MATERIAL_TO_EFFECT_MAP = (new ImmutableMap.Builder<ArmorMaterial, MobEffectInstance>()) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE,200, 1,false,false, true)) .put(ModArmorMaterials.OBSIDIAN, new MobEffectInstance(MobEffects.FIRE_RESISTANCE,200, 1,false,false, true)).build(); public ModArmorItem(ArmorMaterial pMaterial, Type pType, Properties pProperties) { super(pMaterial, pType, pProperties); } @Override public void onArmorTick(ItemStack stack, Level world, Player player){ if (!world.isClientSide()) { if (hasFullSuitOfArmorOn(player)) { evaluateArmorEffects(player); } } } private void evaluateArmorEffects(Player player) { for (Map.Entry<ArmorMaterial,MobEffectInstance> entry : MATERIAL_TO_EFFECT_MAP.entrySet()){ ArmorMaterial mapArmorMaterial = entry.getKey(); MobEffectInstance mapStatusEffect = entry.getValue(); if (hasCorrectArmorOn(mapArmorMaterial, player)) { addStatusEffectForMaterial(player, mapArmorMaterial, mapStatusEffect); } } } private void addStatusEffectForMaterial(Player player, ArmorMaterial mapArmorMaterial, MobEffectInstance mapStatusEffect) { boolean hasPlayerEffect = player.hasEffect(mapStatusEffect.getEffect()); if (hasCorrectArmorOn(mapArmorMaterial, player) && !hasPlayerEffect) { player.addEffect(new MobEffectInstance(mapStatusEffect)); } } private boolean hasCorrectArmorOn(ArmorMaterial material, Player player) { for (ItemStack armorStack : player.getInventory().armor){ if (!(armorStack.getItem() instanceof ArmorItem)) { return false; } } ArmorItem helmet = ((ArmorItem)player.getInventory().getArmor(3).getItem()); ArmorItem breastplace = ((ArmorItem)player.getInventory().getArmor(2).getItem()); ArmorItem leggins = ((ArmorItem)player.getInventory().getArmor(1).getItem()); ArmorItem boots = ((ArmorItem)player.getInventory().getArmor(0).getItem()); return helmet.getMaterial() == material && breastplace.getMaterial() == material && leggins.getMaterial() == material && boots.getMaterial() == material; } private boolean hasFullSuitOfArmorOn(Player player){ ItemStack helmet = player.getInventory().getArmor(3); ItemStack breastplace = player.getInventory().getArmor(2); ItemStack leggins = player.getInventory().getArmor(1); ItemStack boots = player.getInventory().getArmor(0); return !helmet.isEmpty() && !breastplace.isEmpty() && !leggins.isEmpty() && !boots.isEmpty(); } } Also when I place two effects on the same armor, the game crashes. Here is the crash file. The code is the same, only this part is different   private static final Map<ArmorMaterial, MobEffectInstance> MATERIAL_TO_EFFECT_MAP = (new ImmutableMap.Builder<ArmorMaterial, MobEffectInstance>()) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.HERO_OF_THE_VILLAGE,200, 1,false,false, true)) .put(ModArmorMaterials.EMERALD, new MobEffectInstance(MobEffects.FIRE_RESISTANCE,200, 1,false,false, true)).build(); I hope you guys can help me. Thanks.
  • Topics

×
×
  • Create New...

Important Information

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