Skip to content

Preserve custom spring force and torque callbacks when copying - #317

Merged
viblo merged 1 commit into
viblo:masterfrom
antonsoo:fix/spring-copy-laws
Oct 12, 2026
Merged

viblo merged 1 commit into
viblo:masterfrom
antonsoo:fix/spring-copy-laws

Conversation

@antonsoo

Copy link
Copy Markdown
Contributor

Custom spring laws currently disappear during copying or pickling, so a restored simulation silently uses the default force or torque function:

import pymunk

def nonlinear_force(spring, distance):
    return spring.stiffness * (spring.rest_length - distance) ** 3

a, b = pymunk.Body(1, 1), pymunk.Body(1, 1)
b.position = (3, 0)
spring = pymunk.DampedSpring(a, b, (0, 0), (0, 0), 1, 2, 0)
spring.force_func = nonlinear_force
print(spring.copy().force_func is nonlinear_force)  # Before: False; after: True

Add force_func and torque_func to their classes' general-state lists. Restoration then uses the existing setters to install the callback or the native default function. Pickle requires a pickleable callback, as with other serialized callbacks; it no longer silently discards a custom law.

Validation:

  • Added copy/deepcopy/pickle cases that step the restored springs and verify their impulses, plus reset-to-default controls. All six custom-law cases fail on the original source and pass after the change. The full python -m pymunk.tests run passes (289 tests, two skipped).
  • Ran 48 native linear/rotary oscillator continuations at three checkpoints. All 24 custom-law cases now match freshly constructed reference worlds; 24 default-law controls remain identical. An independent scalar integrator agrees within 5.6e-17 for these undamped setups.
  • Ran the shipped constraints demo headlessly with custom laws and copy/pickle checkpoints. All six continuations match explicitly restored reference callbacks over 240 steps. Original-source pickles remain loadable.

Validation used Linux and Python 3.12. Existing unrelated mypy and whole-file formatting failures are unchanged; the edited test module passes Black.

@viblo
viblo merged commit cf5bb83 into viblo:master Oct 12, 2026
7 checks passed
@viblo

viblo commented Oct 12, 2026

Copy link
Copy Markdown
Owner

Thanks for finding and fixing the bug!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants