Skip to content

Conversation

@timiimit-tam
Copy link

@timiimit-tam timiimit-tam commented Oct 14, 2025

Apologies for not opening an Issue first... Let me know if there's a better way of doing this and I can change anything.

What does the pull request do?

This PR makes it possible to change SpeedRatio and PlaybackDirection while animation is running without affecting the current animation progress. PR keeps compatibility with old behavior when speed does not change.

What is the current behavior?

When Animation.SpeedRatio or Animation.PlaybackDirection changes, the animation progress/timeline IS affected.

What is the updated/expected behavior with this PR?

When Animation.SpeedRatio or Animation.PlaybackDirection changes, the animation progress/timeline IS NOT affected.

How was the solution implemented (if it's not obvious)?

In short

When relevant properties change during a running animation, the animation's current progress is remembered and animation continues from that point on with respect to property changes.

This is all that's needed to handle a changing SpeedRatio. For PlaybackDirection, a lot more care has to be put into the logic as explained in the following subsections.

Definition of proper animation direction

Proper animation direction is the value of PlaybackDirection at first frame of the animation. In code it is indicated by _timeMovesBackwards field. PlaybackDirection.Normal and PlaybackDirection.Alternate result in positive proper animation direction, while PlaybackDirection.Reverse and PlaybackDirection.AlternateReverse result in negative proper animation direction. If PlaybackDirection changes direction some time after the first frame of animation, the animation will start playing backwards. If left running, animation will eventually reach the starting position of animation the second time.

Behavior at starting position

When animation begins playing there is nothing new to discuss, it plays as it always has. When animation reverses direction and reaches the starting position subsequently, animation will always hold value of initial keyframe (first or last keyframe depending on proper animation direction), no matter the value of FillMode.

Animations with INFINITE IterationCount will continue backwards past the starting position of the animation. This is to allow changing animation direction without affecting the infinitely repeating nature of the animation.

Animations with finite IterationCount will be clamped to the starting position and will wait for direction to change back into proper animation direction. When that happens, animation will again start playing normally the same way as it has when animation started the first time (albeit with a potentially different speed). Test Reversing_Direction_Past_Initial_Point_Clamps_To_Initial_Point has been added to check the correctnes of this behavior.

Behavior of delays

Between the starting position and ending position of animation, behavior of both Delay and DelayBetweenIterations is always the same, no matter how many times any given delay has been reached. This can be though of as delays being "baked-into" the animation. I believe this is what most people would expect and want.

The only new delay behavior is with animations where IterationCount is INFINITE. When animation plays backwards past the starting point, the DelayBetweenIterations will be played in the opposite part of the iteration time. Here is a quick/crudely drawn illustration of animation timeline to make it clearer:
image
If user wants to always have the same delay between all iterations, then both Delay and DelayBetweenIterations need to be set to the same value.

Unhandled case

Changing between Alternate and non-Alternate PlaybackDirections are not handled. This means that switching between such two modes (from Normal or Reverse to Alternate or AlternateReverse or vice versa) can result in a "jump" of current animation progress depending on when you switch it.

This could be handled in a way that kind of "does" make sense, but I don't see a reason why anyone would need to switch between these two modes.

Finally

Please review carefully in case I missed something, I wouldn't want to break animations which are probably considered a core feature.

I should also mention that I didn't do any testing of FillMode (besides what I mentioned above), I just assumed that if all UnitTests pass, then it works as expected.

Checklist

  • Added Animation Speed page to RenderDemo sample for preview
  • Added unit tests (if possible)?
  • Added XML documentation to any related classes?
  • Consider submitting a PR to https://github.com/AvaloniaUI/avalonia-docs with user documentation

Breaking changes

IterationCount.Value may no longer be greater than long.MaxValue.

Obsoletions / Deprecations

NONE

Fixed issues

Fixes #19979

@timiimit-tam timiimit-tam changed the title Preserve current Animation progress on SpeedRatio or PlaybackDirection change Preserve current Animation progress if SpeedRatio or PlaybackDirection changes Oct 16, 2025
@timiimit-tam
Copy link
Author

timiimit-tam commented Oct 16, 2025

I have cleaned up and force-pushed different commits to make it more easily reviewable.
I am unsure why Avalonia.LeakTests fails in CI, since it doesn't for me on Windows locally.
I believe IntegrationTests.Appium on Windows it not a problem, because it also fails for me locally both without and with my changes.
I am unsure whether I should add a //TODOXX: comment mentioning a breaking change.
Let me know if AnimationSpeedPage is something that's not desired.

@cla-avalonia
Copy link
Collaborator

cla-avalonia commented Oct 16, 2025

@Timotej Korda Mlakar,

Please read the following Contributor License Agreement (CLA). If you agree with the CLA, please reply with the following:

@cla-avalonia agree
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement ( “Agreement” ) is agreed to by the party signing below ( “You” ),
and conveys certain license rights to the AvaloniaUI OÜ ( “AvaloniaUI OÜ” ) for Your contributions to
AvaloniaUI OÜ open source projects. This Agreement is effective as of the latest signature date below.

1. Definitions.

“Code” means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to AvaloniaUI OÜ under this Agreement.

“Project” means any of the projects owned or managed by AvaloniaUI OÜ and offered under a license
approved by the Open Source Initiative (www.opensource.org).

“Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”

“Submission” means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.

2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.

3. Originality of Work. You represent that each of Your Submissions is entirely Your
original work. Should You wish to Submit materials that are not Your original work,
You may Submit them separately to the Project if You (a) retain all copyright and
license information that was in the materials as you received them, (b) in the
description accompanying your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any
licenses or other restrictions of which You are aware, and (c) follow any other
instructions in the Project's written guidelines concerning Submissions.

4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.

5. Licenses.

a. Copyright License. You grant AvaloniaUI OÜ, and those who receive the Submission directly
or indirectly from AvaloniaUI OÜ, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable
license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform,
and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing
rights to third parties.

b. Patent License. You grant AvaloniaUI OÜ, and those who receive the Submission directly or
indirectly from AvaloniaUI OÜ, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license
under Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.

c. Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.

6. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3 ). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6 , THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

