Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(animation): preserve looping tween phase across long frames

yhhb574b20037bd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 460912e58..56fc52a41 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Looping tweens preserve long-frame remainder.** JS value tweens and native property tweens skip completed cycles arithmetically, retain the current phase and ping-pong direction, and complete finite counts at their final endpoint. Exact cycle boundaries keep their endpoint behavior; delay remainder is preserved and very large frame sums are bounded instead of overflowing elapsed time.
+
- **Immediate value tweens produce their endpoint.** Non-positive durations complete at the next eligible update, matching native tweens instead of emitting NaN or retaining a negative-duration tween forever. Delays and callback playback controls continue to apply.
- **Value tween callbacks preserve playback control.** Callback-created tweens start on the next update, recursive updates cannot advance the same pass twice, and callback cancellation or pause is not overwritten by completion or sequence handoff. Existing sequence members still resume in the same frame, without allocating a snapshot of the tween map.
diff --git a/sdk/src/animation/ValueTween.ts b/sdk/src/animation/ValueTween.ts
index 1ddfd0f4d..e704afd85 100644
--- a/sdk/src/animation/ValueTween.ts
+++ b/sdk/src/animation/ValueTween.ts
@@ -127,7 +127,28 @@ export class ValueTweenManager {
entry.delay = 0;
}
- entry.elapsed += step;
+ entry.elapsed = Math.min(Number.MAX_VALUE, entry.elapsed + step);
+ if (entry.loop !== LoopMode.None && entry.duration > 0 && entry.elapsed > entry.duration) {
+ const remainder = entry.elapsed % entry.duration;
+ let skipped = Math.floor(entry.elapsed / entry.duration) - (remainder === 0 ? 1 : 0);
+ let reverse = (entry.elapsed % (entry.duration * 2) >= entry.duration) !== (remainder === 0);
+ const finite = entry.loopCount !== 0;
+ if (finite && skipped >= Math.max(1, entry.loopsRemaining)) {
+ skipped = Math.max(0, entry.loopsRemaining - 1);
+ reverse = skipped % 2 !== 0;
+ entry.elapsed = entry.duration;
+ } else {
+ // Exact boundaries still deliver the endpoint of the cycle
+ // that just ended, rather than the next cycle's start.
+ entry.elapsed = remainder === 0 ? entry.duration : remainder;
+ }
+ if (finite) entry.loopsRemaining -= skipped;
+ if (entry.loop === LoopMode.PingPong && reverse) {
+ const from = entry.from;
+ entry.from = entry.to;
+ entry.to = from;
+ }
+ }
const t = entry.duration > 0 ? Math.min(entry.elapsed / entry.duration, 1) : 1;
const easedT = applyEasing(entry.easing, t, entry.bezierPoints ?? undefined);
entry.callback(entry.from + (entry.to - entry.from) * easedT);
diff --git a/sdk/tests/tween-loop-phase-wasm.test.ts b/sdk/tests/tween-loop-phase-wasm.test.ts
new file mode 100644
index 000000000..d1a9027da
--- /dev/null
+++ b/sdk/tests/tween-loop-phase-wasm.test.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+import { World } from '../src/ecs/world';
+import { Transform } from '../src/ecs/component';
+import { TweenAPI, TweenTarget } from '../src/animation/Tween';
+import { LoopMode, TweenState } from '../src/animation/TweenTypes';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+describe.skipIf(!HAS_WASM)('loop phase on real WASM', () => {
+ let engine: ESEngineModule, registry: CppRegistry, world: World;
+ beforeAll(async () => { engine = await loadWasmModule(); });
+ beforeEach(() => { registry = new engine.Registry(); world = new World(); world.connectCpp(registry, engine); });
+ afterEach(() => { for (const e of world.getAllEntities()) world.despawn(e); world.disconnectCpp(); registry.delete(); });
+
+ it.each([LoopMode.Restart, LoopMode.PingPong])('matches JS and native loop phase across time steps and counts: %j', loop => {
+ for (const loopCount of [0, 1, 2, 3, 4]) {
+ for (const elapsed of [0, .25, 1, 1.25, 2, 2.25, 3, 3.25, 10.25, 1000000.25]) {
+ const api = new TweenAPI(engine, registry), entity = world.spawn();
+ world.insert(entity, Transform);
+ api.to(entity, TweenTarget.PositionX, 0, 10, 1, { loop, loopCount });
+ const values: number[] = [];
+ const handle = api.value(0, 10, 1, value => values.push(value), { loop, loopCount });
+ api.update(elapsed);
+ const complete = loopCount > 0 && elapsed >= loopCount;
+ const boundary = elapsed > 0 && elapsed % 1 === 0;
+ const cycle = complete ? loopCount - 1 : Math.floor(elapsed) - (boundary ? 1 : 0);
+ const t = complete || boundary ? 1 : elapsed % 1;
+ const expected = 10 * (loop === LoopMode.PingPong && cycle % 2 === 1 ? 1 - t : t);
+ expect(values).toEqual([expected]);
+ expect(world.get(entity, Transform).position.x).toBeCloseTo(expected);
+ expect(handle.state).toBe(complete ? TweenState.Completed : TweenState.Running);
+ }
+ }
+ });
+
+ it('retains delay remainder with a subsecond ping-pong duration', () => {
+ const api = new TweenAPI(engine, registry), entity = world.spawn();
+ world.insert(entity, Transform);
+ api.to(entity, TweenTarget.PositionX, 0, 10, .125, { loop: LoopMode.PingPong, delay: .5 });
+ const values: number[] = [];
+ api.value(0, 10, .125, value => values.push(value), { loop: LoopMode.PingPong, delay: .5 });
+ api.update(.8125);
+ expect(values).toEqual([5]);
+ expect(world.get(entity, Transform).position.x).toBeCloseTo(5);
+ });
+});
diff --git a/sdk/tests/value-tween.test.ts b/sdk/tests/value-tween.test.ts
index d70dcc1eb..9093e0a01 100644
--- a/sdk/tests/value-tween.test.ts
+++ b/sdk/tests/value-tween.test.ts
@@ -182,6 +182,38 @@ describe('ValueTweenManager state transitions', () => {
});
describe('ValueTweenManager looping', () => {
+ it('keeps loop phase finite when elapsed addition would overflow', () => {
+ const m = makeManager(), seen = vi.fn();
+ m.create(0, 10, Number.MAX_VALUE, seen, { loop: LoopMode.Restart });
+ m.update(Number.MAX_VALUE / 2);
+ m.update(Number.MAX_VALUE);
+ expect(seen.mock.calls).toEqual([[5], [10]]);
+ });
+ it.each([LoopMode.Restart, LoopMode.PingPong])('retains long-frame phase for loop mode %j', loop => {
+ const run = (steps: number[]) => {
+ const m = makeManager(); let value = -1;
+ m.create(0, 10, 1, v => { value = v; }, { loop });
+ for (const dt of steps) m.update(dt);
+ return value;
+ };
+ expect(run([1.25])).toBeCloseTo(run([.25, .25, .25, .25, .25]));
+ expect(run([1000000.25])).toBeCloseTo(2.5);
+ });
+
+ it.each([LoopMode.Restart, LoopMode.PingPong])('completes all finite cycles in one long update, mode %j', loop => {
+ const m = makeManager(), seen = vi.fn();
+ const id = m.create(0, 10, 1, seen, { loop, loopCount: 2 });
+ m.update(10.25);
+ expect(seen.mock.calls).toEqual([[loop === LoopMode.Restart ? 10 : 0]]);
+ expect(m.getState(id)).toBe(TweenState.Completed);
+ });
+
+ it('carries delay remainder into a looping tween', () => {
+ const m = makeManager(), seen = vi.fn();
+ m.create(0, 10, 1, seen, { delay: .5, loop: LoopMode.PingPong });
+ m.update(1.75);
+ expect(seen.mock.calls).toEqual([[7.5]]);
+ });
it('Restart replays loopCount times then completes', () => {
const m = makeManager();
const seen: number[] = [];
diff --git a/src/esengine/animation/TweenSystem.cpp b/src/esengine/animation/TweenSystem.cpp
index a9b0effb4..a44f90a43 100644
--- a/src/esengine/animation/TweenSystem.cpp
+++ b/src/esengine/animation/TweenSystem.cpp
@@ -11,6 +11,7 @@
#include <glm/glm.hpp>
#include <cmath>
#include <algorithm>
+#include <limits>
namespace esengine::animation {
@@ -50,7 +51,28 @@ void TweenSystem::update(ecs::Registry& registry, f32 deltaTime) {
tween.delay = 0.0f;
}
- tween.elapsed += tweenDelta;
+ tween.elapsed = static_cast<f32>(std::min(
+ static_cast<double>(tween.elapsed) + tweenDelta,
+ static_cast<double>(std::numeric_limits<f32>::max())));
+ if (tween.loop_mode != LoopMode::None && tween.duration > 0.0f && tween.elapsed > tween.duration) {
+ const double elapsed = tween.elapsed;
+ const double duration = tween.duration;
+ const double remainder = std::fmod(elapsed, duration);
+ double skipped = std::floor(elapsed / duration) - (remainder == 0.0 ? 1.0 : 0.0);
+ bool reverse = (std::fmod(elapsed, duration * 2.0) >= duration) != (remainder == 0.0);
+ if (tween.loops_remaining > 0 && skipped >= tween.loops_remaining) {
+ skipped = tween.loops_remaining - 1;
+ reverse = static_cast<i32>(skipped) % 2 != 0;
+ tween.elapsed = tween.duration;
+ } else {
+ // Keep exact boundaries at the endpoint of the preceding cycle.
+ tween.elapsed = static_cast<f32>(remainder == 0.0 ? duration : remainder);
+ }
+ if (tween.loops_remaining > 0) tween.loops_remaining -= static_cast<i32>(skipped);
+ if (tween.loop_mode == LoopMode::PingPong && reverse) {
+ std::swap(tween.from_value, tween.to_value);
+ }
+ }
f32 rawT = (tween.duration > 0.0f)
? glm::clamp(tween.elapsed / tween.duration, 0.0f, 1.0f)
: 1.0f;
diff --git a/tests/ecs/test_tween_activity.cpp b/tests/ecs/test_tween_activity.cpp
index c52eef182..ecab151cc 100644
--- a/tests/ecs/test_tween_activity.cpp
+++ b/tests/ecs/test_tween_activity.cpp
@@ -2,11 +2,63 @@
#include <doctest.h>
#include "esengine/animation/TweenSystem.hpp"
#include "esengine/ecs/components/Transform.hpp"
+#include <limits>
using namespace esengine;
using namespace esengine::ecs;
using namespace esengine::animation;
+TEST_CASE("looping tweens retain long frame phase") {
+ for (auto mode : {LoopMode::Restart, LoopMode::PingPong}) {
+ Registry r; TweenSystem s;
+ auto target = r.create(); r.emplace<Transform>(target);
+ auto tween = s.createTween(r, target, TweenTarget::PositionX, 0, 10, 1);
+ r.get<TweenData>(tween).loop_mode = mode;
+ s.update(r, 1.25f);
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(mode == LoopMode::Restart ? 2.5 : 7.5));
+ CHECK(r.get<TweenData>(tween).elapsed == doctest::Approx(.25));
+ s.update(r, .75f);
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(mode == LoopMode::Restart ? 10 : 0));
+ }
+}
+
+TEST_CASE("finite loops complete in a long frame at their final endpoint") {
+ for (auto mode : {LoopMode::Restart, LoopMode::PingPong}) {
+ Registry r; TweenSystem s;
+ auto target = r.create(); r.emplace<Transform>(target);
+ auto tween = s.createTween(r, target, TweenTarget::PositionX, 0, 10, 1);
+ auto& data = r.get<TweenData>(tween); data.loop_mode = mode; data.loops_remaining = 2;
+ s.update(r, 10.25f);
+ CHECK_FALSE(r.valid(tween));
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(mode == LoopMode::Restart ? 10 : 0));
+ }
+}
+
+TEST_CASE("looping delay remainder and large time steps stay bounded") {
+ Registry r; TweenSystem s;
+ auto target = r.create(); r.emplace<Transform>(target);
+ auto tween = s.createTween(r, target, TweenTarget::PositionX, 0, 10, 1);
+ auto& data = r.get<TweenData>(tween); data.loop_mode = LoopMode::PingPong; data.delay = .5f;
+ s.update(r, 1.75f);
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(7.5));
+ s.update(r, 1000000.0f);
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(7.5));
+ CHECK(r.get<TweenData>(tween).elapsed == doctest::Approx(.25));
+}
+
+TEST_CASE("loop elapsed overflow stays finite") {
+ Registry r; TweenSystem s;
+ auto target = r.create(); r.emplace<Transform>(target);
+ const auto duration = std::numeric_limits<f32>::max();
+ auto tween = s.createTween(r, target, TweenTarget::PositionX, 0, 10, duration);
+ r.get<TweenData>(tween).loop_mode = LoopMode::Restart;
+ s.update(r, duration / 2);
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(5));
+ s.update(r, duration);
+ CHECK(r.get<Transform>(target).position.x == doctest::Approx(10));
+ CHECK(r.get<TweenData>(tween).elapsed == 0);
+}
+
TEST_CASE("delay remainder belongs to its own tween") {
Registry r; TweenSystem s;
auto a = r.create(), b = r.create();
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index b733dfff5..9685d1879 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(animation): preserve looping tween phase across long frames':
+ { note: 'Looping tweens preserve long-frame remainder.' },
'fix(animation): complete immediate value tweens safely':
{ note: 'Immediate value tweens produce their endpoint.' },
'fix(animation): preserve value tween callback control':