Skip to content

Upstream v3.2 sync - #104

Closed
ice1000 wants to merge 28 commits into
ikpil:mainfrom
ice1000:upstream-v3.2-sync
Closed

ice1000 wants to merge 28 commits into
ikpil:mainfrom
ice1000:upstream-v3.2-sync

Conversation

@ice1000

@ice1000 ice1000 commented Nov 12, 2026

Copy link
Copy Markdown

This is not intended to be merged. I am opening this just to make viewing the changes convenient. Feel free to merge or close, I don't care.

This PR updates Box2D.Net to the latest commit (chain builder) as of today, and does not change any language version settings.

I have come to the realization that (too late due to me being new to C#):

  1. This library targets Unity users, which is on .net standard 2.1, an ancient version of C#;
  2. Unity is going to upgrade to CoreCLR and newer versions of C#, leaving fewer reasons to keep this project on an old language version;
  3. This project does not try to use the SIMD operations at all.

For my own purposes, I want to be a bit more aggressive on my fork: I will use the target C# version of that Unity forum post; use bare minimum SIMD in the project (as much as I see feasible, since I don't have that much time either); especially rely on the behavior of recent versions of System.Numerics (yes, it seems to change over major versions). This makes the maintenance easier and publishing on NuGet also easier, because I don't need to use #if anymore.

Again, thanks for creating this project. It's super duper cool.

ice1000 and others added 28 commits November 11, 2026 22:36
Port only the core pieces of upstream 436365a; recording and world
snapshot/restore are intentionally skipped.

- Break split-island sleep time ties by island id for determinism
- Add b2World_GetBounds (union of broad-phase root bounds)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port the API and relative-coordinate changes of upstream 95aaff8.
Box2D.NET stays single precision: BOX2D_DOUBLE_PRECISION is not
supported, but B2Pos / B2WorldTransform are distinct float types so the
API matches upstream and mixing positions with vectors is a compile
error, as it is in an upstream double build.

- Add B2Pos, B2WorldTransform, B2WorldCastOutput, B2BoxCastInput and
  the position helpers (b2SubPos, b2OffsetPos, b2InvMulWorldTransforms,
  b2ToRelativeTransform, b2OffsetAABB, ...)
- Body sims store world transforms; narrow phase, sensors, joints,
  continuous collision and recycling work in relative coordinates
- World queries take an origin; b2DynamicTree_ShapeCast becomes
  b2DynamicTree_BoxCast
- B2DistanceInput / B2ShapeCastPairInput take a relative transform and
  return results in frame A
- Remove B2ManifoldPoint.clipPoint; hit events rebuild the point from
  body centers
- Rename b2Body_Get{Local,World}CenterOfMass to b2Body_Get{Local,World}Center
- Shared, samples and tests updated to compile; determinism test now
  expects upstream's float values (sleep step 327, hash 0x5F0C8CAC)
- Port the float-mode parts of the new large world, collision and math
  tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of erincatto/box2d@56edae7.

- Add B2LocalManifold/B2LocalManifoldPoint. All b2Collide* functions take
  the shapes plus the relative transform of B in A and return a manifold in
  frame A; b2UpdateContact marshals it to world anchors.
- b2DebugDraw callbacks receive world coordinates again (B2Pos /
  B2WorldTransform), origin removed, DrawBoundsFcn added.
- Joint draw helpers take world transforms; add b2OffsetWorldTransform.
- Dynamic tree CreateProxy validates with b2IsValidAABB.
- Shared CreateManyPyramids layout fix.
- Determinism expectations updated to upstream float values (294, 0x006F0F5E).

Samples: compile-level updates only (draw callbacks, manifold samples).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add mover joint (B2MoverJoint/Def/Joints) and pogo joint (B2PogoJoint/Def/Joints)
  with B2JointType entries, union members, create/default functions, solver dispatch,
  reaction/force reporting and debug drawing.
- Redesign pre-solve: b2PreSolveFcn now edits the manifold by ref; continuous collision
  uses the new b2PreContinuousFcn. b2World_SetPreSolveCallback takes both.
- b2DestroyJoint drops wakeAttached; internal destroy paths no longer take wake flags.
- Motion locks / fixed rotation recompute mass data; b2Body_SetMassData honors locks.
- Revolute limits are clamped to +/-0.99 pi instead of asserted; limit setters on
  prismatic/revolute/wheel/distance joints no longer reset accumulated impulses.
- b2Normalize/b2GetLengthAndNormalize use an FLT_MIN based threshold, b2UnwindAngle
  rounds to nearest, b2ShapeDistance handles degenerate short edges.
- Rename b2OffsetWorldTransform -> b2MulWorldTransforms, b2PlaneSolverResult.translation -> delta.
- Add b2World_GetStateHash (port of b2HashWorldStateDeep).
- Tests: ShapeDistanceShortEdgeTest, canEncroach in ShapeCastTest, new pre-solve signature.

Skipped: config.h, atomics, denormal startup check, recording/snapshot changes, and the
new dynamic mover samples. Samples only get the minimal changes needed to compile
(Platform keeps its one-way logic through both callbacks).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add B2BodyDef.safetyFactor (default 0.5) and b2Body_Set/GetSafetyFactor so continuous
  collision can engage at lower speeds.
- b2_isFast now lives on the body flags; contact recycling is disabled when either body is fast.
- b2TransferBody clears transient flags on both body and body sim.
- b2Body_WakeTouching and b2Body_SetSleepThreshold use b2GetWorldLocked.
- Determinism expectations updated to 274 / 0xE86690F4.

Skipped: recording changes and the new continuous/determinism samples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Deferred restitution instead of a separate solver stage:
- restitution velocity is armed per manifold point in b2UpdateContact and
  applied as a velocity target inside the relax pass; the restitution stage,
  b2ApplyRestitution* and B2Profile.applyRestitution are removed
- optimized wide contact constraint preparation (_Wide stage functions,
  per-lane softness, baseSeparation precomputed in collide)
- hit events detected in store impulses for overflow contacts
- continuous collision corrects gravity for the lost time fraction
- remove b2World_EnableSpeculative / enableContactSoftening
- add b2Body_GetMinExtent/GetMaxExtent/GetMaxExtentOrigin
- port test_restitution.c and update determinism expectations

Recording, benchmark csv and new samples skipped; samples/benchmark tool
only adjusted to compile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- add B2_VERSION_MAJOR/MINOR/REVISION and use them in b2GetVersion
- broad-phase: extract b2EnqueueTreeUpdate and also rebuild trees when the
  move buffer is empty, so enlarged nodes left by a destroyed proxy are
  refit (EnlargedProxyDestroyedTest)
- comment cleanups in contact, contact solver and collide task

The NEON-only b2SoftMaskW fix, build.zig, CMake, CI and sample changes are
not applicable or skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Move some joint drawing behind drawJointExtras to reduce visual clutter:
filter joint draws anchor points and only draws its line as an extra,
motor joint line and revolute body-to-frame lines are extras, and the
default joint lines are removed. Sample camera tweak skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of erincatto/box2d@9082072.

- Dynamic tree rewritten: 32 byte nodes stored in sibling pairs, proxies
  split from nodes (B2TreeProxy), moved marks on nodes that propagate to
  the root, sweep refit over a DFS ordered array, DFS rebuild with pair
  compaction. RayCast/BoxCast renamed to CastRay/CastBox,
  ValidateNoEnlarged replaced by ValidateNoMoved.
- Broad phase rewritten around the tree marks: self pairs from the moved
  siblings, cross pairs against the static and kinematic trees, pair keys
  gathered per worker and sorted before contacts are created. The move
  buffer, move results and enlarged AABB flag on shapes are gone.
- Solver uses the mark/enlarge path and refits the kinematic and dynamic
  trees; collide connected marks a dynamic proxy.
- Changing the center of mass invalidates the cached relative transform
  on the body's contacts, and SetMassData updates the center of mass
  velocity.
- b2ContainsHashedKey added to the table.
- Tests: new dynamic tree tests (one proxy, leaf root, brute force query
  and cast, mark and refit, DFS order, stale after insert/remove), off
  center ray cases, EnlargedProxyDestroyed updated, BroadPhasePairs world
  tests, C#-only broad phase tests rewritten for the mark API.
  Determinism expectations 295 / 0x36564C94.

Skipped: snapshot/recording, SIMD and prefetch paths (scalar
equivalents used), benchmark csv and shared/benchmarks.c additions,
sample changes beyond the CastRay rename, CMake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of erincatto/box2d@a38faae.

- Chain shapes are segment based. B2ChainDef.count becomes pointCount
  (at least 2 for an open chain, 3 for a loop) and open chains take
  separate ghost1/ghost2 points, defaulted to infinity as a sentinel.
  segmentCount = isLoop ? pointCount : pointCount - 1.
- Materials live on the segment shapes only. b2Chain_GetSurfaceMaterialCount
  is removed, b2Chain_SetSurfaceMaterial/GetSurfaceMaterial take a segment
  index and b2Chain_SetAllSurfaceMaterials is added.
- Chain creation validates segment lengths and materials.
- Samples and shared benchmarks updated as upstream: pointCount rename,
  FootSensor and ChainLink use explicit ghosts, ChainShape drops the
  duplicated loop point, the SVG path parser removes the loop point.
- Tests: B2ChainTest (test_chain.c) and B2MoverTest (test_mover.c). The
  counting assert hook becomes Assert.DoesNotThrow since a tripped
  B2_ASSERT throws in debug builds.

Skipped: header reorganization (math_types.h, platform.h, ctz.h,
simd.h moves), recording/snapshot, test harness changes, unrelated
sample edits, CMake, zig, issue templates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of erincatto/box2d@773ed92.

- b2Body_ApplyMassFromShapes -> b2Body_UpdateMassFromShapes
- b2DynamicTree_Create/Destroy -> b2CreateDynamicTree/b2DestroyDynamicTree
- b2DynamicTree_CreateProxy(Internal)/DestroyProxy ->
  b2CreateTreeProxy(Internal)/b2DestroyTreeProxy

Skipped: recording, replay and snapshot renames, docs, CMake, zig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Contact sims carry encoded body sim indices (awake, static, or null),
  kept current on wake, sleep, body removal and transfer instead of being
  rewritten by the collide task every step.
- b2RemoveBodySim moves to solver sets and returns the swapped body;
  b2RefreshBodyContactIndices re-encodes its contacts.
- Fat AABBs move from B2Shape to world.fatAABBs.
- Collide task walks graph color spans and resolves body sims from the
  encoded indices; the fast flag is read off the body sim.
- Bullet bounds flag only set for bullets; time of impact flag set on the
  body after the move event.
- Dynamic tree stores node height again; b2DynamicTree_GetHeight is O(1).
- b2ParallelFor uses 8 blocks per worker.
- New BodySimLocatorTest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Added b2DistanceJoint_GetSpringForce.
- The contact registry is a static table and no longer needs runtime
  initialization.
- ContactEvent sample checks b2Body_IsValid instead of a null id.

The desk lamp sample itself is not ported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Restitution is a post-solve stage again. Prepare samples the
  approach velocity only when a contact has restitution or hit events,
  and the new restitution stage applies Poisson restitution for
  b2World::restitutionIterations sweeps (overflow and wide paths).
- The overflow solve is split into push (soft, biased), solve
  (speculative, friction, rolling) and restitution functions.
- New world API: b2World_Set/GetRestitutionIterations,
  b2World_EnableRestitutionPropagation and
  b2World_IsRestitutionPropagationEnabled, with matching b2WorldDef
  fields and B2_MAX_RESTITUTION_ITERATIONS.
- b2_isFast lives on the body sim only and is no longer a transient
  body flag.
- B2_CHECK_INPUT validates API input across world, body, shape, chain
  and joint functions, logging and returning instead of only asserting.
  Joint, prismatic and wheel limits are ordered with min/max.
- Removed b2ManifoldPoint.restitutionVelocity and the b2OrW/b2AndNotW
  SIMD helpers.
- b2DefaultLogFcn is public so tests can restore it.
- Added B2InvalidInputTest and updated B2RestitutionTest (normal
  velocity, overshoot, impulse and energy tests).

Arena and allocator alignment changes and recording are not ported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- b2CollidePolygons returns early when the first SAT axis already
  separates the polygons.
- Default friction and restitution mixing is inlined
  (b2MixFriction/b2MixRestitution) and the world callbacks stay null
  unless the user sets them.
- Length-dependent constants read b2_lengthUnitsPerMeter directly.

The SSE path in b2FindMaxSeparation is not ported. It computes the same
result as the scalar loop, including lowest-index tie breaking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- B2Profile gains a restitution field.
- The overflow solver books restitution stage time to restitution
  instead of relaxImpulses.
- The benchmark runner seeds the new field with float.MaxValue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- b2_hadTimeOfImpact now lives on the body sim only: the continuous
  solver writes it to the sim, b2SyncBodyFlags preserves it, and debug
  draw reads it from the sim.
- The continuous query callback reads the bullet flag from the body
  instead of the body sim, avoiding a data race with sim flag writes.
- b2Body_Enable puts a joint in the static set when neither body is
  dynamic, and b2Body_Disable's assert allows static set joints.
- Add NonDynamicJointDisableTest and update the restitution drop test to
  read the sim flag.
- b2GetJointFullId is public so tests can inspect joint sets, like
  b2GetBodyFullId.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
)

- b2ComputeHull welds with a 0.5 linear slop radius and only against
  the retained vertices (erincatto/box2d#1120).
- Broad-phase pair traversal tests both children with overlap masks
  (b2OverlapPairMask, b2OverlapNodePairMask) and walks set bits with
  b2CTZ32; b2VisitPair becomes b2ExpandPair. Visit order is unchanged.
- Solver stages read the block sync index before attempting the CAS.
- The built-in scheduler spins for 0.05 ms before sleeping and only
  signals the semaphore when a worker is asleep (sleeperCount).
- b2Pause moves from B2Solvers to B2Atomics, matching platform.h.
- Add b2IsAVX2Available (always false) and b2World_EnableSSE2Fallback
  (validation only), and port SIMDWidthTest, which skips at width 4.

Not ported: cpuid detection, the W4/W8 contact solver split and the
AVX2 negation change, since the port always solves contacts 4 wide;
cache line padding of solver blocks and stages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- API renames were applied separately (rename step 1, rename step 2).
- Contact solvers (overflow and wide) accumulate the normal, friction and
  rolling impulses per constraint and apply them once, propagating the
  coupling between sequential impulses analytically (k21..k43).
- The revolute joint accumulates its axial impulses (spring, motor,
  limits) and applies them together with the point constraint.
- Contact recycling is no longer disabled for fast bodies; a pre-solve
  that empties the manifold marks the relative transform invalid.
- Pair keys are sorted with b2RadixSortKeys; add B2SortTest.
- Graph colors pre-size their contact arrays from b2Capacity.contactCount
  over linear ramps; island merging grows arrays geometrically
  (b2Array_Grow).
- b2Capacity.arenaByteCount reserves arena space and reports the peak.
- Add b2World_GetContactTuning and b2RevoluteJoint_GetCurrentSpeed.
- Add PreSolveRejectRecycleTest; determinism expects 299 / 0x465F3DF4.

Not ported: shared benchmark capacity presets, recording guards and
b2Free zero size handling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…1123)

- Split tree setup into b2CreateDynamicTreeInternal / b2DestroyDynamicTreeInternal that work in place
- b2CreateDynamicTree now allocates a tree and calls the internal init; b2DestroyDynamicTree ignores null
- Broad-phase builds its three trees in place with the internal pair
- TreeCreateDestroy test uses the internal pair, matching upstream
- B2DynamicTree / B2TreeNode stay public since C# trees are reference types and Samples use them
- b2Compute*AABB -> b2Compute*Bounds renames left to the user

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add b2ComputeChains / b2FreeChains (B2ChainBuilders) that merge polygons into chain loops, with B2ChainStatus, B2ChainData and B2ChainResult
- Builder uses Dictionary<ulong, int> in place of verstable; maps are only looked up, never iterated, so output stays deterministic
- Contacts are no longer recycled after a time of impact unless already touching
- Contact recycling is disabled when either shape enables pre-solve events
- b2Shape_EnablePreSolveEvents refreshes recycle and pre-solve flags on existing contacts
- Fix degenerate ghost vertices on standalone chain segments (create and set)
- Geometric mover skips the back side of chain segments
- Tests: DegenerateGhostTest, MoverOneSidedTest, ComputeChainsTest, PreSolveToggleTest
- Samples, zig, CI and doc changes not ported

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ice1000

