Animation fixes: 0-duration edge case, integer value bug resolution

This commit is contained in:
John McCardle 2026-01-04 00:45:16 -05:00
commit 357c2ac7d7
8 changed files with 333 additions and 51 deletions

View file

@ -57,15 +57,15 @@ Animation::~Animation() {
void Animation::start(std::shared_ptr<UIDrawable> target) {
if (!target) return;
targetWeak = target;
elapsed = 0.0f;
callbackTriggered = false; // Reset callback state
// Capture start value from target
std::visit([this, &target](const auto& targetVal) {
using T = std::decay_t<decltype(targetVal)>;
if constexpr (std::is_same_v<T, float>) {
float value;
if (target->getProperty(targetProperty, value)) {
@ -73,9 +73,15 @@ void Animation::start(std::shared_ptr<UIDrawable> target) {
}
}
else if constexpr (std::is_same_v<T, int>) {
int value;
if (target->getProperty(targetProperty, value)) {
startValue = value;
// Most UI properties use float, so try float first, then int
float fvalue;
if (target->getProperty(targetProperty, fvalue)) {
startValue = static_cast<int>(fvalue);
} else {
int ivalue;
if (target->getProperty(targetProperty, ivalue)) {
startValue = ivalue;
}
}
}
else if constexpr (std::is_same_v<T, std::vector<int>>) {
@ -104,19 +110,29 @@ void Animation::start(std::shared_ptr<UIDrawable> target) {
}
}
}, targetValue);
// For zero-duration animations, apply final value immediately
if (duration <= 0.0f) {
AnimationValue finalValue = interpolate(1.0f);
applyValue(target.get(), finalValue);
if (pythonCallback && !callbackTriggered) {
triggerCallback();
}
callbackTriggered = true;
}
}
void Animation::startEntity(std::shared_ptr<UIEntity> target) {
if (!target) return;
entityTargetWeak = target;
elapsed = 0.0f;
callbackTriggered = false; // Reset callback state
// Capture the starting value from the entity
std::visit([this, target](const auto& val) {
using T = std::decay_t<decltype(val)>;
if constexpr (std::is_same_v<T, float>) {
float value = 0.0f;
if (target->getProperty(targetProperty, value)) {
@ -131,6 +147,16 @@ void Animation::startEntity(std::shared_ptr<UIEntity> target) {
}
// Entities don't support other types yet
}, targetValue);
// For zero-duration animations, apply final value immediately
if (duration <= 0.0f) {
AnimationValue finalValue = interpolate(1.0f);
applyValue(target.get(), finalValue);
if (pythonCallback && !callbackTriggered) {
triggerCallback();
}
callbackTriggered = true;
}
}
bool Animation::hasValidTarget() const {
@ -169,39 +195,55 @@ bool Animation::update(float deltaTime) {
// Try to lock weak_ptr to get shared_ptr
std::shared_ptr<UIDrawable> target = targetWeak.lock();
std::shared_ptr<UIEntity> entity = entityTargetWeak.lock();
// If both are null, target was destroyed
if (!target && !entity) {
return false; // Remove this animation
}
// Handle already-complete animations (e.g., duration=0)
// Apply final value once before returning
if (isComplete()) {
if (!callbackTriggered) {
// Apply final value for zero-duration animations
AnimationValue finalValue = interpolate(1.0f);
if (target) {
applyValue(target.get(), finalValue);
} else if (entity) {
applyValue(entity.get(), finalValue);
}
// Trigger callback
if (pythonCallback) {
triggerCallback();
}
callbackTriggered = true;
}
return false;
}
elapsed += deltaTime;
elapsed = std::min(elapsed, duration);
// Calculate easing value (0.0 to 1.0)
float t = duration > 0 ? elapsed / duration : 1.0f;
float easedT = easingFunc(t);
// Get interpolated value
AnimationValue currentValue = interpolate(easedT);
// Apply to whichever target is valid
if (target) {
applyValue(target.get(), currentValue);
} else if (entity) {
applyValue(entity.get(), currentValue);
}
// Trigger callback when animation completes
// Check pythonCallback again in case it was cleared during update
if (isComplete() && !callbackTriggered && pythonCallback) {
triggerCallback();
}
return !isComplete();
}
@ -310,15 +352,19 @@ AnimationValue Animation::interpolate(float t) const {
void Animation::applyValue(UIDrawable* target, const AnimationValue& value) {
if (!target) return;
std::visit([this, target](const auto& val) {
using T = std::decay_t<decltype(val)>;
if constexpr (std::is_same_v<T, float>) {
target->setProperty(targetProperty, val);
}
else if constexpr (std::is_same_v<T, int>) {
target->setProperty(targetProperty, val);
// Most UI properties use float setProperty, so try float first
if (!target->setProperty(targetProperty, static_cast<float>(val))) {
// Fall back to int if float didn't work
target->setProperty(targetProperty, val);
}
}
else if constexpr (std::is_same_v<T, sf::Color>) {
target->setProperty(targetProperty, val);

View file

@ -113,6 +113,48 @@ void PyAnimation::dealloc(PyAnimationObject* self) {
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* PyAnimation::repr(PyAnimationObject* self) {
if (!self->data) {
return PyUnicode_FromString("<Animation (uninitialized)>");
}
std::string property = self->data->getTargetProperty();
float duration = self->data->getDuration();
float elapsed = self->data->getElapsed();
bool complete = self->data->isComplete();
bool delta = self->data->isDelta();
bool hasTarget = self->data->hasValidTarget();
// Format: <Animation 'property' duration=2.0s elapsed=0.5s running>
// or: <Animation 'property' duration=2.0s complete>
// or: <Animation 'property' duration=2.0s delta complete>
// or: <Animation 'property' duration=2.0s (no target)>
std::string status;
if (!hasTarget) {
status = "(no target)";
} else if (complete) {
status = "complete";
} else {
char buf[32];
snprintf(buf, sizeof(buf), "elapsed=%.2fs", elapsed);
status = buf;
}
char result[256];
if (delta) {
snprintf(result, sizeof(result),
"<Animation '%s' duration=%.2fs delta %s>",
property.c_str(), duration, status.c_str());
} else {
snprintf(result, sizeof(result),
"<Animation '%s' duration=%.2fs %s>",
property.c_str(), duration, status.c_str());
}
return PyUnicode_FromString(result);
}
PyObject* PyAnimation::get_property(PyAnimationObject* self, void* closure) {
return PyUnicode_FromString(self->data->getTargetProperty().c_str());
}

View file

@ -16,6 +16,7 @@ public:
static PyObject* create(PyTypeObject* type, PyObject* args, PyObject* kwds);
static int init(PyAnimationObject* self, PyObject* args, PyObject* kwds);
static void dealloc(PyAnimationObject* self);
static PyObject* repr(PyAnimationObject* self);
// Properties
static PyObject* get_property(PyAnimationObject* self, void* closure);
@ -42,8 +43,59 @@ namespace mcrfpydef {
.tp_basicsize = sizeof(PyAnimationObject),
.tp_itemsize = 0,
.tp_dealloc = (destructor)PyAnimation::dealloc,
.tp_repr = (reprfunc)PyAnimation::repr,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyDoc_STR("Animation object for animating UI properties"),
.tp_doc = PyDoc_STR(
"Animation(property: str, target: Any, duration: float, easing: str = 'linear', delta: bool = False, callback: Callable = None)\n"
"\n"
"Create an animation that interpolates a property value over time.\n"
"\n"
"Args:\n"
" property: Property name to animate. Valid properties depend on target type:\n"
" - Position/Size: 'x', 'y', 'w', 'h', 'pos', 'size'\n"
" - Appearance: 'fill_color', 'outline_color', 'outline', 'opacity'\n"
" - Sprite: 'sprite_index', 'sprite_number', 'scale'\n"
" - Grid: 'center', 'zoom'\n"
" - Caption: 'text'\n"
" - Sub-properties: 'fill_color.r', 'fill_color.g', 'fill_color.b', 'fill_color.a'\n"
" target: Target value for the animation. Type depends on property:\n"
" - float: For numeric properties (x, y, w, h, scale, opacity, zoom)\n"
" - int: For integer properties (sprite_index)\n"
" - tuple (r, g, b[, a]): For color properties\n"
" - tuple (x, y): For vector properties (pos, size, center)\n"
" - list[int]: For sprite animation sequences\n"
" - str: For text animation\n"
" duration: Animation duration in seconds.\n"
" easing: Easing function name. Options:\n"
" - 'linear' (default)\n"
" - 'easeIn', 'easeOut', 'easeInOut'\n"
" - 'easeInQuad', 'easeOutQuad', 'easeInOutQuad'\n"
" - 'easeInCubic', 'easeOutCubic', 'easeInOutCubic'\n"
" - 'easeInQuart', 'easeOutQuart', 'easeInOutQuart'\n"
" - 'easeInSine', 'easeOutSine', 'easeInOutSine'\n"
" - 'easeInExpo', 'easeOutExpo', 'easeInOutExpo'\n"
" - 'easeInCirc', 'easeOutCirc', 'easeInOutCirc'\n"
" - 'easeInElastic', 'easeOutElastic', 'easeInOutElastic'\n"
" - 'easeInBack', 'easeOutBack', 'easeInOutBack'\n"
" - 'easeInBounce', 'easeOutBounce', 'easeInOutBounce'\n"
" delta: If True, target is relative to start value (additive). Default False.\n"
" callback: Function(animation, target) called when animation completes.\n"
"\n"
"Example:\n"
" # Move a frame from current position to x=500 over 2 seconds\n"
" anim = mcrfpy.Animation('x', 500.0, 2.0, 'easeInOut')\n"
" anim.start(my_frame)\n"
"\n"
" # Fade out with callback\n"
" def on_done(anim, target):\n"
" print('Animation complete!')\n"
" fade = mcrfpy.Animation('fill_color.a', 0, 1.0, callback=on_done)\n"
" fade.start(my_sprite)\n"
"\n"
" # Animate through sprite frames\n"
" walk_cycle = mcrfpy.Animation('sprite_index', [0,1,2,3,2,1], 0.5, 'linear')\n"
" walk_cycle.start(my_entity)\n"
),
.tp_methods = PyAnimation::methods,
.tp_getset = PyAnimation::getsetters,
.tp_init = (initproc)PyAnimation::init,

View file

@ -47,7 +47,34 @@ namespace mcrfpydef {
.tp_repr = PyColor::repr,
.tp_hash = PyColor::hash,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyDoc_STR("SFML Color Object"),
.tp_doc = PyDoc_STR(
"Color(r: int = 0, g: int = 0, b: int = 0, a: int = 255)\n"
"\n"
"RGBA color representation.\n"
"\n"
"Args:\n"
" r: Red component (0-255)\n"
" g: Green component (0-255)\n"
" b: Blue component (0-255)\n"
" a: Alpha component (0-255, default 255 = opaque)\n"
"\n"
"Note:\n"
" When accessing colors from UI elements (e.g., frame.fill_color),\n"
" you receive a COPY of the color. Modifying it doesn't affect the\n"
" original. To change a component:\n"
"\n"
" # This does NOT work:\n"
" frame.fill_color.r = 255 # Modifies a temporary copy\n"
"\n"
" # Do this instead:\n"
" c = frame.fill_color\n"
" c.r = 255\n"
" frame.fill_color = c\n"
"\n"
" # Or use Animation for sub-properties:\n"
" anim = mcrfpy.Animation('fill_color.r', 255, 0.5, 'linear')\n"
" anim.start(frame)\n"
),
.tp_methods = PyColor::methods,
.tp_getset = PyColor::getsetters,
.tp_init = (initproc)PyColor::init,

View file

@ -268,8 +268,12 @@ PyGetSetDef UICaption::getsetters[] = {
//{"w", (getter)PyUIFrame_get_float_member, (setter)PyUIFrame_set_float_member, "width of the rectangle", (void*)2},
//{"h", (getter)PyUIFrame_get_float_member, (setter)PyUIFrame_set_float_member, "height of the rectangle", (void*)3},
{"outline", (getter)UICaption::get_float_member, (setter)UICaption::set_float_member, "Thickness of the border", (void*)4},
{"fill_color", (getter)UICaption::get_color_member, (setter)UICaption::set_color_member, "Fill color of the text", (void*)0},
{"outline_color", (getter)UICaption::get_color_member, (setter)UICaption::set_color_member, "Outline color of the text", (void*)1},
{"fill_color", (getter)UICaption::get_color_member, (setter)UICaption::set_color_member,
"Fill color of the text. Returns a copy; modifying components requires reassignment. "
"For animation, use 'fill_color.r', 'fill_color.g', etc.", (void*)0},
{"outline_color", (getter)UICaption::get_color_member, (setter)UICaption::set_color_member,
"Outline color of the text. Returns a copy; modifying components requires reassignment. "
"For animation, use 'outline_color.r', 'outline_color.g', etc.", (void*)1},
//{"children", (getter)PyUIFrame_get_children, NULL, "UICollection of objects on top of this one", NULL},
{"text", (getter)UICaption::get_text, (setter)UICaption::set_text, "The text displayed", NULL},
{"font_size", (getter)UICaption::get_float_member, (setter)UICaption::set_float_member, "Font size (integer) in points", (void*)5},

View file

@ -434,8 +434,12 @@ PyGetSetDef UIFrame::getsetters[] = {
{"w", (getter)UIDrawable::get_float_member, (setter)UIDrawable::set_float_member, "width of the rectangle", (void*)((intptr_t)PyObjectsEnum::UIFRAME << 8 | 2)},
{"h", (getter)UIDrawable::get_float_member, (setter)UIDrawable::set_float_member, "height of the rectangle", (void*)((intptr_t)PyObjectsEnum::UIFRAME << 8 | 3)},
{"outline", (getter)UIFrame::get_float_member, (setter)UIFrame::set_float_member, "Thickness of the border", (void*)4},
{"fill_color", (getter)UIFrame::get_color_member, (setter)UIFrame::set_color_member, "Fill color of the rectangle", (void*)0},
{"outline_color", (getter)UIFrame::get_color_member, (setter)UIFrame::set_color_member, "Outline color of the rectangle", (void*)1},
{"fill_color", (getter)UIFrame::get_color_member, (setter)UIFrame::set_color_member,
"Fill color of the rectangle. Returns a copy; modifying components requires reassignment. "
"For animation, use 'fill_color.r', 'fill_color.g', etc.", (void*)0},
{"outline_color", (getter)UIFrame::get_color_member, (setter)UIFrame::set_color_member,
"Outline color of the rectangle. Returns a copy; modifying components requires reassignment. "
"For animation, use 'outline_color.r', 'outline_color.g', etc.", (void*)1},
{"children", (getter)UIFrame::get_children, NULL, "UICollection of objects on top of this one", NULL},
{"on_click", (getter)UIDrawable::get_click, (setter)UIDrawable::set_click,
MCRF_PROPERTY(on_click,

View file

@ -2059,7 +2059,9 @@ PyGetSetDef UIGrid::getsetters[] = {
), (void*)PyObjectsEnum::UIGRID},
{"texture", (getter)UIGrid::get_texture, NULL, "Texture of the grid", NULL}, //TODO 7DRL-day2-item5
{"fill_color", (getter)UIGrid::get_fill_color, (setter)UIGrid::set_fill_color, "Background fill color of the grid", NULL},
{"fill_color", (getter)UIGrid::get_fill_color, (setter)UIGrid::set_fill_color,
"Background fill color of the grid. Returns a copy; modifying components requires reassignment. "
"For animation, use 'fill_color.r', 'fill_color.g', etc.", NULL},
{"perspective", (getter)UIGrid::get_perspective, (setter)UIGrid::set_perspective,
"Entity whose perspective to use for FOV rendering (None for omniscient view). "
"Setting an entity automatically enables perspective mode.", NULL},