Files
lingua-engine/plugins/engine.physics/Engine.Physics/PhysicsWorld.cs
T
EmilandClaude Sonnet 5 cd8f221ddd Fix real bugs from independent review (docs/review-handoff.md)
A second AI session read the whole codebase in parallel (read-only, no
code changes) and left a handoff doc. Addressed the correctness findings:

- PhysicsWorld.Sync's early return compared _bodies.Count to live.Count,
  not their contents — same size, different membership (destroy one
  tracked GameObject, gain one untracked-because-no-collider one; or any
  Restore where the scene has both a Rigidbody+collider object and a
  Rigidbody-without-one) skipped cleanup entirely, leaking the native
  Box3D body forever. Fixed by checking the actual stale set. Two new
  regression tests reproduce the review's own two scenarios via a new
  Lingua_GetBodyCount native export, asserting on the native table's own
  count rather than PhysicsWorld's C#-side bookkeeping.
- TryCreateBody stored handle -1 (native shim refused: invalid world, or
  its 8192-slot body table full) as if it were real — every later
  GetBodyTransform on it silently teleported the GameObject to the
  origin with a degenerate rotation, no error anywhere. Now checked and
  warned once, same as the missing-collider case.
- PluginHost.Load didn't roll back anything when Configure threw partway
  through: Schedule.Add/Events.Subscribe registrations it already made
  stayed forever, and its ALC was never unloaded — neither loaded (no
  _loaded entry) nor cleanly unloadable. Fixed with try/catch: best-effort
  Shutdown (the only thing that knows which services this plugin
  provided), RemoveAllFrom on both Schedule and EventBus, best-effort ALC
  unload, rethrow. New fixture plugin (sandbox.failing-configure, mirrors
  sandbox.echo's own real-load pattern) registers a system against a
  shared Ping component then throws, so FailedConfigureRollbackTests can
  assert the dangling system actually stops firing — an earlier version
  tried to prove this via AssemblyLoadContext.All instead, which passed
  even against the deliberately-reverted buggy code (the ALC turned out
  to get collected either way once its only references went out of
  scope); watching the dangling system is what actually distinguishes
  rolled-back from not, confirmed by deliberately reverting the fix and
  watching this specific test fail before restoring it.
- Engine.Host's "r <id>" left a plugin unloaded on a failed reload with
  no honest indication of that, and retrying threw "not loaded" instead
  of ever reaching Load again. Added PluginHost.IsLoaded so the handler
  only calls Unload when there's something to unload, and the failure
  message now says the plugin is unloaded, not just "failed."
- AssetService.ReloadWithRetry's `when (attempt < 4)` guard meant the
  5th and final IOException fell out of the loop and propagated from a
  discarded fire-and-forget Task — no log, no event, nothing. Now logged.
- EditorState.Selected kept pointing at a GameObject Restore had already
  destroyed after ExitPlay, so Inspector/gizmo would silently keep
  editing something no longer in the world. EditorPlugin.DrawUi now
  compares IsPlaying against its own previous frame (not just reacting to
  the Stop button) so this is caught whether Play was exited via the
  button or the "stop" stdin command — the same stdin-vs-real-control gap
  already hit once earlier this session — and re-resolves the selection
  by name.
- README.md and kernel-contract.md's Event Bus/Time rows had fallen a
  milestone behind (still said "no asset system yet" and "no fixed-step
  accumulator yet" after both shipped).

Full suite: 98 tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1qPfzq8TDCUMFMV3UwV5N
2026-09-02 20:57:08 +03:00

154 lines
5.5 KiB
C#

using System.Numerics;
using Engine.Kernel.Diagnostics;
using Engine.Kernel.World;
using Engine.Physics.Contracts;
namespace Engine.Physics;
/// <summary>
/// Owns the one native Box3D world this plugin creates, and the GameObject
/// &lt;-&gt; native body handle mapping. <see cref="Sync"/> creates bodies for
/// any GameObject that's grown a Rigidbody since last frame and destroys
/// bodies for any that lost one (component removed, or the GameObject
/// itself was destroyed) — there's no destruction event to hook, so this
/// diffs Query&lt;Rigidbody&gt;() against the tracked set every FixedUpdate
/// instead. <see cref="Step"/> advances the simulation once and writes
/// every tracked body's new transform back into its GameObject.
/// </summary>
internal sealed class PhysicsWorld : IDisposable
{
private readonly int _handle;
private readonly ILogger _log;
private readonly Dictionary<GameObject, int> _bodies = [];
private readonly HashSet<GameObject> _warnedFailed = [];
public PhysicsWorld(Vector3 gravity, ILogger log)
{
_log = log;
_handle = Native.Lingua_CreateWorld(gravity.X, gravity.Y, gravity.Z);
}
public void Sync(IWorld world)
{
var live = new HashSet<GameObject>();
foreach (var go in world.Query<Rigidbody>())
{
live.Add(go);
if (!_bodies.ContainsKey(go))
TryCreateBody(go);
}
// Comparing counts alone would miss this: destroying one tracked
// GameObject and gaining a different untracked one in the same
// Sync leaves _bodies.Count == live.Count with the sets actually
// different — the stale native body would never get destroyed and
// would keep simulating forever. Restore (every ExitPlay) hits
// this reliably whenever the scene has both a Rigidbody+collider
// GameObject and a Rigidbody-without-collider one, since the
// latter never enters _bodies to begin with.
var stale = _bodies.Keys.Where(go => !live.Contains(go)).ToList();
if (stale.Count == 0)
return;
foreach (var go in stale)
{
Native.Lingua_DestroyBody(_bodies[go]);
_bodies.Remove(go);
_warnedFailed.Remove(go);
}
}
public void Step(float timeStep, int subStepCount = 4)
{
Native.Lingua_WorldStep(_handle, timeStep, subStepCount);
foreach (var (go, handle) in _bodies)
{
Native.Lingua_GetBodyTransform(handle, out var px, out var py, out var pz, out var qx, out var qy, out var qz, out var qw);
var t = go.Transform;
t.LocalPosition = new Vector3(px, py, pz);
t.LocalRotation = new Quaternion(qx, qy, qz, qw);
go.Transform = t;
}
}
public void ApplyLinearImpulse(GameObject go, Vector3 impulse, bool wake)
{
if (_bodies.TryGetValue(go, out var handle))
Native.Lingua_ApplyLinearImpulse(handle, impulse.X, impulse.Y, impulse.Z, wake);
}
public Vector3 GetLinearVelocity(GameObject go)
{
if (!_bodies.TryGetValue(go, out var handle))
return Vector3.Zero;
Native.Lingua_GetLinearVelocity(handle, out var vx, out var vy, out var vz);
return new Vector3(vx, vy, vz);
}
public void SetLinearVelocity(GameObject go, Vector3 velocity)
{
if (_bodies.TryGetValue(go, out var handle))
Native.Lingua_SetLinearVelocity(handle, velocity.X, velocity.Y, velocity.Z);
}
private void TryCreateBody(GameObject go)
{
var rb = go.GetComponent<Rigidbody>()!;
var pos = go.Transform.LocalPosition;
var rot = go.Transform.LocalRotation;
var box = go.GetComponent<BoxCollider>();
var sphere = go.GetComponent<SphereCollider>();
int handle;
if (box is not null)
{
handle = Native.Lingua_CreateBoxBody(
_handle, pos.X, pos.Y, pos.Z, rot.X, rot.Y, rot.Z, rot.W,
box.HalfExtents.X, box.HalfExtents.Y, box.HalfExtents.Z,
(int)rb.Type, rb.Density, rb.Friction, rb.Restitution);
}
else if (sphere is not null)
{
handle = Native.Lingua_CreateSphereBody(
_handle, pos.X, pos.Y, pos.Z, rot.X, rot.Y, rot.Z, rot.W,
sphere.Radius, (int)rb.Type, rb.Density, rb.Friction, rb.Restitution);
}
else
{
if (_warnedFailed.Add(go))
_log.Warn($"'{go.Name}' has a Rigidbody but no BoxCollider/SphereCollider — no physics body created.");
return;
}
// -1 means the native shim refused (an invalid world handle, or
// its fixed-capacity body table — 8192 — is full). Storing it
// anyway would silently "work": every later Lingua_GetBodyTransform
// call on handle -1 fails ValidBody's check and leaves the out
// params at their P/Invoke-zeroed default, teleporting the
// GameObject to the origin with a degenerate all-zero rotation
// every FixedUpdate — no exception, no log, just a wrong position.
if (handle < 0)
{
if (_warnedFailed.Add(go))
_log.Warn($"'{go.Name}' failed to create a native physics body (world invalid or body table full).");
return;
}
_bodies[go] = handle;
}
public void Dispose()
{
foreach (var handle in _bodies.Values)
Native.Lingua_DestroyBody(handle);
_bodies.Clear();
Native.Lingua_DestroyWorld(_handle);
}
}