7. Notice to AvaloniaUI OÜ. You agree to notify AvaloniaUI OÜ in writing of any facts or
circumstances of which You later become aware that would make Your representations in this
Agreement inaccurate in any respect.

8. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.

9. Governing Law/Jurisdiction. This Agreement is governed by the laws of the Republic of Estonia, and
the parties consent to exclusive jurisdiction and venue in the courts sitting in Talinn,
Estonia. The parties waive all defenses of lack of personal jurisdiction and forum non-conveniens.

10. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by AvaloniaUI OÜ.

AvaloniaUI OÜ dedicates this Contribution License Agreement to the public domain according to the Creative Commons CC0 1.

2 out of 3 committers have signed the CLA.

Timotej Korda Mlakar doesn't seem to be a GitHub user.
Please add the emails used in your commits to your Github account accordingly.

@timiimit-tam
Copy link
Author

@cla-avalonia agree

@MrJul MrJul added enhancement backport-candidate-11.3.x Consider this PR for backporting to 11.3 branch area-animations labels Oct 17, 2025
@avaloniaui-bot
Copy link

You can test this PR using the following package version. 12.0.999-cibuild0059453-alpha. (feed url: https://nuget-feed-all.avaloniaui.net/v3/index.json) [PRBUILDID]

@timiimit-tam
Copy link
Author

Hello, I would like to request a review. Should I open an Issue for a discussion about the problem that this PR fixes?

Copy link
Member

@MrJul MrJul left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your contribution!
The PR is very well described and the code clean and easy to follow.

That said, please bear with me while I review this, it's been a while since I dove into the animation code and while well written, the animation algorithm is starting to be quite complex :)

}
}

private bool IsIterationReversed(bool isAlternatingPlaybackDirection, long? iterationIndex)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: can be made static

}

// Check if normalized time needs to be reversed according to PlaybackDirection
var timeUntilIterDelay = iterDuration - iterTime;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused variables, leftover?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, leftover from ~8 iterations of logical changes. Removed now.

}

if (!_gotFirstKFValue)
private void ApplyLimitedClamp(ref long animTime, long animTimeOrigin)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused parameter animTimeOrigin

var iterTime = animTimePositive % iterDurationTotal;

bool playbackReversed;
if (animTimePositive < 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have trouble understanding this condition. By definition, animTimePositive should always be >= 0, so it's never going to be taken? If taken, this would even make iterIndex negative, messing up with the itersUntilEnd computation below.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

animTimePositive is meant to be the animation time where positive numbers are increasing in direction of proper animation direction. That said, it is negative iff animation is reversed backwards past the initial starting point.

just like animTimePositive can be negative, so can iterIndex. This does not mess up later itersUntilEnd computation. For example when iterIndex == -1, animation is 1 iteration further from the end than it was when animation started. iterIndex is exactly what is illustrated in the picture in original PR description as iter.

Since % modulo can also result in zero when used on negative values, I decrement it so that there is only a single unique iteration 0.

I have added more comments to make this part of code clearer for future readers.

_iterationCount = _animation.IterationCount.Value;
{
if (_animation.IterationCount.Value > long.MaxValue)
throw new InvalidOperationException("IterationCount value cannot be larger than long.MaxValue.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While we can certainly live with "only" long.MaxValue iterations, why the change? I see _iterationCount + 1 in DoComplete() but that can be rewritten to avoid overflow. The other usage with itersUntilEnd should always be positive as far as I understood (don't hesitate to correct me if I'm wrong).

Copy link
Author

@timiimit-tam timiimit-tam Nov 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have attempted to make _iterationCount back into ulong now that logic is more or less finalized... You are correct that itersUntilEnd is supposed to be always positive and DoComplete() can be rewritten.

But looking at

var itersUntilEnd = _iterationCount - iterIndex;

which if changed back to ulong would be ulong = ulong - long. This can underflow 1 - 2 == ulong.max which makes itersUntilEnd <= 0 false and animation would not stop. Though for this to happen the duration of iteration needs to be shorter than 1 animation frame.

Whole algorithm uses long type throughout so in general I think its best to just use it everywhere just to be on a safe side of checking all edge cases of over/under-flowing.

IMO it is fine to keep it limited to long because:

  • why in the world would anyone ever want a truly specific number higher than long.MaxValue and not INFINITE instead
  • animTime will at all times be MUCH bigger than iterIndex, so animTime will over/under-flow way before iterIndex does. Therefore animTime should break algorithm before iterIndex.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This if statment can also include a check that would prevent algo breakage. And I see 2 solutions for that. Change condition to check for long.MaxValue / iterDurationTotal and:

  • Throw if its higher
  • Set _iterationCount = null

This also raises another issue with the code. For which I'm unsure whether I should also try to handle or if im just being too pedantic. IterationCount.INFINITE will break the animation logic same way as another really high value does. Should I make sure to explicitly handle animTime over/under-flow? I'm pretty sure this issue has been present already in old animation logic. Maybe it would be smart to just skip unneccessary computation for now unless someone actually needs it and reports an issue.

@MrJul
Copy link
Member

MrJul commented Nov 7, 2025

When animation reverses direction and reaches the starting position subsequently, animation will always hold value of initial keyframe (first or last keyframe depending on proper animation direction), no matter the value of FillMode.

This does not sound correct, FillMode should always be respected: it's possible to be have the first key frame be at at time > 0 with no FillMode specified, in which case the neutral value should apply. But we have tests for that, so again, there's probably something that I'm missing here. Can you please clarify?

@MrJul
Copy link
Member

MrJul commented Nov 7, 2025

The only new delay behavior is with animations where IterationCount is INFINITE. When animation plays backwards past the starting point, the DelayBetweenIterations will be played in the opposite part of the iteration time. Here is a quick/crudely drawn illustration of animation timeline to make it clearer:

That makes sense. Could you please add an unit test for this special case?

timiimit-tam and others added 2 commits November 10, 2025 14:48
Remove leftover vars/params
Replace some `if`s with terniary assignment
Improve comments
Unduplicate `playbackReversed` code
@timiimit-tam
Copy link
Author

timiimit-tam commented Nov 10, 2025

This does not sound correct, FillMode should always be respected: it's possible to be have the first key frame be at at time > 0 with no FillMode specified, in which case the neutral value should apply. But we have tests for that, so again, there's probably something that I'm missing here. Can you please clarify?

Yes, I imagined that FillMode should not be respected when reversing back and reaching the starting position because then it would be possible to have 1 frame in the middle of animation that would just jump to a randomly looking position (value that Property had before animation started). I thought it would be preferable that initial position should only respect FillMode.Backward first time the animation is in starting position. Any other time the animation would act as if FillMode.Backward is enabled no matter what, to keep animation smooth.

So at start of animation and at its end FillMode will still act normally. My change only affects the middle of animation if user keeps changing PlaybackDirection - moving between negative and positive side of initial starting point of animation.

@timiimit-tam
Copy link
Author

I will add the UnitTest you requested soon.

@avaloniaui-bot
Copy link

You can test this PR using the following package version. 12.0.999-cibuild0059938-alpha. (feed url: https://nuget-feed-all.avaloniaui.net/v3/index.json) [PRBUILDID]

Timotej Korda Mlakar added 3 commits November 11, 2025 08:06
DelayBetweenIterations_Behind_Initial_Point_Is_In_Front_Of_Iterations
@timiimit-tam
Copy link
Author

timiimit-tam commented Nov 11, 2025

There are a few additional changes I made besides the unit test:

  • DelayBetweenIterations had no check for negative values, so I addad that
  • I reordered ifs for throwing to reduce property calls and use cached variables instead
  • I took the libery to also add limited animation time precision. This means that animation's smallest unit of time is 1 millisecond and as such animations can run for longer before breaking. I can undo this if it's not desired or if you think its not worth the computation time (3 additional divisions). I believe 1ms to be a reasonable precision since I can't see monitors reaching 1000hz and if they ever do, I think anything higher would be imperceivable.

@avaloniaui-bot
Copy link

You can test this PR using the following package version. 12.0.999-cibuild0059948-alpha. (feed url: https://nuget-feed-all.avaloniaui.net/v3/index.json) [PRBUILDID]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-animations backport-candidate-11.3.x Consider this PR for backporting to 11.3 branch enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unexpected animation outcome if SpeedRatio or PlaybackDirection properties change

4 participants