ice1000 commented Nov 12, 2026

Copy link
Copy Markdown
Author

Urm sorry, you should definitely not merge this. I accidentally included some changes to the .csproj in the PR. Those weren't meant to be here.

@ice1000 ice1000 closed this Nov 12, 2026
@ice1000

ice1000 commented Nov 12, 2026

Copy link
Copy Markdown
Author

Some numbers from main branch benchmarking:

  • Current: lastest commit
  • Baseline: commit 154bacd

How it runs:

  • All 10 scenarios in tools/Box2D.NET.Benchmark, at 1 worker and 8 workers.
  • Each run repeats 5 times, and the runner keeps the best time.
  • Baseline and current alternate for each scenario, done twice in opposite order, so slow drift on the machine affects both equally.

1 worker

Scenario Baseline (ms) Current (ms) Change
compounds 7302.8 2421.2 −66.8%
joint_grid 4582.9 3303.8 −27.9%
junkyard 18451.0 5655.4 −69.3%
large_pyramid 8379.5 1727.9 −79.4%
many_pyramids 13627.7 2775.0 −79.6%
rain 21290.8 12124.3 −43.1%
smash 5229.2 1883.4 −64.0%
spinner 15952.4 5683.3 −64.4%
tumbler 5334.6 1630.0 −69.4%
washer 20435.8 5778.6 −71.7%

8 workers

Scenario Baseline (ms) Current (ms) Change
compounds 1642.5 692.3 −57.9%
joint_grid 1036.2 647.7 −37.5%
junkyard 4113.1 2019.7 −50.9%
large_pyramid 1517.4 385.4 −74.6%
many_pyramids 3614.8 925.9 −74.4%
rain 6613.6 2958.1 −55.3%
smash 1402.0 572.5 −59.2%
spinner 3536.0 1545.6 −56.3%
tumbler 1275.1 575.1 −54.9%
washer 3860.8 1849.2 −52.1%

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.

1 participant