Skip to content

Cut physics allocations: AFrame as a struct and a transition pool - #4561

Open
Mag-nus wants to merge 1 commit into
ACEmulator:masterfrom
Mag-nus:physics-allocations
Open

Mag-nus wants to merge 1 commit into
ACEmulator:masterfrom
Mag-nus:physics-allocations

Conversation

@Mag-nus

@Mag-nus Mag-nus commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

The problem

On a load of 25 dungeons (429 landblocks, about 12,000 creatures, no players) master allocates about 450 MB a second (451 MB/s, the mean of the two base runs in the A/B below). An allocation trace of master on the same load (2026-11-27) attributes 82% of it to PhysicsObj.update_object. By type, AFrame is 28%, Sphere 17% and Position 12%. Most of it is short-lived scaffolding built again for every object update:

  • AFrame is a class, so every frame combined, copied or offset during an update is a heap object, and so is every Position's frame. Animation (Sequence) and the managers that adjust an offset (PositionManager, StickyManager, ConstraintManager) create more.
  • Every transition builds about 30 objects (~1.75 KB): the Transition and its ObjectInfo, CollisionInfo, CellArray and SpherePath, with their lists. MakeTransition is new Transition(), and CleanupTransition is empty.
  • SpherePath copies positions with new Position(...) each time it saves, restores or sets the check position, and ValidateTransition does the same for the current position.
  • find_cell_list runs add_all_outside_cells again for every land cell already in the array. add_all_outside_cells never sets CellArray.AddedOutside, so the guard that should skip the repeats never fires. Each repeat calls get_landcell again, along with the landblock lookup and lock behind it, 1.7-4.6 times more often than needed.
  • Cells.Values.ElementAt(i) boxes an enumerator on every call (Transition.CheckOtherCells, ObjCell.find_cell_list, PhysicsObj.find_bbox_cell_list). Dictionary.ValueCollection is not an IList.
  • Smaller per-update garbage:
    • UpdateObjectInternal allocates a new Position every update.
    • report_collision_end allocates a List on every successful move, even when the collision table is empty.
    • CylSphere.IntersectsSphere builds the full local-space sphere cache for every cylinder it tests, but only reads its position.
    • EnvCell.find_transit_cells builds a new Sphere for each portal and each sphere.
    • GRotate evaluates CreateFromYawPitchRoll even when the rotation is zero.

The fix

  • AFrame becomes a struct. Its methods that change the frame (Combine with a scale, InterpolateOrigin, InterpolateRotation, GRotate, Rotate, Subtract, set_heading, set_position, set_rotate, set_vector_heading, rotate_around_axis_to_vector) move into AFrameExtensions as this ref extension methods. A call on a copy, such as a property or a method's return value, then fails to compile instead of silently changing the copy. The methods that only read the frame stay on the struct. Code that passed a frame in to be changed now passes it by ref: Sequence.apply_physics, PositionManager.AdjustOffset, StickyManager.adjust_offset, ConstraintManager.adjust_offset and ChessMatch.CalculateWeeniePosition. The frame != null checks in Sequence go, since a struct cannot be null. AFrame frame = null becomes = default in the two places that had it.
  • Transition pool. MakeTransition takes a transition from a per-thread stack ([ThreadStatic], at most 4 kept per thread), and Transition.Release returns it. The callers on the update and visibility paths call it after their last read of the transition: SetPosition, check_collision, transition when the move fails, the three object-update paths that take the transition transition returns, and the four line-of-sight checks in WorldObject. Three callers that run rarely are left as they are and their transitions are collected as before: TryDropItem, /fumble and /nudge. Transitions can nest on one thread, because collision handlers run game code, so the pool is a stack. Reset returns every field of the transition and its parts to the state of new Transition() and drops every reference to objects and cells, so a pooled transition keeps nothing alive. CurPos, CheckPos and BackupCheckPos can be the same object, so Reset gives them new Positions rather than reusing them.
  • Position copies. A new Position.CopyFrom copies the cell ID and frame into an existing position. SpherePath and Transition use it for the check position, its backup and the current position. Where the target can be the same object as another live position (ValidatePlacement sets CurPos = CheckPos), a ReferenceEquals check falls back to new Position(...), as before.
  • add_all_outside_cells sets CellArray.AddedOutside = true, so find_cell_list adds the outside cells once.
  • CellArray.GetCellAt(index) walks the values with the dictionary's struct enumerator and replaces the three ElementAt calls.
  • Smaller per-update garbage:
    • UpdateObjectInternal reuses one scratch Position per PhysicsObj.
    • report_collision_end returns at once when the collision table is empty.
    • CylSphere.IntersectsSphere copies the position into LocalSpacePos, the one field it reads, instead of building the whole cache.
    • CellStruct, BSPTree and BSPNode gain sphere_intersects_cell(center, radius) overloads, which find_transit_cells uses instead of building a Sphere.
    • GRotate skips the multiply when the rotation is zero. Multiplying by the exact identity is exact, so the result is the same bit for bit.

Behaviour

An independent read-only review compared master and this branch path by path and found no difference reachable from a live path. Two differences exist:

  • set_frame with an invalid orientation but a valid origin: master also wrote the zero quaternion into the caller's frame object (an object's RequestPos, for example), and a later normalise turned it into NaN. Now only the object's own position gets the zero quaternion, which set_frame sets in both versions.
  • InterpolationManager stays by value. Passing its frame by ref would have let adjust_offset's frame = offset replace the caller's offset frame. The only difference left is in code with no callers (InterpolateTo, reached only from MoveOrTeleport): master's heading and scaling of the offset also rewrote the queued node's target frame, and now they change a copy.

AFrame.Equals compares frame.Orientation with itself, so any two orientations compare equal. That is on master too, and it moves unchanged here.

Measured

A/B on the dungeon load above, on one 8-core VM (16 GB, .NET 10, Server GC with DATAS) on the night of 2026-11-28. Each run had a 15 minute warm-up and a 45 minute measured window. The runs went in ABBA order so that drift over the night cancels: base, (the memory PR), this PR, this PR, (the memory PR), base. Base is master (65aed57) plus the load-test harness, and the PR build is the same tree plus this diff. The harness touches none of this code. Nothing else ran on the VM during the six windows.

"Pair 1" compares the first PR run with the first base run, and "pair 2" the second with the second. The other columns are the means of two runs each.

Base This PR Change Pair 1 Pair 2
CPU (cores, of 8) 1.621 1.469 -9.4% -9.5% -9.2%
World update, mean (ms) 6.12 5.76 -5.8% -5.8% -5.8%
WorldObject physics (ms) 3.02 2.55 -15.6% -16.3% -14.8%
Monster tick (ms) 15.37 13.92 -9.4% -9.2% -9.6%
Allocation (MB/s) 451 167 -63.0% -63.2% -62.7%
Collections in 45 min 2,290 1,109 -51.6% -52.9% -50.2%
Mean pause (ms) 25.9 38.0 +46.8% +48.9% +44.7%
Total pause in 45 min (s) 59.2 42.1 -28.9% -30.0% -27.9%
Live heap after each gen2, median (GB) 5.96 5.89 -1.3% -0.7% -1.8%
Peak RSS in the window (GB) 11.39 10.87 -4.6% -4.0% -5.1%
  • The times are the server's performance monitor means. The world update is UpdateGameWorld_Entire. The other two rows are WorldObject_Tick_UpdateObjectPhysics and Landblock_Tick_Monster_Tick, which add up the time on every landblock thread, so they can exceed the world update.
  • Both pairs agree on every row. The live heap barely changes, since what this PR removes is short-lived garbage.
  • Longer pauses, fewer of them. With less allocation, the runtime's dynamic GC heap count (DATAS) runs fewer heaps: 6 in this PR's runs against 8 in base's. The first PR run started on 8 and moved to 6 after its first 148 collections. Each heap keeps its own young-generation budget, so collections fall by half while allocation falls by 63%. Each collection's work is split over fewer GC threads, so the mean pause is 47% longer, but total pause falls by 29%.
  • The longer mean pause does not reach the worst cases. The worst world update was 97 and 137 ms on base, and 99 and 94 ms with this PR. The worst 5 seconds of GC pause was 181 and 219 ms on base, and 191 and 145 ms with this PR.

Earlier measurement (2026-11-27, before this A/B)

The same changes were measured earlier in three steps, on the same load in ABBA order with 30 minute windows (the mean of two runs each):

Cores Allocation Collections / 30 min Total pause / 30 min
base 1.618 450 MB/s 1,517 38.5 s
+ the smaller fixes, AddedOutside, GetCellAt, position copies 1.536 (-5.1%) 309 (-31%) 1,046 29.2 s
+ transition pool 1.485 (-8.2%) 228 (-49%) 784 25.3 s
+ AFrame struct 1.451 (-10.4%) 166 (-63%) 725 26.9 s

Each step beat the run-to-run noise (about 1%) in both halves of the ABBA. Those builds differ from this branch only by cleanups (the AFrameExtensions split among them) and by passing InterpolationManager's frame by ref.

Testing

  • ACE.Server.Tests: 16 passed, 4 failed, the same as master. The 4 failures come from the test paths to Config.js.example and starterGear.json.
  • Before the load test, the changes other than the struct were compared with master in a harness that runs the real PhysicsObj.update_object on single objects over real terrain and setups. Over 1,000,000 updates (35,607 cell changes, about 50,000 updates in contact), compared on cell, position, orientation, state and shadow cells after every update, there were no mismatches, and a crowd placement of 1,500 creatures came out the same. A negative control, the unguarded in-place SetCheckPos, gave 161,621 mismatches in 200,000 updates, so the comparison can fail.
  • In the A/B, the PR runs logged no kind of error or warning that the base runs did not, with one exception. The second PR run logged one NullReferenceException from the console serverstatus command, which the harness runs every 10 minutes. It came at worldObject.Missile in AdminStatCommands.HandleServerStatus, so most likely from a null in the list that GetAllWorldObjectsForDiagnostics copies off a landblock's object dictionary. That race is on master: the command copies the dictionary on the console thread while the landblock tick adds and removes objects. This PR doesn't touch that code.

Files

  • Source/ACE.Server/Physics/Animation/AFrame.cs
  • Source/ACE.Server/Physics/Animation/Sequence.cs
  • Source/ACE.Server/Physics/Transition.cs
  • Source/ACE.Server/Physics/SpherePath.cs
  • Source/ACE.Server/Physics/PhysicsObj.cs
  • Source/ACE.Server/Physics/CylSphere.cs
  • Source/ACE.Server/Physics/BSP/BSPNode.cs
  • Source/ACE.Server/Physics/BSP/BSPTree.cs
  • Source/ACE.Server/Physics/Common/CellArray.cs
  • Source/ACE.Server/Physics/Common/CellStruct.cs
  • Source/ACE.Server/Physics/Common/EnvCell.cs
  • Source/ACE.Server/Physics/Common/LandCell.cs
  • Source/ACE.Server/Physics/Common/ObjCell.cs
  • Source/ACE.Server/Physics/Common/Position.cs
  • Source/ACE.Server/Physics/Managers/ConstraintManager.cs
  • Source/ACE.Server/Physics/Managers/PositionManager.cs
  • Source/ACE.Server/Physics/Managers/StickyManager.cs
  • Source/ACE.Server/Physics/Particles/ParticleEmitter.cs
  • Source/ACE.Server/Entity/Chess/ChessMatch.cs
  • Source/ACE.Server/WorldObjects/WorldObject.cs
  • Source/ACE.Server/WorldObjects/WorldObject_Magic.cs

🤖 Generated with Claude Code

- AFrame becomes a struct. Its mutators move to AFrameExtensions as
  `this ref` extension methods, so a call on a copy does not compile;
  callers that change a frame pass it by ref.
- Pool transitions per thread (at most 4), released by the update and
  line-of-sight callers; Reset drops every object and cell reference.
- Copy check, backup and current positions in place (Position.CopyFrom),
  falling back to a new Position where the target may be aliased.
- add_all_outside_cells sets CellArray.AddedOutside, so find_cell_list
  adds the outside cells once.
- CellArray.GetCellAt replaces Cells.Values.ElementAt.
- Reuse a scratch Position in UpdateObjectInternal, return early from
  report_collision_end on an empty table, copy only LocalSpacePos in
  CylSphere.IntersectsSphere, test spheres by center and radius in
  find_transit_cells, and skip GRotate's multiply for a zero rotation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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