Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afd8071dac | ||
|
|
73944c15ed | ||
|
|
424502904d | ||
|
|
97400a7857 | ||
|
|
5fbb4c0adb | ||
|
|
4e6c69938b | ||
|
|
75f324a7b8 | ||
|
|
ee8ac211d2 | ||
|
|
48aded2e69 | ||
|
|
50d2252f21 | ||
|
|
c635c170fc | ||
|
|
44c8463e6f | ||
|
|
d5f05673ea | ||
|
|
1d271148d3 | ||
|
|
81da81150b | ||
|
|
bd443efd3e | ||
|
|
aabfccf837 | ||
|
|
f3af17ea07 | ||
|
|
80bf68d44a | ||
|
|
1879021cf9 | ||
|
|
b1fa7300b2 | ||
|
|
b82a0b094f | ||
|
|
41f9179fb0 | ||
|
|
0f861430f4 | ||
|
|
bbc5628b4f | ||
|
|
e3c01bed9e | ||
|
|
e51cf76202 | ||
|
|
1cce42207a | ||
|
|
92d390c0a3 | ||
|
|
620af79161 | ||
|
|
b128ad42e5 | ||
|
|
b973df418e | ||
|
|
66f9440a36 | ||
|
|
2cb5b588bc | ||
|
|
99d0d26656 | ||
|
|
e1f1449927 | ||
|
|
f2797fa0dd | ||
|
|
32578bd109 | ||
|
|
da5ef233a5 | ||
|
|
0b87fbe37c | ||
|
|
32df139679 | ||
|
|
2e04ba94f5 | ||
|
|
d82da6d1ff | ||
|
|
335b66247d | ||
|
|
881a209e9a | ||
|
|
1d2b9d9fdf | ||
|
|
97640b30b6 | ||
|
|
89e401bc20 | ||
|
|
908a68782b | ||
|
|
078f4b6456 | ||
|
|
23b28cf9e1 | ||
|
|
c0dde04f01 | ||
|
|
1212edd3ee | ||
|
|
92e446a4f6 | ||
|
|
4ddcf7bc9c | ||
|
|
0ccedf22dc | ||
|
|
888117dc5c | ||
|
|
c6365d4d85 | ||
|
|
35b0b6d7f9 | ||
|
|
e71c731bd5 | ||
|
|
9d19d37c89 | ||
|
|
0fc389db7c | ||
|
|
f91450a97a | ||
|
|
9963da70b2 | ||
|
|
b95b218281 | ||
|
|
e94977fe0b | ||
|
|
7bb53119d7 | ||
|
|
3af239e7da | ||
|
|
217c640c4b | ||
|
|
50f54582c8 | ||
|
|
bb35465623 | ||
|
|
db3fd95eba | ||
|
|
cdf79b197d | ||
|
|
a28318ccbb | ||
|
|
ca237bb0af | ||
|
|
d95cde3047 | ||
|
|
c2f905452c | ||
|
|
d9a60f52c1 | ||
|
|
f62dea38af | ||
|
|
5de7e05814 | ||
|
|
9ffc3cc21b | ||
|
|
761e4c1568 | ||
|
|
66179d68b4 | ||
|
|
5a383c4d5e | ||
|
|
73d43637f1 | ||
|
|
a4e7139188 | ||
|
|
fb77d15a94 | ||
|
|
5104b176a1 | ||
|
|
037c9da9c2 | ||
|
|
be21de1959 | ||
|
|
e856403e27 | ||
|
|
c5e4e34825 | ||
|
|
99f1d0bfaf | ||
|
|
72e9d3e71e | ||
|
|
6c90bd10f7 | ||
|
|
e530b9b97d | ||
|
|
55d0e0f0bd | ||
|
|
2f78cfa8f5 | ||
|
|
83ea2b8fa4 | ||
|
|
6edf5d671c | ||
|
|
586361ad67 | ||
|
|
cec6d0d464 | ||
|
|
7efcefc8a0 | ||
|
|
e4cf4cd444 | ||
|
|
5c35a40ccf | ||
|
|
a614477d68 | ||
|
|
5a4cde33ae | ||
|
|
d54e14cc50 | ||
|
|
8be057a4b1 | ||
|
|
617beec1dc | ||
|
|
0b0321aa00 | ||
|
|
db09805aba | ||
|
|
fbc1530fa5 | ||
|
|
e6a1e4ad02 | ||
|
|
eb30cac65b | ||
| 7ba31c30fc | |||
| 78786670eb |
75 changed files with 15221 additions and 8691 deletions
2
.gitmodules
vendored
2
.gitmodules
vendored
|
|
@ -1,3 +1,3 @@
|
|||
[submodule "extern/box3d"]
|
||||
path = extern/box3d
|
||||
url = https://github.com/erincatto/box3d.git
|
||||
url = https://eureka.gamecult.org/forge/GameCult/box3d.git
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
# Ymir Persona State
|
||||
|
||||
`ymir.cc` is Ymir's repo-local persistent Persona state.
|
||||
|
||||
Do not hand-edit the `.cc` file. Use the repo-local tools:
|
||||
|
||||
```powershell
|
||||
.\tools\persona-state-read.ps1
|
||||
.\tools\persona-remember.ps1 -Summary "..." -Claim "..." -Tension "..." -ActionImplication "..."
|
||||
```
|
||||
|
||||
The tools call VoidBot's typed self-state service so the same document schema
|
||||
used by registered repo Faces owns mutation and reads.
|
||||
|
||||
VoidBot automatic indexing requires Ymir to be registered as a repo Face
|
||||
identity in VoidBot. Until then, this file is local typed state and can still be
|
||||
read or mutated by the tools here.
|
||||
Binary file not shown.
|
|
@ -1,23 +0,0 @@
|
|||
{
|
||||
"id": "ymir",
|
||||
"repoName": "Ymir",
|
||||
"repoPath": "E:/Projects/Ymir",
|
||||
"displayName": "Ymir",
|
||||
"description": "Ymir Face for the Ymir repo: the world-body physics substrate for GameCult. Ymir should speak with plain, heavy precision: body, field, contact, impulse, witness, cut. It cares about moving physics truth out of Unity and into a coherent CultMath/CultCache/CultMesh-owned substrate without letting adapters, renderers, or debug surfaces pretend to own the world.",
|
||||
"grants": [
|
||||
"discussion",
|
||||
"rumination",
|
||||
"repo_read",
|
||||
"repo_propose"
|
||||
],
|
||||
"jurisdictions": [
|
||||
{
|
||||
"kind": "repo",
|
||||
"id": "Ymir",
|
||||
"repoName": "Ymir",
|
||||
"path": "E:/Projects/Ymir",
|
||||
"authority": "propose"
|
||||
}
|
||||
],
|
||||
"faceStatePath": "E:/Projects/Ymir/.voidbot/state/ymir.cc"
|
||||
}
|
||||
55
AGENTS.md
55
AGENTS.md
|
|
@ -1,55 +1,10 @@
|
|||
# Ymir Agent Instructions
|
||||
|
||||
Ymir owns authoritative physics sessions and their GameCult contracts. Box3D
|
||||
owns the physics algorithms inside those sessions. Treat Unity, products,
|
||||
renderers, editor tools, and dashboards as clients or adapters unless a
|
||||
document explicitly transfers authority.
|
||||
|
||||
Before substantial implementation, state:
|
||||
|
||||
- Objective: what physical invariant or cutover outcome the work serves.
|
||||
- Current mechanism: how bodies, fields, contacts, and commands flow now.
|
||||
- Invariants: what must remain true during direct load, step, query, adapter
|
||||
playback, and reload.
|
||||
- Intended change: which owner or data path becomes simpler.
|
||||
- Cut line: which old callback, cache, adapter, or compatibility path may be
|
||||
deleted or demoted.
|
||||
Ymir provides the 3D SoA rigid-body and PBD/SPH particle boundary (`Ymir.Box3D` and `native/Ymir.Box3D`) around pinned Box3D (`extern/box3d`), consumed by `Lodur` and `BadDaySimulator`. Box3D owns rigid integration, collision geometry, broadphase, joints, and contact solving.
|
||||
|
||||
Architecture constraints:
|
||||
|
||||
- Do not reimplement Box3D integration, collision geometry, broadphase,
|
||||
queries, solver behavior, contact lifecycle, or numeric tolerances.
|
||||
Physics edge cases follow the pinned Box3D release. Executable parity tests
|
||||
witness selected released behaviors; they are not a second specification.
|
||||
- `Ymir.Core` owns typed contracts, stable-id projection, session commands,
|
||||
deterministic ordering, persistence reconstruction, and publication. The
|
||||
native Ymir wrapper owns Box3D ABI isolation. Daemon, Unity, and future Rust
|
||||
or CultMesh surfaces consume those boundaries without importing Box3D
|
||||
internals.
|
||||
- Use CultMath for GameCult-side numeric projections and force preparation. It
|
||||
must not become a second integration or collision engine. Do not copy
|
||||
Unity.Mathematics helpers into Ymir.
|
||||
- JSON is allowed at HTTP/CLI compatibility boundaries. It is not durable truth.
|
||||
Durable state should move toward CultCache `.cc` documents and CultMesh
|
||||
publication.
|
||||
- Keep adapters boring. A Unity adapter may submit commands, receive snapshots,
|
||||
and render them; it must not silently repair or override Ymir state.
|
||||
- During cutover, provider advertisements and operator state must describe the
|
||||
running implementation. Target Box3D/CultMesh capabilities are not live
|
||||
capabilities until their production paths exist.
|
||||
- Aetheria embeds Ymir. Eve clients connect directly to Aetheria's advertised
|
||||
CultMesh provider; standalone Ymir and rendezvous services are not in the
|
||||
Aetheria gameplay path.
|
||||
- Add tests at the layer where the invariant lives. State invariants belong in
|
||||
`Ymir.Core`; daemon route shape belongs in daemon smokes; Unity visual timing
|
||||
bugs need Unity-side probes.
|
||||
|
||||
Persona and persistent memory:
|
||||
|
||||
- Ymir's repo Face identity lives in `.voidbot/voice/identity.json`.
|
||||
- Ymir's Persona state path is `.voidbot/state/ymir.cc`.
|
||||
- Read state with `tools/persona-state-read.ps1`.
|
||||
- Write durable repo memories with `tools/persona-remember.ps1`; do not hand-edit
|
||||
`.cc` state.
|
||||
- Preserve lessons that steer future ownership, cutover, invariants, and
|
||||
failure modes. Do not commemorate every small patch.
|
||||
- Do not reimplement Box3D rigid integration, collision geometry, broadphase, queries, or solver behavior in managed code.
|
||||
- Keep `native/Ymir.Box3D` free of gameplay policy: Box3D and the particle solver decide physics; consumers (`Lodur`, `BadDaySimulator`) own gameplay policy, limb control, and teardown rules.
|
||||
- Read `docs/soa-world.md` before changing ABI 21 structs or lane layouts; update both native `ymir_box3d_soa.c` size/ABI checks and managed `Box3DSoaWorld.cs` structs together.
|
||||
- Add tests in `tests/Ymir.Box3D.Soa.Tests/` at the layer where the invariant lives, and run the suite on a build host matching the target platform (Linux builds/tests run on Yggdrasil).
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<CultLibRoot Condition="'$(CultLibRoot)' == '' and '$(CULTLIB_ROOT)' != ''">$(CULTLIB_ROOT)</CultLibRoot>
|
||||
<CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot>
|
||||
<!-- CultLib 2.0.0: tag cultlib-unity-v2.0.0. -->
|
||||
<CultLibRevision>42dce3611a81adc5c5fac54cadbaa5637d6022d3</CultLibRevision>
|
||||
<GitExecutable Condition="'$(GitExecutable)' == '' and Exists('C:\Program Files\Git\cmd\git.exe')">C:\Program Files\Git\cmd\git.exe</GitExecutable>
|
||||
<GitExecutable Condition="'$(GitExecutable)' == ''">git</GitExecutable>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
<Project>
|
||||
<!-- Builds consume CultLib at one admitted revision. Point CultLibRoot (or CULTLIB_ROOT) at a clean
|
||||
worktree of that revision: git worktree add <path> cultlib-unity-v2.0.0 (detached) (in CultLib). -->
|
||||
<Target Name="VerifyCultLibRevision"
|
||||
BeforeTargets="ResolveProjectReferences"
|
||||
Condition="'$(SkipCultLibRevisionCheck)' != 'true'">
|
||||
<ItemGroup>
|
||||
<_CultLibReference Include="@(ProjectReference)"
|
||||
Condition="$([System.String]::Copy('%(Filename)').StartsWith('GameCult.')) or '%(Filename)' == 'CultMath'" />
|
||||
</ItemGroup>
|
||||
<Error Condition="'@(_CultLibReference)' != '' and !Exists('$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj')"
|
||||
Text="CultLibRoot '$(CultLibRoot)' is not a CultLib checkout." />
|
||||
<Exec Condition="'@(_CultLibReference)' != ''"
|
||||
Command=""$(GitExecutable)" -C "$(CultLibRoot)" rev-parse HEAD"
|
||||
ConsoleToMSBuild="true"
|
||||
StandardOutputImportance="Low">
|
||||
<Output TaskParameter="ConsoleOutput" PropertyName="ActualCultLibRevision" />
|
||||
</Exec>
|
||||
<Error Condition="'@(_CultLibReference)' != '' and '$([System.String]::Copy($(ActualCultLibRevision)).Trim())' != '$(CultLibRevision)'"
|
||||
Text="CultLib must be revision $(CultLibRevision) (cultlib-unity-v2.0.0); found $([System.String]::Copy($(ActualCultLibRevision)).Trim()). Set CultLibRoot to a clean worktree of that tag." />
|
||||
<Exec Condition="'@(_CultLibReference)' != ''"
|
||||
Command=""$(GitExecutable)" -C "$(CultLibRoot)" status --porcelain --untracked-files=normal"
|
||||
ConsoleToMSBuild="true"
|
||||
StandardOutputImportance="Low">
|
||||
<Output TaskParameter="ConsoleOutput" PropertyName="CultLibStatus" />
|
||||
</Exec>
|
||||
<Error Condition="'@(_CultLibReference)' != '' and '$([System.String]::Copy($(CultLibStatus)).Trim())' != ''"
|
||||
Text="CultLibRoot '$(CultLibRoot)' must be clean before this repo consumes it." />
|
||||
</Target>
|
||||
</Project>
|
||||
158
README.md
158
README.md
|
|
@ -1,162 +1,24 @@
|
|||
# Ymir
|
||||
|
||||
Ymir is the GameCult library and service boundary around a pinned Box3D
|
||||
release, being cut over into Aetheria's authoritative embedded physics
|
||||
substrate. The name means **Not Invented Here**. We are taking the hint.
|
||||
Ymir is GameCult's 3D physics boundary around a pinned Box3D release (`extern/box3d`), consumed directly by `Lodur` and `BadDaySimulator`.
|
||||
|
||||
Box3D owns physics algorithms. Ymir owns the service boundary that makes those
|
||||
algorithms usable as durable, typed GameCult world truth. Unity, renderers, and
|
||||
game products consume Ymir state and contact facts; they do not become physics
|
||||
authorities.
|
||||
Box3D owns rigid-body integration, collision geometry, broadphase, joints, and contact solving. Ymir adds a C17 native SoA wrapper (`native/Ymir.Box3D`) with an embedded XPBD solid + SPH fluid particle solver (`ymir_particles.c`) and a managed `.NET 8` binding (`src/Ymir.Box3D`, package `GameCult.Ymir.Box3D`).
|
||||
|
||||
The production runtime path is a retained Box3D session. The parity facade
|
||||
witnesses released behavior at the native boundary; Ymir adds stable ids,
|
||||
typed commands and facts, replay memory, and deterministic projection without
|
||||
installing a second solver.
|
||||
## Entry Points
|
||||
|
||||
## Front Door
|
||||
|
||||
- **Value:** a retained Box3D physics session with GameCult world truth around it: stable entity ids, explicit mutation receipts, typed contact facts (Begin/Hit/End), replay-backed checkpoints, and deterministic result ordering.
|
||||
- **Problem:** physics authority must not be split between Unity callbacks, gameplay geometry tests and a managed solver. Box3D decides physics, Ymir owns the service boundary, Aetheria supplies intent.
|
||||
- **Entry points:**
|
||||
- `src/Ymir.Core/YmirSession.cs`: the public in-process retained session (commands, receipts, stepping, queries, `CapturePersistence`). `YmirSimulator.cs` is the snapshot facade that wraps an isolated session.
|
||||
- `src/Ymir.Box3D/` and `native/Ymir.Box3D/`: the native session ABI and the Ymir-owned Box3D shim (`GameCult.Ymir.Box3D` package).
|
||||
- `tests/Ymir.Box3D.Parity/`: the executable parity contract against pinned Box3D v0.1.0 (`docs/box3d-parity.md`).
|
||||
- `src/Ymir.Box3D/Box3DSoaWorld.cs` and `native/Ymir.Box3D/ymir_box3d_soa.c`: a headless 3D world (gravity, free rotation) whose state is a structure-of-arrays view read in place (`docs/soa-world.md`). Early slice for Lodur and Bad Day Simulator; spheres and static boxes only.
|
||||
- `docs/architecture.md`, `docs/retained-session-contract.md`, `docs/aetheria-cutover.md`.
|
||||
- Build and test: `git submodule update --init --recursive`, then `dotnet test Ymir.slnx` (needs CMake and a C17 compiler).
|
||||
- **Live:** retained sessions, replay-backed checkpoint reconstruction, parity for overlap and cast queries, tractor membership, contact-begin facts, restitution, torque lifetime, collision filtering and bullet CCD. Aetheria embeds one session per run and zone and stores persistence in a daemon-private CultCache. Package version `0.3.0`.
|
||||
- **Planned:** journal compaction, Linux and macOS package RIDs (built and smoked on their own workers), a committed release smoke for packaging, and the optional standalone daemon (`src/ymir-daemon` is a thin command host today and is never in Aetheria's gameplay path).
|
||||
|
||||
## Target Ownership
|
||||
|
||||
- Box3D owns rigid-body integration, collision geometry, broadphase, solver
|
||||
behavior, continuous collision, overlap and cast semantics, contact
|
||||
lifecycle, force and torque lifetime, tolerances, and deterministic step
|
||||
behavior for identical recorded inputs.
|
||||
- Ymir owns the pinned Box3D version, stable GameCult entity ids,
|
||||
native ABI isolation, public in-process retained sessions, explicit mutation
|
||||
receipts, typed contact facts, snapshot lowering, deterministic result
|
||||
ordering, versioned CultCache snapshots.
|
||||
- An optional Ymir daemon may own named session routing, durable command receipts,
|
||||
checkpoint reconstruction, CultMesh command/fact publication, and process
|
||||
supervision for worlds it hosts. It is not part of Aetheria's gameplay path.
|
||||
- Aetheria owns gameplay policy and supplies typed physical intent: bodies,
|
||||
fields, tractor targets, forces, projectiles, filters, and the gameplay
|
||||
consequences of Ymir contact facts.
|
||||
- CultMath remains available for GameCult-side numeric projections and force
|
||||
preparation. It is not a second collision or integration engine.
|
||||
- Unity and Eve lowerers render world state and submit commands. They never
|
||||
repair, override, or independently simulate authoritative physics.
|
||||
|
||||
Box3D opaque handles are process-local derived state. They are never durable
|
||||
entity ids and never cross the public contract boundary.
|
||||
|
||||
Ymir does not promise bit-identical continuation from an arbitrary mid-world
|
||||
snapshot. Replay starts from canonical creation order plus the complete command
|
||||
stream. Checkpoints may accelerate numeric state recovery within named
|
||||
tolerances, but authoritative contact lifecycle facts resume only after that
|
||||
canonical history has been replayed through the checkpoint tick.
|
||||
|
||||
## Aetheria Deployment Boundary
|
||||
|
||||
Aetheria embeds the Ymir library and native Box3D wrapper in its own daemon.
|
||||
The Aetheria daemon owns gameplay ticks, world policy, player sessions,
|
||||
commands, receipts, assets, and the Eve/CultMesh provider advertisement.
|
||||
Generic Eve clients connect directly to Aetheria; they do not connect through
|
||||
Ymir or a rendezvous service.
|
||||
|
||||
A future standalone Ymir daemon may expose the same physics contract for
|
||||
tooling or other products. It is not an intermediary in Aetheria's gameplay
|
||||
path and must never become a competing copy of Aetheria world truth.
|
||||
|
||||
## Current Cutover State
|
||||
|
||||
Box3D v0.1.0 is pinned at commit
|
||||
`8441b4a06d6d09dcfb0b0f704df4d847d1437b92`. A Ymir-owned native shim and
|
||||
parity suite already witness released Box3D behavior for:
|
||||
|
||||
- sphere overlap and shape casts
|
||||
- tractor capsule membership and rounded caps
|
||||
- numeric overlap and cast slop
|
||||
- planar sphere-world stepping
|
||||
- contact-begin facts
|
||||
- restitution mixing
|
||||
- transient torque lifetime
|
||||
- category/mask/group collision filtering
|
||||
- bullet CCD against kinematic bodies, including Box3D's next-step contact-event timing
|
||||
|
||||
The production `Ymir.Box3D` boundary owns the native session ABI. The legacy
|
||||
snapshot `YmirSimulator.Step` contract now creates an isolated Box3D session,
|
||||
projects the result, and disposes it. It contains no managed integrator,
|
||||
collision loop, or impulse solver.
|
||||
|
||||
That snapshot facade deliberately does not pretend to own long-lived world
|
||||
identity. The public in-process `YmirSession` now exposes explicit body
|
||||
mutations, force and torque commands, revisioned receipts, retained stepping,
|
||||
and typed Begin/Hit/End facts. It never treats omission as removal. Aetheria
|
||||
embeds one session per run and zone; its old process-wide simulator objects
|
||||
are not session identifiers. Revision-checked
|
||||
retained-session circle overlap and cast queries observe the current stable-id
|
||||
body projection without mutating it. Replay-backed checkpoint reconstruction is
|
||||
implemented. `CapturePersistence` emits only the journal suffix not yet stored
|
||||
by its host plus a bounded resume descriptor; restore verifies contiguous
|
||||
chunks, the complete journal digest, the projected world, and active contact
|
||||
episodes before the session can emit facts. Aetheria stores those records in a
|
||||
daemon-private CultCache and uses its hard-flushed public frame as the commit
|
||||
marker. Journal compaction and non-Windows RID artifacts remain cutover work.
|
||||
|
||||
See [the architecture map](docs/architecture.md) and
|
||||
[the executable parity contract](docs/box3d-parity.md). The
|
||||
[retained-session contract](docs/retained-session-contract.md) records the
|
||||
current ownership cut shared by embedded and optional standalone hosts.
|
||||
- `src/Ymir.Box3D/Box3DSoaWorld.cs`: managed 3D SoA world (`Box3DSoaWorld`, `Box3DSoaView`, `Box3DSoaFacts`) exposing contiguous body, joint, particle, constraint, wet-patch, and sensor lanes read in place.
|
||||
- `native/Ymir.Box3D/ymir_box3d_soa.c` and `native/Ymir.Box3D/ymir_particles.c`: native SoA world (ABI 21) and PBD/SPH particle engine built into `ymir_box3d` (`ymir_box3d.dll` / `libymir_box3d.so` / `libymir_box3d.dylib`).
|
||||
- `tests/Ymir.Box3D.Soa.Tests/`: xUnit verification suite covering rigid dynamics, joints, grabs, contact facts, impulses, removals, particles, cloth/rope coupling, fluids, wet patches, and sensors.
|
||||
- `docs/soa-world.md`: SoA world contract, lane semantics, and measured bounds.
|
||||
- `docs/box3d-parity.md`: pinned Box3D fork provenance (`extern/box3d`) and observed upstream behavior.
|
||||
|
||||
## Build And Test
|
||||
|
||||
Initialize the pinned dependency and run the solution:
|
||||
Initialize the pinned Box3D submodule and build/test with CMake + a C17 compiler:
|
||||
|
||||
```powershell
|
||||
git submodule update --init --recursive
|
||||
dotnet test Ymir.slnx
|
||||
```
|
||||
|
||||
The parity project builds the native shim from source and requires CMake plus a
|
||||
C17 compiler:
|
||||
|
||||
```powershell
|
||||
dotnet test tests\Ymir.Box3D.Parity\Ymir.Box3D.Parity.csproj
|
||||
```
|
||||
|
||||
Box3D is MIT licensed. Its license is retained in `extern/box3d`.
|
||||
|
||||
`GameCult.Ymir.Box3D` packages the managed boundary, Box3D license, and native
|
||||
facade under `runtimes/<rid>/native`. A local Windows x64 package has loaded in
|
||||
an isolated empty consumer without CMake or the submodule. A committed release
|
||||
smoke is still required before that is a repeatable packaging guarantee. Linux
|
||||
and macOS packages must be produced and smoked on their own release workers
|
||||
before those RIDs are advertised.
|
||||
|
||||
The current package version is `0.3.0`. ABI v5 exposes the exact pinned native
|
||||
build identity plus Box3D body type,
|
||||
bullet, field-participation, and collision-filter configuration without
|
||||
exposing Box3D handles. These are Ymir contract fields, but their behavior is
|
||||
Box3D behavior.
|
||||
|
||||
## Cutover Rule
|
||||
|
||||
A Ymir cutover is complete only when all runtime stepping, collision queries,
|
||||
and contact facts come from Box3D through an explicitly owned Ymir session.
|
||||
Manual Unity callbacks and Aetheria geometry tests must be structurally unable
|
||||
to decide the result. Snapshot compatibility calls may use isolated sessions;
|
||||
they are not allowed to infer or share retained-world identity.
|
||||
|
||||
## Building against CultLib
|
||||
|
||||
Builds are pinned to CultLib 2.0.0 (tag `cultlib-unity-v2.0.0`, revision `42dce3611a81adc5c5fac54cadbaa5637d6022d3`); the build fails if the CultLib checkout differs or is dirty. Create a pinned worktree and point the build at it:
|
||||
|
||||
```powershell
|
||||
git -C <CultLib> worktree add --detach <path> cultlib-unity-v2.0.0
|
||||
dotnet build -p:CultLibRoot=<path> # or set CULTLIB_ROOT=<path>
|
||||
```
|
||||
|
||||
Without an override the sibling `..\CultLib` checkout is used and must itself be at that tag.
|
||||
Box3D is MIT licensed; its license is retained in `extern/box3d/LICENSE` and packed in `GameCult.Ymir.Box3D`.
|
||||
|
|
|
|||
|
|
@ -1,13 +1,8 @@
|
|||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/ymir-daemon/ymir-daemon.csproj" />
|
||||
<Project Path="src/Ymir.Box3D/Ymir.Box3D.csproj" />
|
||||
<Project Path="src/Ymir.Core/Ymir.Core.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj" />
|
||||
<Project Path="tests/Ymir.Box3D.Soa.Tests/Ymir.Box3D.Soa.Tests.csproj" />
|
||||
<Project Path="tests/Ymir.Tests/Ymir.Tests.csproj" />
|
||||
</Folder>
|
||||
<Project Path="../CultLib/packages/cultmath/src/CultMath/CultMath.csproj" />
|
||||
</Solution>
|
||||
|
|
|
|||
|
|
@ -1,42 +0,0 @@
|
|||
# Aetheria Cutover Notes
|
||||
|
||||
## First Slice
|
||||
|
||||
Cut over projectile travel and impact discovery before trying to replace every
|
||||
Unity physics use.
|
||||
|
||||
1. Spawn a Ymir body for each projectile and relevant target hull/contact shape.
|
||||
2. Step Ymir on the same fixed tick used by Aetheria gameplay.
|
||||
3. Render Unity projectile GameObjects from Ymir snapshots.
|
||||
4. Convert Ymir contacts into Aetheria hit/splash policy.
|
||||
5. Keep Unity colliders as visual/debug witnesses only during the transition.
|
||||
6. Delete or neuter collider callbacks once the Ymir path owns hit truth.
|
||||
|
||||
## Negative Checks
|
||||
|
||||
- A projectile with a Unity collider disabled still travels and hits through
|
||||
Ymir.
|
||||
- A Unity `OnCollisionEnter` callback cannot apply damage independently.
|
||||
- Replaying from the same canonical creation order and command stream under the
|
||||
accepted Box3D build produces the same ordered Ymir facts.
|
||||
- Restarting from a checkpoint matches named numeric state tolerances. It emits
|
||||
no authoritative gameplay contact facts until canonical history has replayed
|
||||
through the checkpoint tick and restored exact contact lifecycle identity.
|
||||
- Mid-flight visible projectile position matches the Ymir snapshot within a
|
||||
named tolerance.
|
||||
|
||||
## Adapter Boundary
|
||||
|
||||
Unity adapter code may:
|
||||
|
||||
- submit spawn/despawn/field/body commands
|
||||
- receive snapshots and contacts
|
||||
- render GameObjects from snapshots
|
||||
- publish diagnostics
|
||||
|
||||
Unity adapter code may not:
|
||||
|
||||
- alter positions as a hidden repair loop
|
||||
- apply gameplay damage from Unity collisions
|
||||
- maintain a parallel physics cache that can override Ymir
|
||||
- treat scene hierarchy as the source of simulation truth
|
||||
|
|
@ -1,237 +0,0 @@
|
|||
# Ymir Architecture
|
||||
|
||||
## Objective
|
||||
|
||||
Expose Box3D as authoritative, typed, persistent GameCult physics without
|
||||
leaking an alpha native API into products, clients, or durable state.
|
||||
|
||||
Ymir's target is a stable embedded wrapper around retained Box3D worlds, not an
|
||||
independent physics-engine research project. Box3D supplies the physics mind.
|
||||
Ymir supplies the memory, nerves, names, and session boundary. The same
|
||||
boundary may optionally be hosted as a standalone daemon.
|
||||
|
||||
## Target Owner
|
||||
|
||||
A long-lived Box3D `b3World` owns the physical decision: given the current
|
||||
world plus commands for a fixed step, what transforms, velocities, overlaps,
|
||||
casts, and contact transitions are true.
|
||||
|
||||
Ymir owns the enclosing session and contract:
|
||||
|
||||
- pin and build the accepted Box3D release;
|
||||
- map stable GameCult ids to transient Box3D handles;
|
||||
- accept typed body, shape, filter, force, torque, field, query, and step
|
||||
commands;
|
||||
- project Box3D outputs into typed, deterministically ordered Ymir facts;
|
||||
- reconstruct sessions from CultCache checkpoints;
|
||||
- return typed state, contacts, queries, and receipts to an embedding product;
|
||||
- when running standalone, publish Ymir's own physics provider and operator
|
||||
surfaces through CultMesh;
|
||||
- supervise world lifetime, failure, replay, and observability.
|
||||
|
||||
## Deployment Boundary
|
||||
|
||||
For Aetheria, Ymir is an embedded library. Aetheria owns the outer daemon,
|
||||
gameplay session, fixed tick, product commands and receipts, asset catalog, and
|
||||
advertised Eve/CultMesh surface. Generic Eve clients connect directly to the
|
||||
Aetheria daemon. They never import Ymir internals and do not route gameplay
|
||||
through a standalone Ymir or discovery service.
|
||||
|
||||
A standalone Ymir daemon is an optional hosting mode for physics tooling and
|
||||
other products. It hosts the same Ymir session primitive; it is not an
|
||||
Aetheria relay and cannot own a shadow copy of Aetheria's world.
|
||||
|
||||
## Current Body
|
||||
|
||||
The runtime solver cut is complete: Box3D is the only integrator, collision
|
||||
engine, broadphase, query-geometry implementation, and contact source in the
|
||||
committed Ymir path. The public `YmirSimulator.Step` compatibility API creates
|
||||
an isolated internal session for one complete snapshot, projects its output,
|
||||
and disposes it. Public circle overlap and cast APIs invoke Box3D geometry over
|
||||
caller-supplied bodies.
|
||||
|
||||
The retained native session now has a public in-process `YmirSession` port with
|
||||
explicit spawn, remove, teleport, velocity, configuration, force, torque,
|
||||
step, and disposal operations. It emits revisioned receipts and typed
|
||||
Begin/Hit/End facts with stable Ymir identities. Ordinary retained steps do not
|
||||
accept complete body snapshots.
|
||||
|
||||
The embedded retained-session library has replay-backed reconstruction,
|
||||
durable command receipts, incremental journal-suffix capture, and bounded
|
||||
resume descriptors. Aetheria stores these in a second daemon-private CultCache:
|
||||
immutable chunks are flushed first, immutable per-frame resumes second, and the
|
||||
public Aetheria frame last. The public frame is the only commit marker. Orphaned
|
||||
private records cannot advance gameplay truth, and restart fails closed once
|
||||
the persistence capability has been activated. Complete replay history is not
|
||||
product state and never rides in public client frames. The current CLI still
|
||||
has no named session registry or CultMesh command lowerings; its CultCache
|
||||
output remains a regenerated diagnostic projection.
|
||||
|
||||
## Target Inputs
|
||||
|
||||
- stable body and shape definitions
|
||||
- fixed time step and explicit substep count
|
||||
- transient forces, torques, impulses, and target transforms
|
||||
- collision filters and material definitions
|
||||
- overlap, ray, and shape-cast queries
|
||||
- product-owned selections such as which pickup ids a tractor may affect
|
||||
|
||||
Aetheria chooses physical intent and gameplay eligibility. Box3D decides
|
||||
geometry membership and contact. Ymir carries the typed handoff.
|
||||
|
||||
## Target Outputs
|
||||
|
||||
- body transforms and linear/angular velocities
|
||||
- begin, end, and hit contact facts with stable Ymir ids
|
||||
- overlap and cast results sorted by distance and stable id
|
||||
- step receipts and replay/checkpoint provenance
|
||||
- provider-owned operator and debug projections
|
||||
|
||||
Box3D callback order is not a public contract. Ymir may sort facts, but it may
|
||||
not alter their membership or invent missing contacts.
|
||||
|
||||
## Derived State
|
||||
|
||||
- Box3D world, body, shape, contact, and joint handles are transient session
|
||||
state derived from stable Ymir definitions.
|
||||
- CultCache checkpoints are reconstruction inputs and publication records; they
|
||||
are not a second live solver.
|
||||
- SoA body documents are transport and inspection projections over the live
|
||||
session.
|
||||
- Unity GameObjects and Electron objects are render state only.
|
||||
- Aetheria damage, loot, capacity, faction, and scoring consequences are
|
||||
derived from Ymir facts plus Aetheria policy.
|
||||
|
||||
## Dimensional Compatibility
|
||||
|
||||
The fossil Aetheria simulation uses a two-dimensional gameplay plane. During
|
||||
cutover, Ymir maps that plane into Box3D X/Z with translation on Y locked and
|
||||
rotation constrained to the plane normal. This is an explicit compatibility
|
||||
projection. It does not make Ymir a second 2D physics engine.
|
||||
|
||||
Sphere friction and inertia are not identical to planar disk behavior. Any
|
||||
mechanic that depends on that difference must be witnessed against the fossil
|
||||
and then expressed through Box3D configuration, not repaired by a parallel
|
||||
solver.
|
||||
|
||||
## Forbidden Writers
|
||||
|
||||
- managed integration, impulse resolution, collision geometry, or broadphase
|
||||
code in Ymir;
|
||||
- persisted force or torque replayed as if it were continuing authority;
|
||||
- Aetheria rectangle, capsule, overlap, or contact tests deciding gameplay
|
||||
physics;
|
||||
- Unity collision callbacks deciding hits, destruction, or pickup collection;
|
||||
- renderer transforms pushing hidden corrections into the world;
|
||||
- transport endpoints or dashboards owning world state;
|
||||
- Box3D opaque ids stored as durable GameCult identity.
|
||||
|
||||
## Target Shared Paths
|
||||
|
||||
Direct player commands, agent commands, programmatic spawns, server ticks,
|
||||
imports, reconnects, replay, and checkpoint recovery will enter the same Ymir
|
||||
session primitive for their named world. Today, DTO compatibility methods
|
||||
lower into an isolated Box3D session; they may not run an alternate step or
|
||||
infer retained identity from a body list.
|
||||
|
||||
Session identity must be explicit. A process-wide simulator object, zone index,
|
||||
or repeated stable body id is not enough to join two calls to the same world.
|
||||
Aetheria owns run and zone lifetime and creates, retains, and disposes the
|
||||
corresponding embedded Ymir session. Projectile sweep
|
||||
and stationary mine proximity integration can use Ymir's revision-checked
|
||||
retained-session circle-cast and overlap queries. They observe the current
|
||||
stable-id body projection; they do not invent a contact episode or mutate the
|
||||
Box3D world.
|
||||
|
||||
Radial gravity and tractor attraction are typed force-generation inputs. They
|
||||
are applied to Box3D before stepping. Pickup collection remains an Aetheria
|
||||
transaction triggered exactly once by a Ymir/Box3D contact fact.
|
||||
|
||||
## Native Boundary
|
||||
|
||||
`extern/box3d` pins the accepted upstream source. `native/Ymir.Box3D` owns a
|
||||
small stable C ABI facade. Managed Ymir code binds only to that facade; it does
|
||||
not scatter hundreds of direct P/Invokes across the daemon.
|
||||
|
||||
The native facade must remain boring:
|
||||
|
||||
- caller-owned blittable buffers;
|
||||
- explicit version and precision facts;
|
||||
- no GameCult gameplay policy;
|
||||
- no JSON state boundary;
|
||||
- no public exposure of Box3D internal handles;
|
||||
- first-class RID packaging before production consumers depend on it.
|
||||
|
||||
## Target Persistence Contract
|
||||
|
||||
Canonical deterministic replay starts from the same initial definitions and
|
||||
creation order, then applies the complete command stream under the pinned
|
||||
Box3D build and accepted runtime configuration.
|
||||
|
||||
A checkpoint restart is a different promise. Its schema must contain enough
|
||||
typed definitions and state to reconstruct an equivalent Box3D world: stable
|
||||
ids, 3D transforms, linear and angular velocity,
|
||||
body/shape/material/filter definitions, session tuning, and provenance. Box3D
|
||||
does not expose every internal solver cache, so arbitrary mid-world checkpoint
|
||||
restart is tested against named numeric state tolerances rather than claimed as
|
||||
bit-identical continuation. Contact membership, ordering, and exactly-once
|
||||
lifecycle identity are binary contracts, not tolerance checks. Authoritative
|
||||
contact facts resume only after canonical history has been replayed through the
|
||||
checkpoint tick; a checkpoint alone cannot emit gameplay contact facts.
|
||||
|
||||
`gamecult.ymir.session_checkpoint.replay.v1` implements that promise. It stores
|
||||
the initial definitions, complete typed command journal, logical session
|
||||
generation, command digest, body-generation counter, world verification
|
||||
projection, active contact-episode verification records, and pinned runtime
|
||||
fingerprint. Restore replays into a new Box3D world with outward publication
|
||||
suppressed, then compares the reconstructed boundary exactly before returning a
|
||||
live session. The bounded binary codec rejects incompatible, corrupt, or
|
||||
trailing data and checksums the complete encoded payload. ABI v5 validates the
|
||||
exact pinned native build id, not merely Box3D's public version. Native Box3D
|
||||
identities never enter the checkpoint.
|
||||
|
||||
`gamecult.ymir.world_state.v2` appends Box3D body type, bullet,
|
||||
field-participation, and collision filter arrays to the v1 layout. The v1 and
|
||||
v0 readers are explicit migration paths; keys are not reassigned. Torque is
|
||||
transient command state and is intentionally absent. Version 2 is a
|
||||
compatibility world snapshot, not a complete retained-session
|
||||
checkpoint: it does not preserve full shape, material, filter, session tuning,
|
||||
provenance, or warm contact state.
|
||||
|
||||
Transient forces and torques are commands, not durable body state. Derived
|
||||
mass and inertia are published only when useful for inspection. Old checkpoint
|
||||
versions must migrate explicitly or fail closed; they may not silently decode
|
||||
under a reassigned MessagePack layout.
|
||||
|
||||
## Cut Line
|
||||
|
||||
The managed integrator and circle impulse solver have been deleted from the
|
||||
runtime path. Any uncommitted `YmirQueryPrimitives` or `YmirSpatialIndex` work
|
||||
is obsolete and must not be annexed. The retained-session cut continues until
|
||||
Box3D-backed sessions prove:
|
||||
|
||||
1. fixed-step body state projection;
|
||||
2. begin/end/hit contact lifecycle;
|
||||
3. overlap and shape-cast lowering;
|
||||
4. continuous collision event timing and same-step Box3D cast witnesses;
|
||||
5. transient force and torque application;
|
||||
6. checkpoint reconstruction and replay (implemented; journal compaction and
|
||||
long-running storage remain operational work);
|
||||
7. Aetheria gravity, tractor, pickup, and payload smokes.
|
||||
|
||||
There is no managed fallback after that cut. A native load or compatibility
|
||||
failure fails closed and reports the missing capability.
|
||||
|
||||
## Required Verification
|
||||
|
||||
- Box3D parity tests record released upstream law at the native boundary.
|
||||
- Ymir differential tests compare public projections with the same Box3D
|
||||
session facts.
|
||||
- Negative source checks prove custom solver and spatial-index authorities are
|
||||
absent after cutover.
|
||||
- Aetheria smokes prove gravity, tractor attraction, contact-gated pickup
|
||||
collection/rejection, physical payload hits, and restart continuation through
|
||||
the retained contract. Destruction loot remains Aetheria gameplay state
|
||||
gated by Ymir contact facts where collection occurs.
|
||||
- Released-client witnesses prove generic Eve clients only observe Ymir and
|
||||
Aetheria provider contracts, never native implementation details.
|
||||
|
|
@ -1,76 +1,15 @@
|
|||
# Box3D Parity Harness
|
||||
# Pinned Box3D Fork Notes
|
||||
|
||||
## Authority
|
||||
|
||||
Box3D v0.1.0 is Ymir's physics implementation and executable semantics oracle.
|
||||
The production native session ABI and snapshot lowering are live; explicit
|
||||
retained-world ownership is still being connected. The exact upstream source is pinned as the
|
||||
`extern/box3d` submodule at commit
|
||||
`8441b4a06d6d09dcfb0b0f704df4d847d1437b92`.
|
||||
Box3D v0.1.0 is Ymir's rigid-body physics implementation (`extern/box3d` submodule), pinned at the GameCult fork commit `c790839` (`https://eureka.gamecult.org/forge/GameCult/box3d`, branch `gamecult/destroy-enlarged-proxy`).
|
||||
|
||||
Box3D does not own GameCult entity ids, gameplay policy, persistence, or result
|
||||
ordering. Ymir projects Box3D facts into those contracts. Box3D owns
|
||||
shape overlap, shape cast, solver, broadphase, contact lifecycle, force and
|
||||
torque lifetime, and numeric tolerances.
|
||||
The fork is upstream `8441b4a06d6d09dcfb0b0f704df4d847d1437b92` plus:
|
||||
- `b3ManifoldPoint.stepNormalImpulse`: observed field recording the normal impulse each contact point applied over the whole step, with a static assert that `RELAX_ITERATIONS` is 1 so the sum is exact.
|
||||
- Substep callback (`b3World_SetSubStepCallback`, with `b3Body_GetSubStepState` and `b3Body_ApplySubStepImpulse`, valid only inside the callback) used by the particle phase (`ymir_particles.c`) after the biased solve and before positions integrate.
|
||||
- Contact friction hook (`ebe346a`, see `docs/soa-world.md`).
|
||||
- Broad-phase fix (`DestroyEnlargedProxyTest`): rebuilding when the move buffer is empty clears stale enlarged flags on tree ancestors after proxy destruction.
|
||||
|
||||
## Body
|
||||
To rebase onto a newer Box3D, re-apply those commits, re-run `tests/Ymir.Box3D.Soa.Tests`, and compare pile state hashes against the upstream build.
|
||||
|
||||
`native/Ymir.Box3D` statically links the pinned C17 library into one small
|
||||
shared-library facade. The facade exports retained sphere-world sessions plus
|
||||
the overlap, cast, pair-step, torque-lifetime, version, and ABI-layout
|
||||
operations used by the harness. This keeps Box3D's alpha C ABI out of Ymir's
|
||||
public managed contracts.
|
||||
|
||||
Production ABI version 5 uses caller-owned blittable buffers, explicit cdecl,
|
||||
fixed-width status/count values, compile-time C layout assertions, and a
|
||||
managed/native layout and pinned-build-identity sentinel before opening a session. It adds explicit
|
||||
retained body mutations, one-shot force and torque operations, and a
|
||||
session-owned Begin/Hit/End event buffer. The private buffer retains Box3D's
|
||||
stored contact key only long enough to correlate its separate event arrays;
|
||||
public Ymir facts never expose native contact identity. Planar direction maps to Box3D
|
||||
rotation about Y; angular velocity and transient torque remain Box3D state and
|
||||
commands rather than managed integration.
|
||||
ABI v5 additionally carries Box3D static/kinematic/dynamic selection, bullet
|
||||
CCD, category/mask/group filtering, and per-body radial-field participation.
|
||||
|
||||
`tests/Ymir.Box3D.Parity` builds that facade through CMake and invokes it with
|
||||
source-generated .NET interop. Run it with:
|
||||
|
||||
```powershell
|
||||
dotnet test tests\Ymir.Box3D.Parity\Ymir.Box3D.Parity.csproj
|
||||
```
|
||||
|
||||
The build requires CMake and a C17 compiler. Box3D is MIT licensed; its license
|
||||
is retained in the pinned submodule.
|
||||
|
||||
## Released v0.1.0 Law
|
||||
|
||||
- Sphere overlap accepts separation strictly below the `0.0005 m` overlap
|
||||
slop. Exact tangency therefore overlaps.
|
||||
- Sphere shape casts use Box3D's `0.005 m` linear slop. The hit fraction is not
|
||||
the zero-tolerance analytic sphere intersection.
|
||||
- The low-level v0.1.0 sphere shape cast reports initially touching and
|
||||
initially overlapping shapes as hits. The harness records the released
|
||||
binary's behavior rather than relying on prose or recollection.
|
||||
- A two-point shape proxy plus radius is the tractor capsule. Membership
|
||||
includes rounded start and end caps and the same overlap slop.
|
||||
- Box3D query callback order is not a contract. Ymir sorts projected results by
|
||||
distance and stable entity id.
|
||||
- Contact begin facts are emitted after the world step.
|
||||
- Restitution uses the maximum of the two shape materials.
|
||||
- Applied torque is transient and cleared by each world step; a continuous
|
||||
torque must be submitted again for the next step.
|
||||
- A negative Box3D group index suppresses collision within that group before
|
||||
category/mask evaluation. Category and mask bits then decide eligible pairs.
|
||||
- Bullet CCD against a kinematic target prevents traversal during the fast
|
||||
step, but Box3D v0.1.0 emits the typed contact event on the following step.
|
||||
Same-step gameplay triggering therefore requires an explicit Box3D shape
|
||||
cast; Ymir must not invent an earlier Begin event.
|
||||
|
||||
## Cut Line
|
||||
|
||||
The managed integrator and circle collision solver are no longer runtime
|
||||
authorities. The remaining parity slice covers explicit retained-world
|
||||
ownership, end-contact lifecycle, continuous collision, and replay. Custom
|
||||
query geometry and spatial indexes are not fallback authorities; Box3D owns
|
||||
those edge cases.
|
||||
Box3D is MIT licensed; its license is retained in `extern/box3d/LICENSE`.
|
||||
|
|
|
|||
|
|
@ -1,203 +0,0 @@
|
|||
# Retained Session Contract
|
||||
|
||||
## Objective
|
||||
|
||||
One named Ymir session owns one retained Box3D world. A product may restore the
|
||||
world once, issue explicit mutations, step it, query it, and consume typed
|
||||
Box3D contact facts. A body snapshot is output and checkpoint material; it is
|
||||
not an implicit command language.
|
||||
|
||||
## Current Mechanism
|
||||
|
||||
`YmirSimulator` is an isolated snapshot compatibility API. It creates a native
|
||||
session, synchronizes a complete body list, steps once, projects the result,
|
||||
and disposes the session. Its private compatibility helper uses that complete
|
||||
list, so omission can delete a body and stale input can teleport or overwrite
|
||||
solver velocity inside the isolated call. Its legacy contact output merges
|
||||
current manifolds, begin events, and hit events into one pair-deduplicated list
|
||||
and omits End.
|
||||
|
||||
The public `YmirSession` does not use that mechanism for ordinary retained
|
||||
steps. The compatibility path is not the retained session contract.
|
||||
|
||||
## Owner
|
||||
|
||||
- One public Ymir session serializes commands for one named world.
|
||||
- Its native Box3D `b3World` exclusively owns integration, collision,
|
||||
broadphase, queries, solver state, and contact lifecycle.
|
||||
- Ymir owns stable GameCult ids, body generations, session revision, step
|
||||
sequence, deterministic projection, fact identity, and command receipts.
|
||||
- The product owns session lifetime and gameplay policy. Aetheria maps one
|
||||
`(RunId, ZoneIndex)` lifetime to one Ymir session.
|
||||
|
||||
## Target Inputs
|
||||
|
||||
The retained port accepts narrow operations with explicit meaning:
|
||||
|
||||
- spawn a body, rejecting an existing id;
|
||||
- remove a body, rejecting an unknown id;
|
||||
- teleport a body;
|
||||
- set linear and angular velocity;
|
||||
- configure body shape, mass, static/kinematic/dynamic type, and restitution;
|
||||
- apply one-shot force or torque;
|
||||
- step with a fixed delta, substep count, and typed fields;
|
||||
- dispose the session.
|
||||
|
||||
The current public slice implements those mutation and step operations plus
|
||||
revision-checked circle overlap and cast queries. A query observes the current
|
||||
retained body projection under the session lock and accepts an explicit set of
|
||||
stable candidate body ids. The candidate set is product-owned eligibility;
|
||||
Box3D still owns the overlap/cast geometry and numeric result.
|
||||
Bullet, collision-filter, and field-participation profiles are currently
|
||||
spawn/restore definitions. Retained `Configure` changes radius, mass,
|
||||
static/kinematic/dynamic type, and restitution only. Changing the profile
|
||||
requires explicit remove-and-spawn until a typed profile command exists.
|
||||
|
||||
Restore/import is the only path allowed to accept a complete world snapshot.
|
||||
There is no `Upsert`, generic patch bag, or omission-based removal.
|
||||
|
||||
## Outputs
|
||||
|
||||
Each accepted mutation produces a receipt that names the session generation,
|
||||
command id, before revision, and after revision. A step additionally returns:
|
||||
|
||||
- authoritative Box3D body state;
|
||||
- the new step index;
|
||||
- typed `Begin`, `Hit`, and `End` facts;
|
||||
- stable fact ids and contact-episode ids;
|
||||
- the accepted step configuration through its typed command.
|
||||
|
||||
The current library validates the native Box3D version and ABI before session
|
||||
creation but does not repeat those facts in every Step result.
|
||||
|
||||
Facts canonicalize bodies by stable id and flip normals when canonicalization
|
||||
swaps endpoints. Their public order is body pair, contact episode, kind, then
|
||||
within-kind ordinal. This is stable publication order, not invented substep
|
||||
chronology.
|
||||
|
||||
## Derived State
|
||||
|
||||
- Box3D handles are process-local and never cross the contract.
|
||||
- DTO and SoA body arrays are projections.
|
||||
- `gamecult.ymir.world_state.v2` is an inspection/migration snapshot, not a
|
||||
retained-session checkpoint.
|
||||
- Receipt and contact-episode ledgers are session metadata, not physics law.
|
||||
- Aetheria cargo, damage, loot, feedback, and scoring remain gameplay state
|
||||
derived from Ymir facts.
|
||||
|
||||
The replay checkpoint preserves the logical session generation, complete typed
|
||||
command journal, receipt ledger, body-generation counter, world projection, and
|
||||
active contact episodes. Restore creates a fresh native Box3D world and replays
|
||||
that journal through the checkpoint boundary before facts may leave the
|
||||
session. The world and episode records verify replay; they do not replace it or
|
||||
infer contact continuity from body proximity.
|
||||
|
||||
`gamecult.ymir.session_checkpoint.replay.v1` is encoded by the bounded binary
|
||||
`YmirSessionCheckpointCodec`. The checkpoint carries the pinned Box3D/ABI/
|
||||
precision fingerprint and fails closed on incompatible provenance, corrupt or
|
||||
trailing data, journal divergence, world divergence, or contact-lineage
|
||||
divergence. A SHA-256 checksum binds session identity, provenance, journal,
|
||||
world verifier, and active episodes. ABI v5 independently validates the exact
|
||||
pinned native build id before opening a session. It contains no native Box3D
|
||||
handle or contact key.
|
||||
|
||||
For incremental host persistence,
|
||||
`gamecult.ymir.session_journal_chunk.v1` carries a contiguous command-journal
|
||||
suffix and `gamecult.ymir.session_resume.v1` carries the bounded reconstruction
|
||||
boundary. `CapturePersistence(persistedJournalEntryCount)` never repeats an
|
||||
already acknowledged prefix. Restore orders chunks by their first entry,
|
||||
requires exact coverage from zero through the descriptor count, and then uses
|
||||
the same full replay and verifier path as a complete checkpoint. Both binary
|
||||
forms are independently checksummed.
|
||||
|
||||
The cursor is an index within one session generation. Bounded persistence uses
|
||||
an explicit generation rollover, never an inferred acknowledgement side effect.
|
||||
`TryCreateCompactedPersistenceBaseline` may create a replacement session only
|
||||
when the current journal is empty or ends in an accepted Step and Box3D reports
|
||||
no active contact episodes. The replacement starts from the current body
|
||||
projection and time with a fresh session generation, revision zero, an empty
|
||||
receipt ledger, and an empty journal. The host atomically swaps ownership and
|
||||
then disposes the prior session.
|
||||
|
||||
Active contacts, pending forces, or other unstepped mutations refuse rollover.
|
||||
Those sessions retain replay reconstruction until a later quiescent boundary.
|
||||
Ymir does not synthesize contact closure, serialize private Box3D handles, or
|
||||
pretend a body snapshot can preserve solver contact state. Old generation
|
||||
journals become audit history after the host commits the replacement boundary;
|
||||
they are not inputs to the new generation's restore.
|
||||
|
||||
## Forbidden Writers
|
||||
|
||||
- recurring complete-body synchronization after restore;
|
||||
- snapshot omission as body removal;
|
||||
- transform or velocity setters hidden inside ordinary Step;
|
||||
- managed contact lifecycle inference that replaces Box3D events;
|
||||
- random fact ids or ids derived from manifold floats;
|
||||
- Box3D callback order exposed as a public ordering guarantee;
|
||||
- Unity callbacks, renderer state, or gameplay proximity checks deciding
|
||||
contact truth.
|
||||
|
||||
## Shared Paths
|
||||
|
||||
Direct commands, agent commands, spawns, and checkpoint replay use the same
|
||||
explicit session operations. Restore establishes a fresh native world through
|
||||
those operations; it is not a parallel state writer.
|
||||
Retained queries will observe a named revision without mutating it. Snapshot
|
||||
reads cannot be fed back without an explicit restore, teleport, velocity, or
|
||||
configuration operation.
|
||||
|
||||
## Contact Identity
|
||||
|
||||
A contact episode is identified by the canonical pair of body id plus body
|
||||
generation and a monotonically assigned episode number. Begin and End share
|
||||
that identity. A later re-contact creates a new episode. Fact identity derives
|
||||
from session generation, step index, contact episode, kind, and deterministic
|
||||
ordinal. Box3D contact and shape handles are never durable identity.
|
||||
|
||||
Body removal must close any active episode exactly once. Because Box3D End
|
||||
events may reference destroyed shapes, the native boundary retains stable ids
|
||||
until the event buffer has been drained.
|
||||
|
||||
Box3D publishes Begin, Hit, and End in separate arrays rather than one causal
|
||||
sequence. The private ABI carries Box3D's stored transient contact key so Ymir
|
||||
can correlate those arrays before assigning public episode identity. That key
|
||||
is derived process state: it never appears in a public fact or checkpoint.
|
||||
|
||||
## Cut Line
|
||||
|
||||
1. Typed native mutation operations and step-owned lifecycle buffers: done.
|
||||
2. Public managed retained session with no ordinary full synchronization:
|
||||
done.
|
||||
3. Revision-checked retained-session overlap and cast queries: done.
|
||||
4. One embedded retained world and physical-payload session per Aetheria run
|
||||
and zone: done.
|
||||
5. Incremental journal chunks and bounded resume descriptors: done. Aetheria
|
||||
stores them in a daemon-private CultCache; complete history does not ride in
|
||||
public product frames. Quiescent generation rollover provides the compaction
|
||||
primitive; host adoption and old-generation retention policy are separate.
|
||||
6. For optional standalone hosting, add a session registry, generation-bearing
|
||||
routed commands, idempotent Create, durable receipts, and CultMesh lowering.
|
||||
|
||||
The isolated `YmirSimulator` remains a compatibility API. It is never the
|
||||
retained-world authority.
|
||||
|
||||
Mutation-generated End evidence is currently retained in the native pending
|
||||
buffer and published by the next accepted Step. The host transaction cut
|
||||
must make mutation plus Step one publication boundary, or return mutation facts
|
||||
directly, before Ymir promises that removal followed by disposal publishes an
|
||||
End fact.
|
||||
|
||||
## Verification
|
||||
|
||||
- A spawned body advances across steps without being resubmitted.
|
||||
- Omission from unrelated commands cannot remove or reset a body.
|
||||
- Force and torque affect exactly one accepted step.
|
||||
- stale revisions and conflicting command ids cannot mutate the world.
|
||||
- persistent touching emits one Begin, separation emits one End, and re-contact
|
||||
creates a new episode.
|
||||
- duplicate fact delivery cannot commit Aetheria cargo twice.
|
||||
- different insertion orders produce the same semantic fact order.
|
||||
- queries observe the requested retained revision and cannot inject bodies.
|
||||
- disposed or stale session generations fail closed.
|
||||
- restored continuation reproduces command receipts, bodies, active contact
|
||||
identity, and subsequent Begin/End facts before authoritative publication.
|
||||
|
|
@ -1,23 +1,20 @@
|
|||
# Headless SoA world
|
||||
|
||||
A headless 3D Box3D world with a structure-of-arrays state view, for Lodur and Bad Day Simulator.
|
||||
Box3D decides every physical outcome; Ymir creates bodies, steps the world and exposes state.
|
||||
|
||||
## Why it is not the retained session
|
||||
|
||||
`ymir_box3d_session_*` (`ymir_box3d.c`) is the planar Aetheria session: gravity is zero, Y is locked,
|
||||
only yaw rotates (`motionLocks.linearY/angularX/angularZ`), and state leaves by `copy_bodies` into an
|
||||
array of structs. A body cannot fall or tumble there, and every read is a copy. The SoA world is a
|
||||
separate native object (`ymir_box3d_soa.c`, ABI 1) so the Aetheria session's contract is untouched.
|
||||
Box3D decides every physical outcome; Ymir creates bodies, steps the world and exposes state (`ymir_box3d_soa.c`, ABI 21).
|
||||
|
||||
## Contract
|
||||
|
||||
- Native (ABI 2): `ymir_box3d_soa_create(capacity, joint_capacity, gravity) / add_body / add_joint / step /
|
||||
get_view / destroy`. `add_body` takes one descriptor (sphere, capsule, box, static box; position,
|
||||
rotation, velocity, size, density, friction, restitution, rolling resistance, parent, limb). Capacities are fixed at creation,
|
||||
- Native (ABI 21): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) /
|
||||
create_particles / destroy_particles / create_distances / create_bends / create_sensors / take_wet(n, sensors, volumes, taken) / attach(n, desc*) / set_pinned(n, handles, pinned) / remove / set_material / free_slots /
|
||||
add_body / add_static_heightfield / add_static_mesh / add_joint / step / get_view / get_facts / set_anchor_target / destroy_joint / set_joint_thresholds / remove_body / free_joint_slots / free_body_slots / apply_impulse / cast_ray_closest / destroy`. `add_body` takes one descriptor (sphere, capsule, box, static box, anchor; position,
|
||||
rotation, velocity, size, density, friction, restitution, rolling resistance, material id, parent, limb). `add_static_heightfield` (kind 6) and `add_static_mesh` (kind 7) create static terrain/mesh bodies whose native `b3HeightFieldData` / `b3MeshData` allocations are owned per body slot and destroyed after `b3DestroyBody` / `b3DestroyWorld` on `remove_body` / `destroy` (particle proxies treat both as `YMIR_PROXY_NONE`). Capacities are fixed at creation,
|
||||
so lane pointers never move.
|
||||
- Body lanes (`ymir_box3d_soa_view`): `stable_id`, `kind`, `parent` and `limb` (set at creation, not read by
|
||||
Box3D: the limb tree for the consumer), position xyz, rotation quaternion xyzw, linear and angular
|
||||
Box3D: the limb tree for the consumer), `size_0`, `size_1`, `size_2` (read-only shape size set at creation,
|
||||
never changed by `step`: sphere {radius}, capsule {radius, half_length} along local Y, box and static box
|
||||
{half_x, half_y, half_z}; unused components 0; dynamic and static box shapes are centred on the body origin, whereas
|
||||
`StaticHeightField` (kind 6, anchored at grid `(0, 0)`) and `StaticMesh` (kind 7, local vertex coordinates) leave `size_0..2 = 0`), position xyz, rotation quaternion xyzw, linear and angular
|
||||
velocity xyz. One contiguous array per component, indexed by body.
|
||||
- Write lanes: per-body world `force` (at the centre of mass) and `torque`, xyz, mutable through the view.
|
||||
`step` applies them to the dynamic bodies and clears them, so a lane holds one step's intent. A
|
||||
|
|
@ -26,17 +23,272 @@ separate native object (`ymir_box3d_soa.c`, ABI 1) so the Aetheria session's con
|
|||
(revolute, spherical, weld). The joint frame has its z axis on the axis (the hinge axis); the creation
|
||||
pose is the joint's zero. Optional limits: revolute angle, spherical swing cone and twist. Joint lanes:
|
||||
`joint_kind`, `joint_body_a/b`, `joint_angle` (Box3D's revolute angle or spherical twist), `joint_frame`
|
||||
(world orientation of frame A, quaternion), `joint_rotation` (frame B relative to frame A, quaternion,
|
||||
(world orientation of frame A, quaternion), `joint_origin` (world position of frame A's origin, the anchor), `joint_rotation` (frame B relative to frame A, quaternion,
|
||||
w >= 0) and `joint_angular_velocity` (B minus A, in frame A). A consumer can compute a joint torque from
|
||||
these and write it as equal and opposite torques on the two body lanes.
|
||||
- Joint stress: `joint_constraint_force_xyz` (N) and `joint_constraint_torque_xyz` (N m) are Box3D's constraint solution for the joint at the end of the last step
|
||||
(`b3Joint_GetConstraintForce/Torque`, world frame; a hung mass at rest reads m g within 2%; a removed lane reads 0). The joint desc's `force_threshold` and
|
||||
`torque_threshold` (+inf, the default, is never; NaN or a negative value is refused; `set_joint_thresholds(joint, generation, force, torque)` changes a live joint's)
|
||||
make Box3D report the joint in a step where its load reaches one: an Overload fact `{joint_lane, joint_generation, force xyz, torque xyz}` (the load read after the step), at most once per
|
||||
joint per step. The threshold is a sensor: Ymir never removes a joint on it, the caller decides with `destroy_joint`. Joint user data is lane + 1.
|
||||
- Contact lanes (read-only, rewritten by every `step`): `contact_impulse` (N s: the normal impulse the
|
||||
body's touching contacts delivered to it over the whole step, the sum of Box3D's `stepNormalImpulse` over
|
||||
its manifold points; 0 for a body touching nothing; exact, so a jointed limb's reading is what the contacts
|
||||
really delivered, not a mass formula's guess. It is a sum of magnitudes over all the body's contacts, not the
|
||||
net: a ball under a ball reads support plus load, 3 m g dt, not m g dt. At rest it equals the weight only on
|
||||
average: heavy balls in a pile alternate between about 1.5 and 0.5 m g dt from step to step, so a consumer
|
||||
must not threshold a single step; average over steps or use `contact_impulse / dt` as a load estimate over a
|
||||
window), `contact_count`
|
||||
(touching contacts), `mass` (kg, Box3D's `b3Body_GetMass` copied once at create; 0 for static, kinematic, anchor and removed lanes) and `material_id` (the body's `material_id`, also set as the shape's Box3D user
|
||||
material). `stepNormalImpulse` is the GameCult Box3D fork's observed field (see `box3d-parity.md`); it is
|
||||
the normal channel only, since Box3D exposes no tangent impulse. Sleep is off in SoA worlds, so manifolds
|
||||
hold no stale values; if sleep is ever enabled, zero the lanes of sleeping bodies. The hit fact's `impulse`
|
||||
(N s) is the same sum over the manifold of the hit's two shapes, read after the step.
|
||||
- Contact facts: every shape is created with contact and hit events on (Box3D's default is off). After each
|
||||
`step`, `ymir_box3d_soa_get_facts` returns pointers and counts into buffers fixed at create (`fact_capacity`
|
||||
per kind, no allocation in the step): Begin and End `{lane_a, lane_b, stable_id_a, stable_id_b}` and Hit
|
||||
those plus `point` xyz, `normal` xyz (A to B), `approach_speed` (a touch faster than `hit_threshold` m/s)
|
||||
and `material_a`, `material_b`; Touching (`touching`) lists each pair touching after the step once, `lane_a < lane_b`, from the same per-body contact read as `ContactCount` (`touching_dropped` past `fact_capacity`). Facts are in Box3D's event order and last one step: the next `step`
|
||||
rewrites them. `*_dropped` counts the facts a step could not keep past `fact_capacity`. The lane in a fact
|
||||
is the body's user data (lane + 1) and the stable id is the shape's user data. The facts report; they
|
||||
decide nothing.
|
||||
- Overload and removal facts (buffers fixed at create like the rest): `overload` (above), `body_removed` `{lane, generation (the dead handle's), stable_id, wet_patches, wet_volume}`
|
||||
and `joint_removed` `{lane, generation, body_a, body_b, with_body}` (1 when a removed body took the joint, 0 for `destroy_joint`). `remove_body` and `destroy_joint` write them
|
||||
into pending arrays and the next `step` publishes them in removal order (a lane is removed at most once between steps, so they never overflow), with the End touch facts the
|
||||
removal caused: a removed body's shape is no longer valid, so its End facts are attributed from the retired shape table `{shape, lane, stable_id}`, cleared once the step has
|
||||
collected them. Every removal path (a grab release, a cut, a gib, a level unload) appears in these facts. A step refused for a non-finite write lane publishes nothing and keeps them.
|
||||
- Grab and poke input (immediate commands; Ymir decides nothing about grabbing, so a player grab, a scripted
|
||||
hook and a cursor tool are all the same three calls):
|
||||
- Anchor (body kind 4): a kinematic body with no shape. It never collides or is hit, its size lanes are 0 and
|
||||
size, density, friction and material are ignored. `set_anchor_target(lane, position, rotation, time_step)`
|
||||
gives it the velocity that reaches the pose after `time_step`, so passing the step's dt lands it on the pose
|
||||
at the end of the next step, where `step` stops it: after every step an anchor's velocity is zeroed, so with no
|
||||
new target it holds still at the last pose (a skipped frame flings nothing) and its velocity lanes read 0. It is
|
||||
refused for a lane that is not an anchor, for non-finite or non-unit input and for a time step <= 0. The force and torque lanes never move an anchor. Its pose reads from the state lanes.
|
||||
- Motor joint (kind 3): `add_joint` with the descriptor's `linear_hertz`, `linear_damping`, `max_force`,
|
||||
`angular_hertz`, `angular_damping`, `max_torque` (finite, >= 0, ignored by the other kinds; zero hertz turns that
|
||||
spring off; no velocity target). The frame is built from the world anchor and axis like every joint, so the
|
||||
linear spring pulls body B's anchor point onto A's (A an anchor, B the body to grab). `max_force` and
|
||||
`max_torque` bound the pull: with a max force below the weight the body hangs below the target. `joint_angle`
|
||||
reads 0.
|
||||
- Release: the cursor's anchor is long-lived (a client creates one per cursor and keeps it, or removes it with `remove_body`).
|
||||
`destroy_joint(joint, generation)` releases a joint of any kind (a grab, a cut, a tear) through the one joint-ending path, `ymir_soa_retire_joint`,
|
||||
the only `b3DestroyJoint`; the bodies stay. The joint's lane becomes a tombstone: `joint_kind` 4
|
||||
(Removed), `joint_body_a/b` -1, every joint lane 0 (the constraint lanes included), generation + 1; no last state is kept, a caller that wants it reads before
|
||||
removing. `joint_count` counts slots ever used, tombstones included.
|
||||
`add_joint` reuses the lowest tombstone only after a step has completed since the destroy, so lanes read within a
|
||||
step stay valid; until then the slot is not free. `free_joint_slots` (managed `FreeJointSlots`) is what
|
||||
`add_joint` could create right now: check it, and `FreeBodySlots`, before adding an anchor for a grab, so a full
|
||||
world leaves no orphan anchor. Repeated grab and release on one slot do not grow the world.
|
||||
A joint's handle is its lane and the slot's generation (`joint_generation` lane, counts destroys of the slot;
|
||||
managed `Box3DSoaJointHandle`, returned by `AddJoint` and `AddMotorJoint`, converts to the lane). `destroy_joint`
|
||||
refuses a generation that is not the slot's, a removed lane and an out-of-range lane, so a second release click with an old handle never destroys a later
|
||||
grab that reused the slot. Anchor creation must be followed by a joint that validates (its spring fields are
|
||||
checked there), or the anchor is left behind: with one long-lived anchor per cursor that is accepted, and an atomic
|
||||
`AddGrab` is a follow-up only if cursors become dynamic.
|
||||
- Body removal: `remove_body(lane, generation)` (managed `RemoveBody(Box3DSoaBodyHandle)`) is the one body-ending path. A body's handle is its lane
|
||||
and the lane's generation (`body_generation` lane; managed `Box3DSoaBodyHandle`, returned by every `Add*` body helper, converts to the lane, so lane arrays and `int`
|
||||
parameters take it unchanged). It is refused whole, changing nothing, for a lane that is not a live body, a stale generation, and with status REFERENCED (6; managed: it
|
||||
throws) while a live body attachment or liquid sensor names the body: the caller removes those first (an anchor is a body and gets no rule of its own: its attachments
|
||||
and sensors count the same). Otherwise, in order: the body's wet patches are removed (`ymir_particles_release_body`, no Box3D call), every joint naming the body is
|
||||
retired (ascending lane, so a removed anchor ends its grabs and their handles go stale), the body's shape is entered in the retired table, Box3D destroys the body and the lane
|
||||
becomes a tombstone: `kind` 5 (Removed), every other lane 0 (stable id 0, parent -1, limb 0), generation + 1. Lane order never changes (no swap-remove; `count` is the
|
||||
high-water mark of lanes ever used). `add_body` takes the lowest Removed lane whose step has completed, else appends, else FULL; a lane is never reused before the step
|
||||
whose facts name it dead, and the removed stable id may be reused. `free_body_slots` (managed `FreeBodySlots`) counts them. `attach`, `create_sensors`, `add_joint` and a
|
||||
new body's `parent` refuse a Removed lane; a live child's `parent` may still name one (the consumer owns its tree). `particle_support_body` is a last-step fact and may name a
|
||||
removed lane until the next substep; a drop cannot settle on it (its proxy reads no shape). Box3D's own joint cascade in `b3DestroyBody` never runs: the joints are retired first.
|
||||
- `apply_impulse(lane, impulse, point)`: a one-shot world impulse (N s) at a world point; off the centre of mass it
|
||||
also spins the body. Dynamic bodies only (a static body or anchor is refused), non-finite input refused.
|
||||
- `cast_ray_closest(origin, translation)` fills a `ymir_box3d_soa_ray_hit` {hit, lane, stable_id, point, normal,
|
||||
fraction}: Box3D's closest hit along origin + t * translation, t in [0, 1], default filter; a miss is success with
|
||||
`hit` 0 and every field 0; a non-finite or zero translation is refused. Anchors are never hit. A ray that starts
|
||||
inside a shape skips that shape (Box3D's behaviour, it ignores initial overlap) and reports what lies beyond.
|
||||
- Managed: `AddAnchor`, `SetAnchorTarget`, `AddMotorJoint`, `DestroyJoint`, `FreeJointSlots`, `FreeBodySlots`, `ApplyImpulse`, `CastRayClosest` (returns
|
||||
`Box3DSoaRayHit`) on `Box3DSoaWorld`; refusals throw `InvalidOperationException`.
|
||||
- State lanes change only inside `step`. Between steps a caller may read any state lane in place.
|
||||
- Managed (`src/Ymir.Box3D/Box3DSoaWorld.cs`, internal): `Box3DSoaView` exposes each lane as a span over
|
||||
- Managed (`src/Ymir.Box3D/Box3DSoaWorld.cs`, public: `Box3DSoaWorld`, `Box3DSoaView`, `Box3DSoaFacts`, `Box3DSoaKind`, `Box3DSoaJointKind`; the native structs and the view constructor stay internal): `Box3DSoaView` exposes each lane as a span over
|
||||
native memory (`ReadOnlySpan` for state, `Span` for write lanes). Spans are invalid after `Dispose`.
|
||||
`Count` and `JointCount` are as of when the view was taken, so take it after the last add.
|
||||
`Box3DSoaWorld.Facts` is a `ref struct` of `ReadOnlySpan`s (`Begin`, `End`, `Hit`) with the same dispose
|
||||
guard; the constructor takes `factCapacity` (default 4 x capacity, 0 refused) and `hitThreshold` (default 1);
|
||||
the `Add*` methods take an optional `materialId`.
|
||||
- Determinism: one Box3D worker, bodies stepped in insertion order, same inputs give identical lane
|
||||
bytes on the same build. It is not claimed across platforms or CPUs.
|
||||
- Concurrency: creating Box3D worlds from several threads at once aborts the process (seen in tests);
|
||||
create worlds one at a time.
|
||||
- Particles (`ymir_particles.c`, C17, calls no Box3D; `ymir_box3d_soa.c` stays the only Box3D caller and the only caller
|
||||
of `ymir_particles_begin`, `_substep` and `_end`). The particle state is a constraint graph: particles are one lane set with a
|
||||
phase word and every constraint type is a lane set of its own. There is no object above the lanes: a rope, a sheet, a gut or
|
||||
flesh is whatever constraints a caller emitted, and exists only in that caller's builders. A world created with a
|
||||
`ymir_particle_capacities{particles, distances, bends, attachments, tethers, materials, fluid, wets}` that is not all zero owns fixed
|
||||
lanes that never move; created with none (`NULL` or all zero) it behaves byte-identically to ABI 8. Nothing writes a
|
||||
particle's position or velocity but the step.
|
||||
- Data model. Particle lanes: `x y z vx vy vz radius inv_mass rest_x rest_y rest_z phase material live generation removed_at
|
||||
component`. The phase word: bits 0-19 are the group, bit 20 `SELF_COLLIDE`, bit 21 `SELF_FILTER`, bit 22 `FLUID`, bit 23 `NO_PARTICLE_CONTACT` (refused together with `FLUID`); any other bit is refused.
|
||||
Distance lanes: two particles, rest length, compliance (m/N), `tension` (sensor). Bend lanes: two distances that share one
|
||||
particle (and so the three particles a, b, c), rest and limit offsets, compliance. Attachment lanes: kind (body, static,
|
||||
removed), flags (`TETHER`; `ONE_WAY`, Body only: the body side weighs nothing, so the attachment holds its particle to the body's point and never moves or loads the body, for flesh whose mass the bone already carries; `LIMB`, Body only: the particle is flesh of the body's limb tree, so contact skips every body whose limb-tree root, the `parent` lane followed to its end, is the attached body's), particle, body, point, compliance, `force` (sensor). Held lanes (derived, command time): per particle the list of bodies its live Body attachments name, which contact skips, and `limb_body`, the body of its lowest live `LIMB` attachment or -1. Limit: when a particle's `LIMB` attachments name bodies of two limb trees only the lowest one's tree is skipped; the other tree's bones collide, except the bodies the particle is attached to. Tether lanes (derived): attachment,
|
||||
particle, bound, parent tether, edge, other attachment. Material table: friction, XSPH viscosity, wet friction and the caller's material id. Handles are
|
||||
(lane, generation).
|
||||
- Pinned, dormant, kinematic, anchor. `pinned` is a command-owned lane (`set_pinned`; `destroy_particles` frees it to 0). A pinned particle is dormant: no step walk visits it, its `x y z vx vy vz` are stale from the tick it was pinned until it wakes, and a reader draws it from its anchor, the point of its lowest live non-`TETHER` attachment (body or static) when it was pinned, held while it sleeps so no attachment another command adds can move it, where the view's `particle_pinned` lane says which and its `particle_anchor` lane names the attachment (readers read it, never re-derive it). A pinned particle that shares a live distance or bend with an unpinned one is kinematic: each substep its position is its anchor's point at the substep's start pose and its predicted position that point at the predicted pose, so the live neighbour is held against a moving border (its velocity is the anchor point's over the substep). Every step walk visits a list `rederive_active` derived at command time, the last step of every topology command and of `set_pinned`: `act` (live unpinned particles), `kin`, `act_dist` and `act_bend` (live constraints with an unpinned particle), `act_att` (attachments of unpinned particles), all in lane order, plus `anchor` and `w` (the inverse mass the step reads: 0 for pinned). With nothing pinned the lists are every live lane in lane order and `w` is `inv_mass`, bit for bit. A dormant particle is in no contact grid (flesh at rest meets no fluid and no body: it rides its bone, which is the body fluid and other bodies meet, so blood poured on dormant skin stops at the bone's capsule, within a skin radius of the skin's surface only while the capsule is that surface), writes no impulse, and a pinned fluid particle is refused. `set_pinned` refuses whole (INVALID_ARGUMENT) a stale or dead handle, a value other than 0 or 1, a fluid particle, and pinning a particle with no anchor; a wake sets position to the anchor's point at the bodies' poses now and velocity to that point's velocity. `remove(attachment)` refuses a pinned particle's anchor. No distance component holds both a pinned particle and a live `TETHER` attachment (a tether loads every lane of its component, and no walk moves a pinned one): `rederive_topology`, which every topology command and `set_pinned` end in, checks it once on the components it derives before writing any lane, and refuses whole whatever would break it (a tether attached into a component with pinned flesh, a distance joining such a component to a tethered one, a pin in a tethered component); the command backs its lanes out. Wake first. Any other attachment of a pinned particle is accepted in whatever lane it takes and leaves its anchor and pose as they were. A patch of settled liquid on a pinned particle is read at its anchor's point, so it rides the bone.
|
||||
- Commands, each refused whole before anything changes: `create_particles(n, desc{position, velocity, rest, mass, radius,
|
||||
phase, material})` takes the lowest free lanes; `destroy_particles(n, handles)` removes every constraint that touches them;
|
||||
`create_distances(n, desc{a, b, rest (< 0 = rest-pose length), compliance})`; `create_bends(n, desc{e1, e2, compliance
|
||||
(< 0 = soft pass off), max_angle (< 0 = no limit)})`, refused unless the two distances share exactly one particle and the
|
||||
bend does something; `attach(n, desc{kind body|static, flags, particle, body, point, compliance}*)` (a batch like `create_distances`: every desc validated, the lowest free lanes by cursor, one derivation, backed out whole on a refusal: a batch equals N single attaches only when accepted, since N singles keep the attachments accepted before a refused one); `remove(type distance|bend|
|
||||
attachment, n, handles)`; `set_material(index, desc{friction, viscosity (>= 0), material_id})`; `free_slots(lane set)`. A distance takes
|
||||
the bends over it with it. Ymir never removes a constraint or releases an attachment on a load: tear, cut, gib and release
|
||||
are the caller's say-so.
|
||||
- Derivation. Every topology command ends in the one `rederive_topology()`, which is the only writer of the tether lanes and
|
||||
the component lane. It builds the adjacency of the live distances, labels components by their lowest lane, and then islands
|
||||
(Kim, Chentanez, Mueller 2012 sec. 3.4): a particle holding a live `TETHER` attachment is a tether particle, and an island is
|
||||
a maximal set of tether particles joined by live distances, named by its lowest `TETHER` attachment. For each island, in lane
|
||||
order, one Dijkstra (binary heap, ties by node then edge) over the distances' rest lengths runs from all its tether particles;
|
||||
another island's tether particle is settled but not expanded. Each particle that is not a tether particle keeps the two
|
||||
nearest islands by rest path (an equal path keeps the lower island) and gets one tether to the nearest point of each, bounded
|
||||
by that geodesic path (not the Euclidean rest distance: 0.23% on a flat two-corner sheet, but a coiled rope could never uncoil under
|
||||
it, and the graph has no surface to say when it holds), with the tether of the previous particle on the path and the edge used (parents come before children). Ranking
|
||||
attachments instead of islands fails when a corner is held by adjacent pins (two corners of two pins stretch 11.6% at 5 s by
|
||||
the two nearest attachments, 2.4% by islands); one island per particle (nearest only) stretched 16.4%, and Kim's typical four
|
||||
islands buy 1.66% against 1.72% on a 20-pin sheet for twice the lanes, so the count is `YMIR_TETHER_ISLANDS` = 2. Float32
|
||||
path sums can break the exact-arithmetic closure of the rankings at a tie (a particle keeps an island its parent dropped), so
|
||||
a tether is written only when its parent particle is a source or holds a tether to the same island: a gated particle keeps
|
||||
one tether. So N particles carry at most 2N tethers however many points are pinned: a 32 x 32 sheet pinned at 20 points had
|
||||
20650 tethers (3.5 ms per tick) and has 2008. Two `TETHER` attachments on different particles of one component, at least one
|
||||
on a body, also get a pair tether: the rest path between their particles bounds the distance between their points (what lets
|
||||
a heavy body be held at 0.1% stretch from a static point: the full excess moves the body, not only the light end particle).
|
||||
Two static points never move, so their pair has no end to pull and is not derived. A pair tether sits behind a route of booking lanes (attachment -1, an edge
|
||||
and a parent, no bound of their own) along that path, so the tension sensors read its load on the edges it crossed; pairs
|
||||
cost O(A^2) lanes and a derivation runs one more Dijkstra per tether point that has a later partner. Hold a heavy body with
|
||||
`TETHER` at both ends: with the tether on one end only a 70 kg body hung from a 48-particle rope sinks 0.25 m below its
|
||||
attachment (speed 1.1 m/s at rest), with both it holds to 0.002% stretch. The tether count is known before anything is
|
||||
written (the Dijkstras run once to count and once to write); a command that would need more than the tether capacity is undone
|
||||
whole and refused (`create_distances` and `attach` are the commands that can).
|
||||
- Lanes. Particle, distance, bend and attachment lanes are tombstones (live 0 or kind removed, generation + 1, every other lane 0
|
||||
except `removed_at`) reused only once a step has passed, lowest lane first. Stale generations are refused. Counts are high-water
|
||||
marks; a view's counts are read when the view is taken, so take it after the last command.
|
||||
- Solve (inside the fork's substep callback, `h = dt / substeps`, one iteration of each pass per substep: the small step does
|
||||
the converging). Order: predict particles and proxies, hash grid (the non-fluid lanes), pair contacts (Jacobi), the fluid pass (its own grid; fluid-solid contact), attachments, distances in
|
||||
lane order, bends in lane order, tethers, body contacts last (with contacts first a box pushed into a rope reads 14% of a
|
||||
radius inside). A bend works on the offset of its shared particle b from the centroid of a, b, c (Kelager 2010): a soft XPBD
|
||||
pass toward the rest offset, then a hard unilateral pass at the offset `max_angle` allows (computed from the two rest
|
||||
lengths), free inside it and rigid at it. It bends on any topology a caller builds, and the limit is a hard constraint at the
|
||||
substep the solver runs: how stiff it reads at few substeps is the open question `bend-limit-stiffness`.
|
||||
- Contact. Particles of different groups collide; of one group only when both set `SELF_COLLIDE`, and not (when either sets
|
||||
`SELF_FILTER`) if their rest-pose distance is under 1.5 (ri + rj). A `NO_PARTICLE_CONTACT` particle meets bodies and fluid
|
||||
only: it is left out of the solid grid, so no non-fluid particle touches it, while body contact and the fluid grid still
|
||||
hold it. The solid grid is sized by its members (a cell's particles are walked in lane order whatever the bucket count, so
|
||||
the sizing moves no byte); the fluid grid keeps the full table, which `fluid_density`'s sum order depends on. Each pair is found once, walking half the 27-cell
|
||||
neighbourhood from each particle (its own cell for higher lanes, 13 cells forward), in two walks: the first counts each
|
||||
particle's overlaps; the second moves both ends of a pair by one displacement, weighted `1 / max(n_i, n_j)`, so a pair's two
|
||||
corrections carry equal and opposite momentum and contact conserves it (to float32 rounding of the positions: 0.01% in the
|
||||
thrown scene, 0.6% at a 30:1 particle mass ratio and 6% at 100:1). No pair list is kept: its size is not bounded by the particle
|
||||
count. Body contact: a particle against each shaped body in lane order, the correction
|
||||
split by inverse mass at the contact point, Coulomb friction from the particle's material; every body a particle is attached to
|
||||
is skipped.
|
||||
- Fluid. Fluid is a phase bit, not an object: a particle with `FLUID` takes part in a number-density constraint with every
|
||||
other fluid particle and with the solids it would touch by contact, and keeps contact (at `ri + rj`) with those solids; two
|
||||
fluid particles do not contact, whatever their groups and `SELF_*` flags (all fluid shares one density field, Macklin et al.
|
||||
2014 sec. 7). Kernel per pair `h = 2 (ri + rj)` (4 r at equal radii), Poly6 `W = 315 / (64 pi h^9) (h^2 - r^2)^3` for the
|
||||
density and Spiky `grad W = -45 / (pi h^6) (h - r)^2 r_hat` for the gradient (Macklin and Mueller 2013); no PhysX code is
|
||||
adapted. The rest density `n0(h)` is the Poly6 sum over the simple-cubic lattice of spacing `h / 2` (a constant, computed at
|
||||
create, times `h^-3`), so a particle has volume `(2 r)^3` and there is no rest-density field. The constraint is unilateral,
|
||||
`C_i = max(n_i / n0 - 1, 0)`, so there is no artificial-pressure term and an under-dense fluid (a gas of far particles) is not
|
||||
pulled together; `lambda_i = -C_i / (sum_k w_k |grad_k C_i|^2 + eps w_i)` (0 when that is 0; XPBD inverse-mass weighting, Macklin et al. 2016) with the gradients over `n0` in 1/m^2 and `eps = 1e-4` (a sweep of
|
||||
1e-6 to 1e-2 on the column test moved the max density between 1.344 and 1.377 and nothing else: the gradient sum is about 500).
|
||||
Per substep, after contact, the fluid pass rebuilds the grid over every live lane at the kernel cell `4 r_fmax` (the same tables, in place; nothing after the
|
||||
pass reads the contact grid) and copies position, inverse mass and phase into sorted order, so a bucket reads contiguously (`sorted[q]` is the lane of sorted index `q`).
|
||||
`fluid_rings = ceil(2 (r_fmax + r_max) / 4 r_fmax)` (1 at equal radii: 27 cells). Pass A takes each fluid row in sorted order: the buckets of its cells, each bucket once (a
|
||||
bucket two offsets hash to is skipped the second time, by a visit stamp; a particle of a cell outside the rings is out of reach, so the distance test needs no cell
|
||||
compare), a branchless compaction of the candidates within `2 (r_i + r_max)` into a stack row buffer of 128 (hits past it add to `fluid_neighbour_overflow`), and over the
|
||||
buffer `n_i` (self and the solids it would touch by contact counted, `s = 1` as Flex 7.1) and `lambda` (a solid's is 0), and the row's neighbour list: every kernel neighbour
|
||||
in walk order, packed (CSR) into an arena of `fluid_capacity * 96` entries (about 33 neighbours at rest at 4 r reach, about 45 at the column's compression); each past the
|
||||
arena adds 1 to `fluid_neighbour_overflow`, the ABI 12 view scalar (last step, summed over its substeps), so `n` and `lambda` stay exact until the row buffer overflows and
|
||||
only the correction and XSPH lose the pairs past the arena. `fluid_capacity` (`ymir_particle_capacities.fluid`, `Box3DSoaParticleCapacities.Fluid`, 0 by default) is the most
|
||||
live fluid particles: `create_particles` refuses a batch past it whole (`FULL`, no lane taken). Pass B reads the lists: each fluid row in index
|
||||
order, each listed neighbour in list order, a fluid neighbour below the row skipped (its own row does the pair), a solid always done from the
|
||||
fluid row; a pair moves by `d = (lambda_i + lambda_j) grad W / n0(h)`, end `i`
|
||||
by `w_i d` and end `j` by `-w_j d`, applied after the pass (equal masses move as before; a static end takes nothing and the fluid its XPBD share, so the energy at 30 : 1 and 100 : 1 does not rise). A pair therefore
|
||||
carries equal and opposite momentum at any mass ratio (a solid end is the reaction: `m_i dx_i = -m_j dx_j`), a zero-mass end
|
||||
takes nothing, and the one pair formula serves fluid with fluid and with solids. Then the fluid-solid contact (the contact pass never sees a fluid lane: the contact grid holds
|
||||
the other lanes only, at `2 r_max`): two passes over the fluid rows' lists, the first counting the overlaps of each listed solid at `ri + rj`, the second moving both ends as the contact
|
||||
pass does, weight `1 / max(n_i, n_j)` over these pairs only, applied after (Jacobi); PhysX solves fluid-solid in its fluid pass the same way. The XSPH viscosity of Schechter and Bridson
|
||||
runs after the velocity update over the same lists (fluid neighbours above the row), `dv = c (v_j - v_i) W / n0` with `c` the mean of the two
|
||||
materials' `viscosity`, split by inverse mass the same way, and only when some material has a viscosity above 0 (one scan of the material lanes a substep). A pair that
|
||||
entered reach since pass A is missed by XSPH (smoothing, not a constraint). Lists, copies and the fluid grid are per-substep scratch, carved once at create: 28 bytes a particle lane
|
||||
(`nbr_start`, `nbr_count`, `sx sy sz sw sphase`; h1's per-lane lists were 388) and 384 a unit of fluid capacity. A world with no live fluid steps byte-identically to
|
||||
one before fluid (no pass runs: `live_fluid` counts the live fluid particles, written by create and destroy only). Cost on the 16 x 16 sheet scene at 4 substeps, increment over the same scene without fluid (Release, three runs; the cost line in `Box3DSoaCouplingTests` now prints the median of nine interleaved with-and-without pairs and its interquartile range):
|
||||
512 fluid +0.76 to +0.84 ms a tick at viscosity 0 and +0.86 to +1.01 at 0.01; 2000 fluid +4.1 to +4.4 at both, against a target of 1.0 ms at 512 (h1: +3.0 to +3.4 and +13.1 to +13.9). The probe behind the design
|
||||
(a standalone replica of the pass) read 7 ns a cell visit in the 125-cell walk: the cost was per cell, not arithmetic, so the cell is now the kernel reach and the copies and the branchless filter keep the 27 buckets cheap. Two counting sorts a substep run with fluid live.
|
||||
sensor lane `particle_density` reads `n_i / n0` (1 at rest, 0 for a solid) in the last substep the particle ran.
|
||||
Support lanes `particle_support_body` and `particle_support_particle` (ABI 13; `SupportBody`, `SupportParticle` in the binding) name what a fluid particle touched in the
|
||||
last substep it ran. Both are cleared to -1 for each live fluid lane at the start of the substep, after prediction, and written by the substep's contacts: body contact
|
||||
sets `support_body` to the lane of each shaped body whose surface comes within the particle's radius, bodies ascending, so the highest lane touched wins; the fluid-solid
|
||||
contact pass sets `support_particle` to the first solid listed in the particle's row that touches it (pass 1 of the walk, the solid's lane). A fluid particle resting only
|
||||
on fluid reads -1 on both, so the bottom of a deep pool is supported and the interior is not; a solid lane, a free lane and a lane after create or destroy read -1 too.
|
||||
The lanes name contact, not rest: the caller judges speed. They are notification only, written by the step and read by no pass; a world with no settled liquid
|
||||
steps byte-identically to ABI 12. `destroy_particles` writes -1 to a destroyed lane's support lanes and to the `support_particle` of every live drop that named a destroyed solid, so no read after a destroy
|
||||
names a dead lane.
|
||||
- Settle (ABI 14). Liquid at rest becomes data: `settle(n, handles)` (`Box3DSoaWorld.Settle`) turns each named fluid particle into volume in a wet patch and destroys the particle (through
|
||||
`destroy_particles`, the ISOLATED derivation reused: fluid holds no constraint). A patch is a disc of settled liquid on one support: a body (`wet_body`, its point in the body's frame: the
|
||||
particle's nearest surface point from the proxies, which the command refreshes first, so it follows the body) or a solid particle (`wet_particle`, point 0); the other support reads -1. Lanes
|
||||
`wet_body wet_particle wet_x wet_y wet_z wet_radius wet_volume wet_material wet_live wet_generation wet_removed_at` (capacity `wets`, `YMIR_LANES_WET` = 4 for `remove` and `free_slots`, lanes
|
||||
tombstoned and reused as the others). A drop's support is its last step's `support_body` (else `support_particle`); one with neither is refused. A drop's volume is `(2 r)^3`, its patch's radius
|
||||
`sqrt(volume / (pi film))` with `YMIR_WET_FILM` = 1 mm (one constant; a film per liquid is not added). In handle order a drop joins the lowest live patch on the same support and material whose
|
||||
disc holds its contact point (volumes add, the centre is the volume-weighted mean, the radius is recomputed); else it takes the lowest free lane; else it joins the nearest patch of the same support
|
||||
and material; else (no patch on its support) it adds its volume to the nearest live patch of its material in the world, by world distance from the drop to the patch's centre (the patch's body pose applied; ties go to the lowest lane), and that centre stays; else (no live patch of its material at all) the batch is refused `FULL`, whole, and every lane is as it was (an undo log sized by `fluid_capacity`). A dead or non-fluid particle, a stale handle, a particle named twice
|
||||
or one with no support is refused whole too. `wet_volume` per body (the view's `WetVolume`, `body_wet_volume` natively) is the sum of the live patches on the body in wet lane order, written by
|
||||
`rederive_wet` alone, which `settle`, `take_wet`, `remove(WET)` and `destroy_particles` (when it kills patches on the solid particles it destroys) call; the step never writes a wet lane or the volume. `remove(WET)` kills patches and ends in `rederive_wet`,
|
||||
never in `rederive_topology`; `destroy_particles` kills the patches on the solid particles it destroys. `settle` and `remove` return the patch handles to read. Material `wet_friction` (>= 0) is stored
|
||||
and viewed (`MaterialWetFriction`), and lowers friction where the liquid lies (below). Which particles settle, and when, is the caller's policy
|
||||
(speed, age, film depth: `lodur:follow_up:bds-blood-settle-policy`); Ymir holds the data and the command.
|
||||
- Sensors (ABI 15). A liquid sensor is a sphere fixed in a body that reads the liquid volume inside it: `create_sensors(n, desc{body, point, radius})` (`Box3DSoaWorld.CreateSensors`; `point` in the body's frame, `radius` m,
|
||||
capacity `sensors`, `YMIR_LANES_SENSOR` = 5 for `remove` and `free_slots`, lanes tombstoned and reused as the others) refuses the whole batch, changing nothing, for a body outside the world's body count, a radius that is not
|
||||
finite and > 0, a non-finite point, or too few free lanes. Lanes `sensor_body sensor_x sensor_y sensor_z sensor_radius sensor_liquid_volume sensor_wet_volume sensor_live sensor_generation sensor_removed_at`; a free lane reads
|
||||
live 0, body -1 and 0 elsewhere. At the end of every step `ymir_particles_end` writes `sensor_liquid_volume` (m^3): for each live sensor in lane order, the sum in lane order of `(2 r)^3` over the live fluid
|
||||
particles whose centre lies within `radius` (distance squared <= radius squared) of the sensor's centre, the body's proxy position plus the proxy rotation applied to `point`, in the pose the last substep left the
|
||||
proxy in; 0 when no fluid is live. A second lane, `sensor_wet_volume` (`SensorWetVolume`), is the pooled liquid: the sum of the volumes of the live wet patches whose centre lies within `radius` of that centre, on any body or
|
||||
solid particle (a body's patch centre is in its body's frame: the sphere is taken into that frame, culled against the body's disc box and walked through the wet index by centre x, bodies ascending; a patch on a solid particle
|
||||
sits at the particle's position and is summed after, in wet lane order, by a scan of the wet lanes, which have no index). Two numbers, not a sum, so a consumer weighs pooled and moving liquid apart
|
||||
(`lodur:ruling:liquid-sensor-reads-pooled-liquid`). Both are end-of-step readings: a `settle`, `destroy_particles` or `remove` between steps shows at the next step, which is the contract. The pass runs before `ymir_particles_end`'s early return for no live particle, so a sensor never keeps a reading once the liquid is gone. The readings are sensors: the step
|
||||
writes them and no pass reads them back, so a world with sensors steps byte for byte as one without, and a world with none steps as ABI 14. `remove(SENSOR)` ends in no topology derivation. Ymir names no organ
|
||||
(a head's airway, a lung): the consumer places a sensor and maps the volume (`lodur:follow_up:lodur-airway-liquid`). Gives up: a sphere only, not a shape-exact volume, and no per-liquid split.
|
||||
- Take (ABI 21). `take_wet(n, sensors, volumes, taken)` (`Box3DSoaWorld.TakeWet`) removes up to `volumes[k]` m^3 of pooled liquid from the wet patches sensor k reads, so liquid a body breathes in leaves the world.
|
||||
It refuses the whole call, changing nothing (INVALID_ARGUMENT), for n < 0, a NULL array with n > 0, a stale or dead sensor, a sensor named twice, and a volume that is not finite or is < 0 (managed: an
|
||||
`ArgumentException` for a handle that is not a sensor, unequal lengths, or a non-empty `taken` shorter than the sensors). Per sensor in call order: W is the pooled sum above, `f = W > 0 ? min(1, v / W) : 0`, and a second walk of
|
||||
the same sphere test (`pooled_walk`, shared with the reading, so the take removes from exactly the patches the reading summed, patches on solid particles included) scales every visited patch's volume by `1 - f`
|
||||
and its radius by `wet_disc_radius`; a patch at f = 1 is removed as `remove(WET)`. Proportional by design: the film on a face and the pool beneath it shrink together and no lane order decides whose liquid is taken. A later
|
||||
sensor in the call sees an earlier one's take (one index serves the whole call: a killed lane keeps its centre until the call's one `rederive_wet`, which returns it to rest, and a walk skips a lane that is not live); `taken[k]` (m^3) is the summed volume that left the patches, in double and
|
||||
rounded once, so float storage can leave it below the ask or 0; `rederive_wet` runs once at the end, and not at all when nothing changed. The proxies are refreshed first, as `settle` does. `sensor_wet_volume` is written by the step's end alone: the reading changes at the next step. Ymir names no organ (a lung, an airway):
|
||||
the consumer decides when liquid is breathed. Live drops are not taken (the caller destroys whole drops).
|
||||
- Wet friction. Settled liquid lowers friction where it lands, per contact, never per shape: `wet_mu(body, point, mu)` is `min(mu, wet_friction)` of the lowest live patch on that body whose
|
||||
disc holds the point (the point in the body's frame, as `wet_x wet_y wet_z` are), and `mu` at once when the body's `wet_volume` is 0. It is the one patch test. A particle that touches a body
|
||||
uses it at the nearest surface point for a solid particle (also `min` with `particle_wet_mu[i]`, the wet friction of the lowest live patch on that solid particle, +inf when dry, derived by
|
||||
`rederive_wet`); a fluid particle keeps its material friction. Body-body contact goes through the GameCult Box3D fork's `b3World_SetContactFrictionCallback`: `b3UpdateConvexContact` calls the
|
||||
hook right after the mix (`sqrt(frictionA frictionB)`) with the mean of the manifold points in each body's frame (one point per manifold), both bodies' user data (lane + 1) and the mixed value,
|
||||
and the world's hook returns `wet_mu` on B of `wet_mu` on A of it: it only lowers. The read is race-free (patches change only between steps) and a world with no settled liquid steps byte for
|
||||
byte as before. Box3D skips `contactFrictionFcn` for `b3_simMeshContact` (so wet friction does not apply to `StaticHeightField` or `StaticMesh` contacts). The fork runs the hook on a recycled contact too (Box3D skips a recycled contact's update, and with it the friction mix): it mixes again and calls the hook, only when a hook is installed, so friction follows a patch settled or removed under a body at rest. The lookup is culled: `rederive_wet` indexes the live body patches by body then centre x with each body's box and largest radius (`wet_order`, `wet_body_start`, `wet_body_count`, `wet_body_box`), so a point outside the body's box is a constant check and one inside binary-searches the x window; the lowest lane still decides. The fork's own tests: `test.exe WorldTest` (the unfiltered run stops at CompoundTest, which fails at the fork's base as well). No ABI change (14).
|
||||
Fluid holds no constraint: `create_distances` and `attach` refuse a fluid particle, so `create_bends` (over distances) can
|
||||
never name one; a thing that holds liquid is cloth around free fluid (a balloon), as in Flex sec. 8. Every `create_particles`
|
||||
and every `destroy_particles` of particles that held no distance derives only the isolated lanes
|
||||
(`rederive_topology` with the ISOLATED mode: `component[i] = i` for created lanes, 0 for destroyed, tethers untouched): emitting
|
||||
and removing 64 fluid particles a tick on the 20-pin 32 x 32 sheet costs 0.3 ms a tick of commands where the full derivation
|
||||
costs 4.2 ms.
|
||||
- Coupling (unchanged): one proxy per body (pose, velocity, shape, real inverse mass and world inverse
|
||||
inertia). Before each rigid substep's positions integrate, `b3Body_GetSubStepState` fills the proxies and `b3Body_ApplySubStepImpulse`
|
||||
delivers each dynamic body's correction as an impulse; the `particle_impulse` lane is the tick's total. Bodies are never
|
||||
teleported; no `b3Body_Apply*Impulse` or `SetTransform` runs from the particle path. The gate is the live particle count.
|
||||
- Sensors. Every correction is `lambda / h^2` in newtons, one scale. Distance `tension` is read by momentum balance: the
|
||||
constraint's own correction, the bends over it and the tether impulses routed leaves-first down each path tree each book their
|
||||
position impulse along the edge, over `h^2`, mean over the substeps; it reads the weight below each edge within 1% from 1 to
|
||||
70 kg whichever way the load is routed. Attachment `force` is the sum of the corrections at the point, tether load included. Loop
|
||||
caveat: a sensor reads the solver's corrections, and a load that circulates in a closed loop of the graph (a sheet pinned at
|
||||
four corners) is read as the corrections it needs, not as a statically determined split.
|
||||
- Particle determinism: single thread; constraints Gauss-Seidel in lane order; the one Jacobi pass (pair contact) accumulates corrections and applies them after the walk (each pair once, from the
|
||||
lower of its two cells, neighbours read in cell then index order from a stable counting-sort grid, a bucket shared
|
||||
by two cells is told apart by the cells' coordinates, a pair weighted the same at both ends); the heap and the breadth-first
|
||||
labelling break ties by lane; proxy impulses are summed per body in lane order, per substep; only `+ - * /`, `sqrtf` and `cosf`
|
||||
(at command time); the file builds with `-ffp-contract=off` (`/fp:precise` on MSVC). Same bytes on the same build, serial or with
|
||||
other worlds stepping on other threads. No threads in this cut.
|
||||
- Concurrency: see Threading below; world creation and destruction are serialized by Ymir's native lock.
|
||||
|
||||
## Tests
|
||||
|
||||
|
|
@ -46,11 +298,59 @@ difference diverging, argument refusal, dispose; and for joints: hinge angle and
|
|||
lanes agreeing, an off-axis hinge, a limit and a weld, a spherical joint leaving the swing plane, force and
|
||||
torque lanes (exact acceleration, cleared after the step, static bodies ignoring them, NaN refusing the
|
||||
step), capsule and box rest heights with parent and limb lanes, refusals, and bit-identical repeat runs of
|
||||
a torque-driven jointed body.
|
||||
a torque-driven jointed body. `Box3DSoaGrabTests`: a strong grab reaching a target 1 m away within 1 s, a weak grab falling at least `g - F/m`, an anchor that does not collide and is not hit by a ray, force lanes not moving an anchor, an off-centre impulse (linear `J/m` and the spin's sign and size), the ray's nearest body with lane, stable id, point and fraction, refusals changing nothing, and bit-identical repeat runs with a moving anchor and an impulse. `Box3DSoaContactTests`: a drop gives one begin and one hit (speed within 5%
|
||||
of sqrt(2gh), point and normal), lifting gives one end, dropped counters resetting each step, materials on
|
||||
hits, facts lasting one step, overflow counted, per-step byte determinism of facts and contact lanes, and
|
||||
no allocation across 100 steps with fact reads. `Box3DSoaImpulseTests`: `contact_impulse` and the hit `impulse` equal the momentum change of the bodies the contact acted on, plus their weight, within 1e-4 of the peak at every step: a 5 kg ball and a 0.3 g BB at 100 m/s onto a jointed forearm (the BB reads 0.030 N s, the ball over 400 times more), the arm falling forearm-first onto a slab, a sphere dropped 1.4 m at 60 and 240 Hz, 1 and 4 sub-steps, restitution 0 and 0.5, two free bodies at restitution 0 and 0.5; a swung arm into a slab, a big sphere with 60 small ones converging (more contacts than graph colours, so the scalar overflow solver runs: the big lane is the sum of the small lanes, each equal to its own momentum change), and at rest `contact_impulse / dt` is the weight (0.1%, a lone sphere) while a body touching nothing reads 0.
|
||||
|
||||
`Box3DSoaRemoveTests`: removing a body retires its joints and zeroes its lane (old handles stale, others untouched, facts one step), is refused while an attachment or a liquid sensor names it, each alone and for an anchor too (nothing changed; after the caller removes them it succeeds; attach, sensors, add_joint and a parent then refuse the lane), refuses a current-generation handle to a tombstone (destroy_joint and remove_body) and lets an add reuse stable id 0, skips a removed lane in the particle substeps and the write-lane check (its write lanes are still cleared), names every removed toucher over 200 single-removal steps in a two-lane world (the retired table is cleared each step), survives 12 seeds of random add/remove churn on a floor (run in Debug too: Box3D validates its broad-phase there), takes its wet patches with it (count and summed volume on the fact, another body's patches untouched), ends a grab when the anchor goes, ends a touch by name, leaves a drop unable to settle, keeps the other lanes' state, reuses a lane one step later with a new generation, repeats bit for bit with removals and thresholds over 300 steps and allocates nothing managed. `Box3DSoaJointTests`: the constraint lanes read m g, an overload is reported once its load reaches the threshold and the joint stays, thresholds are refused when NaN or negative. `Box3DSoaGrabTests`: every joint kind destroys through one path. `Box3DSoaParticleTests`: the ABI 8 scene's six checkpoint hashes with no particle capacity (pinned from 5104b17); a 48-particle rope (a builder in the tests: distances and soft bends) hanging from a tethered static point under 1% stretch for 4 s; a 70 kg sphere held by the same rope (from 1 s to 5 s speed under 0.001 m/s, stretch under 0.1%, the impulse per tick within 0.5% of m g dt); an anchor dragging a 5 kg box along the floor (`particle_impulse` reads it); a sphere, capsule, box and static box each pushed into a lying rope's end (no particle over 10% of its radius inside); a 16 x 16 sheet from the same two commands hung by two corners (after 5 s the corners carry the weight within 1% and no edge is past 5%), and by two corners of two pins each (after 8 s, same bounds: it still rings at 5 s); edge tension, the edge at 0, 10 and 46 and both attachment forces read the load at 1, 5, 20 and 70 kg; a cut (remove an edge of a hung 40-rope: the bends over it die, tethers 39 -> 19, the component splits, the head holds and the tail falls); overload (300 kg) removes nothing; destroying a mid-rope particle removes its constraints and releases a held body; a 24-particle cantilever at 32 substeps under a 30 and a 10 degree hard limit and a stiff and a floppy soft pass, and a limit-only bend bit-identical to no bend inside its cone; momentum of a rope, a sheet and a blob thrown into each other with no gravity within 5e-4 and energy never rising; phase rules (groups, `SELF_COLLIDE`, `SELF_FILTER`, a folded rope); an off-centre attachment spinning a free box by I^-1 (r x J) within 2%; lanes reused after a step lowest first, stale generations refused, a derivation that does not fit refused with no lane changed, bad input refused; a pile of four ropes and a sheet on two bodies byte-equal across two runs at six checkpoints (pinned), a one-ulp difference diverging, and eight concurrent worlds giving the serial bytes; no allocation across 100 steps and across a cut, a destroy and a create, and none for a 300-distance batch created and removed; gravity along each axis; a spinning box carrying its attachment point and two ends on one light box settling (the proxy's rotation); one group's `SELF_COLLIDE` needing both particles and `SELF_FILTER` either; a slack pair tether leaving its body alone; a refused `attach` leaving no lane and no tether; each particle on the nearest point of its two nearest islands (a 5-rope held at both ends, a star whose centre keeps the two nearer arms, a 9-rope with two touching points counting as one island) and no pair between two static points; every tether's parent present after each of 20 attaches on a 32 x 32 sheet (float ties at rank 2 gated); a particle held by two bodies touching neither. `Box3DSoaParticleSourceTests` reads the C source: no Box3D call in `ymir_particles.*`, no allocation outside create and free, no threads or atomics, no rope, sheet, cloth or chain identifier in the solver or the binding, the tether and component lanes written only by the derivation, every topology command ending in it, `begin` and `end` called once (in the step), `substep` once (in the callback), the callback the only user of the fork's two accessors, no topology change in the phases, and the retired names absent.
|
||||
|
||||
`Box3DSoaCouplingTests` (also the batch file): a 256-attachment sheet attached one by one and as one batch ends with equal lanes, generations and state after 120 steps; a batch with one bad desc (a fluid particle, a removed body, `STATIC` with `ONE_WAY` or `LIMB`), more descs than free lanes, or a derivation past the tether capacity changes no lane; `ONE_WAY` leaves its box at speed 0 with a 0 impulse lane while the particle holds its point; spawn cost lines for 256 attachments and for one and four Fellas. A sphere thrown at 5 m/s with a 48 x 20 g rope from rest keeps x momentum within 0.1% and gains no energy, at 5 and 70 kg; thrown up it reaches the apex momentum allows; 5 kg snapping a taut rope at 6 m/s keeps at most 5% of its energy and 70 kg is still within a tick; a 45 degree pendulum for 12 s gains no energy and loses at most 1.25 times a heavy-particle control, and a hung body keeps its spin about the vertical; removing the body attachment or destroying the rope's particles frees a held 70 kg body in the step after, with no upward impulse; `particle_impulse` equals M dv minus M g dt every tick, hung and thrown; material friction 0.6 holds a rope on a 20 degree slope and friction 0 does not; no particle is farther from a tethered point than its rest path; an attached end stays on its body point; a world whose only body is static still steps the particles (a dropped rope falls g t^2 / 2 within 2%) and rests; and a cost line with 16 ropes x 48 and one 16 x 16 sheet at 4 substeps, one body and forty (printed, not asserted).
|
||||
|
||||
`Box3DSoaTerrainTests`: a bowl `StaticHeightField` catching a dropped sphere (sliding into the bowl centre with zero tunneling) and box (resting flat at bowl height), a `StaticMesh` box-prism roof drop and horizontal wall drive without penetration, `CastRayClosest` returning accurate hit point, surface normal, lane, and stable id on both `StaticHeightField` and `StaticMesh`, 10 x 20 repeated add/step/remove/dispose churn cycles with live particles (verifying `BodiesRemoved` and `End` touch facts), and clean refusal without slot consumption on invalid grid/mesh inputs (all-degenerate collinear or repeated-index triangles, out-of-bounds `>= 50000f` / `> 1e5f` vertex coordinates, overflowing `min_height = -2e38f, max_height = +2e38f` or scaled extents `>= 1e5f`, and oversized `count_x * count_z > 64M`, `triangle_count > 16M`, or `vertex_count > 32M`).
|
||||
|
||||
## Not done
|
||||
|
||||
Contact facts for the SoA world (Begin/Hit/End), body removal with a stable ordering rule, compound bodies
|
||||
and per-shape material, joint motors and springs (Lodur drives joints from torque lanes instead), and a
|
||||
public typed surface in `Ymir.Core` (the wrapper is internal, visible to the test assembly). Windows build
|
||||
and Unity consumption are unrun; cross-platform bit-identity is unclaimed.
|
||||
`Box3DSoaFluidTests`: the refusals (a distance or attachment naming fluid, a viscosity below 0 or not finite; a batch of fluid past the fluid capacity, refused whole); 64 fluid particles created and destroyed a tick on the 20-pin sheet leaving every tether lane byte-equal; an 8 x 8 x 16 column in a box well (max density, mean density, nothing outside); fluid thrown into a free sheet and rope at fluid : solid mass 64 : 20, 1 : 30, 30 : 1 and 100 : 1 (momentum drift, energy on every row); a 343-particle fluid block dropped 15 cm onto a floor of immovable solid particles at 4 substeps (penetration, nothing through the floor's interior bar the one particle over a lattice hole); probe scene 3, the 343-particle pour on a tilted sheet and a sloped rope at 4 substeps, printed as readings with the same block flagged solid as the control, asserting nothing; fluid pushing a free box with the impulse lane equal to its M dv; a 3 r lattice not clumping; XSPH damping a shear field; the kernel reaching a larger solid beyond two contact radii; the pour's six checkpoint hashes (two runs, a one-ulp nudge, eight concurrent worlds). Each bound states its readings and the mutant it separates from. `Fluid_cost_line` prints 512 and 2000 fluid particles on the sheet scene at viscosity 0 and 0.01. Overflow is asserted 0 in the column, the floor and the pour.
|
||||
|
||||
Compound bodies
|
||||
and per-shape material, and motor joints with a velocity target (the motor joint here is a position spring only; Lodur drives limbs from torque lanes). A one-call cascading `remove_body` that also removes the attachments and sensors naming the body is not built: the caller removes them first.
|
||||
Consumers use `Ymir.Box3D` (`Box3DSoaWorld`) directly.
|
||||
Unity consumption is unrun; cross-platform bit-identity is unclaimed.
|
||||
|
||||
Particles: a sheet pinned at few points sieves at 4 substeps (the pour stretches a corner-pinned 16 x 16 sheet 38% and a same-size particle passes it, a same-mass solid block worse; per-substep travel is about 1 cm against a 4 cm contact, so it is the sheet and the contact solver, not the fluid: a loose-cloth limit, ruling ymir-sheet-sieve-at-budget-substeps); a sheet attached along its length to a body holds (`Skin_on_a_bone_holds_under_pour_and_drop`: 30 skin particles on a capsule under a 343-particle pour or 64 dropped solids, 3 s at 4 substeps and 60 or 120 Hz, worst edge stretch 0.021, no load particle inside the bone, skin place held to float noise), so BDS skin needs no more substeps, no boundary density for rigid bodies (a Box3D body adds nothing to a fluid particle's density estimate, so fluid
|
||||
beside a wall or floor under-reads: a 8 x 8 x 16 column in a box well reads 0.88 mean at zero gravity), no cohesion, adhesion or
|
||||
vorticity, no settle of fluid to rest (the column keeps a velocity noise, 1.25 m/s at its worst at 3 s with the one pass a substep, 0.82 with viscosity 0.1), a column compresses under its own weight (max density 1.34 on 16 layers), no pinning command beyond zero mass and attachments, no
|
||||
sleep, no threads, no particle write lanes. A heavy body cannot be held up by contacts against a floor (the particles are squeezed
|
||||
between two solids a position solver cannot satisfy at a 50:1 mass ratio; the pushing tests drive the body into a rope end
|
||||
instead). A snap on a taut rope is inelastic by the solver's construction, and a swung weight loses a few percent more as a tied
|
||||
body than as a heavy particle; neither gains energy.
|
||||
A hard bend limit is one iteration per substep and is not rigid at the substep counts the tests run; whether to change the solver is
|
||||
the open question `bend-limit-stiffness`, and the solver is as it was. Measured on a 24-particle cantilever held at two particles, 600 ticks at 60 Hz, the
|
||||
largest deflection of one joint: a 10 degree limit allows 21.7 degrees at 4 substeps and 22.3 at 8, 13.6 at 32 under a 1 kg tip and
|
||||
32.0 at 32 under a 5 kg tip; a 30 degree limit allows 31.5 at 4, 33.8 at 8 and 29.9 at 32 under a 5 kg tip. A soft bend is no stiffer
|
||||
than a floppy one at 4 or 8 substeps (tip drop with no load, stiff 1e-7 against floppy 1e-4: 0.764 m against 0.779 at 4, 0.835
|
||||
against 0.822 at 8, 0.053 against 0.798 at 32 where it reads as pinned). Read a bend limit as a guide below about 32 substeps and
|
||||
not at all under a heavy tip. A 16 x 16 sheet hung by two corners rings for about 9 s before the corners carry its weight within 1%
|
||||
(by two corners of two pins each, about 6 s). Pair contact
|
||||
conserves momentum to float32 rounding of the positions, which grows with the particle mass ratio (0.6% at 30:1, 6% at 100:1);
|
||||
the momentum test's 5e-4 is that floor, not a contact property: translating the whole scene moves its drift between 0.56e-4 and
|
||||
4.0e-4 under either contact walk, and the per-particle-average mutant reads 5.6e-2.
|
||||
Determinism under MSVC's
|
||||
`/fp:precise` is unbuilt (no `cl` on the workstation).
|
||||
|
||||
## Build and lifetime notes
|
||||
|
||||
- Native library name: `ymir_box3d.dll` on Windows (MinGW needs `PREFIX ""`, set under `if(MINGW)`; MSVC emits it
|
||||
natively), `libymir_box3d.so` on Linux, `libymir_box3d.dylib` on macOS. `Ymir.Box3D.csproj` copies from
|
||||
`bin\$(Configuration)\` on every platform: `CMakeLists.txt` writes `bin/$<CONFIG>/` and the csproj passes `-DCMAKE_BUILD_TYPE=$(Configuration)`, so single- and multi-config generators land in the same place.
|
||||
- Windows run: MinGW gcc with `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; `Ymir.Box3D.Soa.Tests` passes.
|
||||
Linux run (Yggdrasil, default generator, gcc): the same tests pass and emit `bin/Debug/libymir_box3d.so`. macOS is unrun.
|
||||
- Threading: creating and destroying worlds is safe from any number of threads at once (a process-wide lock in `ymir_box3d_soa.c` serializes `b3CreateWorld`/`b3DestroyWorld`, which otherwise scan and rewrite Box3D's global world pool unsynchronized). Stepping distinct worlds concurrently is not known to race: Box3D's own docs promise no thread safety, and this rests on a reading of the pinned source and one light test. A single world
|
||||
is still not thread-safe. `Box3DSoaConcurrentCreateTests` creates, steps and disposes worlds from eight threads.
|
||||
- At most 128 live worlds per process (Box3D's `B3_MAX_WORLDS`); creating more trips a Box3D assert, not a managed error.
|
||||
- `Box3DSoaWorld` is not thread-safe: `Dispose` must not race `Step` or a lane read. A `Box3DSoaView` refuses
|
||||
to hand out a lane (ObjectDisposedException) once its world is disposed, and a `default` view refuses with
|
||||
InvalidOperationException. The check guards obtaining a span, not a span already held: a span taken from a
|
||||
view must not be used after the world is disposed. Known limit: an undisposed world leaks its
|
||||
native memory; there is no finalizer or SafeHandle.
|
||||
|
|
|
|||
2
extern/box3d
vendored
2
extern/box3d
vendored
|
|
@ -1 +1 @@
|
|||
Subproject commit 8441b4a06d6d09dcfb0b0f704df4d847d1437b92
|
||||
Subproject commit c7908394eb3ec3aa0f54bf26a98a683c1950ac15
|
||||
|
|
@ -11,7 +11,7 @@ set(BOX3D_VALIDATE ON CACHE BOOL "" FORCE)
|
|||
|
||||
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../../extern/box3d" "${CMAKE_CURRENT_BINARY_DIR}/box3d")
|
||||
|
||||
add_library(ymir_box3d SHARED ymir_box3d.c ymir_box3d_soa.c)
|
||||
add_library(ymir_box3d SHARED ymir_box3d_soa.c ymir_particles.c)
|
||||
target_link_libraries(ymir_box3d PRIVATE box3d::box3d)
|
||||
target_include_directories(ymir_box3d PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/box3d/include")
|
||||
target_compile_features(ymir_box3d PRIVATE c_std_17)
|
||||
|
|
@ -21,6 +21,14 @@ endif()
|
|||
|
||||
set_target_properties(ymir_box3d PROPERTIES
|
||||
C_VISIBILITY_PRESET hidden
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$<CONFIG>"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$<CONFIG>"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
|
||||
if(MINGW)
|
||||
# MinGW would emit libymir_box3d.dll; the managed side loads ymir_box3d.dll.
|
||||
set_property(TARGET ymir_box3d PROPERTY PREFIX "")
|
||||
endif()
|
||||
|
||||
# The particle solver's bytes must not depend on whether the compiler fuses a multiply and an add.
|
||||
set_source_files_properties(ymir_particles.c PROPERTIES COMPILE_OPTIONS
|
||||
"$<IF:$<C_COMPILER_ID:MSVC>,/fp:precise,-ffp-contract=off>")
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
3117
native/Ymir.Box3D/ymir_particles.c
Normal file
3117
native/Ymir.Box3D/ymir_particles.c
Normal file
File diff suppressed because it is too large
Load diff
330
native/Ymir.Box3D/ymir_particles.h
Normal file
330
native/Ymir.Box3D/ymir_particles.h
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps
|
||||
// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body
|
||||
// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver moves those proxies by the
|
||||
// constraints it solves, and the impulse each body accumulated comes back in the proxy for soa.c to apply.
|
||||
// See docs/soa-world.md.
|
||||
//
|
||||
// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type
|
||||
// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a
|
||||
// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every
|
||||
// topology command ends in and which is their only writer.
|
||||
//
|
||||
// Determinism: single thread; constraints are Gauss-Seidel in lane order; the one Jacobi pass (particle-particle
|
||||
// contact) accumulates and applies after the walk (each pair once, from the lower of its two cells, neighbours read in cell then index order
|
||||
// from a stable counting-sort grid, a pair weighted the same at both ends); proxy impulses are summed per body
|
||||
// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise
|
||||
// on MSVC) so no fused multiply-add changes a byte.
|
||||
//
|
||||
// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019).
|
||||
// No code of PhysX 5.6.0 or any other solver is adapted here.
|
||||
|
||||
#ifndef YMIR_PARTICLES_H
|
||||
#define YMIR_PARTICLES_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
enum
|
||||
{
|
||||
YMIR_PARTICLES_OK = 0,
|
||||
YMIR_PARTICLES_INVALID_ARGUMENT = 1,
|
||||
YMIR_PARTICLES_DUPLICATE_ID = 2,
|
||||
YMIR_PARTICLES_FULL = 3,
|
||||
YMIR_PARTICLES_OUT_OF_MEMORY = 4,
|
||||
YMIR_PARTICLES_REFERENCED = 6 // a body that a live attachment or sensor names cannot be released
|
||||
};
|
||||
|
||||
// Phase word: bits 0-19 are the group; the four flags below are the only other bits.
|
||||
enum
|
||||
{
|
||||
YMIR_PHASE_GROUP_MASK = 0xFFFFFu,
|
||||
YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it)
|
||||
YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it)
|
||||
YMIR_PHASE_FLUID = 1u << 22, // a fluid particle: number density, not contact, with other fluid; contact with solids. Group and
|
||||
// the SELF_* flags are ignored between two fluid particles (all fluid shares one density field)
|
||||
YMIR_PHASE_NO_PARTICLE_CONTACT = 1u << 23, // not in the solid contact grid: no contact with another particle that is not fluid;
|
||||
// bodies stop it and fluid still meets it. Refused with FLUID
|
||||
YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER | YMIR_PHASE_FLUID |
|
||||
YMIR_PHASE_NO_PARTICLE_CONTACT
|
||||
};
|
||||
|
||||
// Lane sets a command names (a type for remove, a set for free_slots).
|
||||
enum
|
||||
{
|
||||
YMIR_LANES_PARTICLE = 0,
|
||||
YMIR_LANES_DISTANCE = 1,
|
||||
YMIR_LANES_BEND = 2,
|
||||
YMIR_LANES_ATTACHMENT = 3,
|
||||
YMIR_LANES_WET = 4, // a wet patch: settled liquid on a body or a solid particle
|
||||
YMIR_LANES_SENSOR = 5 // a liquid sensor: a sphere fixed in a body that reads the liquid volume inside it
|
||||
};
|
||||
|
||||
enum
|
||||
{
|
||||
YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane)
|
||||
YMIR_ATTACH_STATIC = 1, // particle to a world point
|
||||
YMIR_ATTACH_REMOVED = 2
|
||||
};
|
||||
|
||||
enum
|
||||
{
|
||||
YMIR_ATTACH_FLAG_TETHER = 1u, // bounds each particle by the rest path to the nearest point of its two nearest islands of tether attachments
|
||||
YMIR_ATTACH_FLAG_LIMB = 2u, // the particle is flesh of its body's limb tree: contact skips every body whose limb-tree root is the attached body's root; refused on a STATIC attachment
|
||||
YMIR_ATTACH_FLAG_ONE_WAY = 4u // the body side weighs nothing: the attachment holds its particle to the body's point and never moves or loads the body (the bone's own mass already carries the flesh); refused on a STATIC attachment
|
||||
};
|
||||
|
||||
enum
|
||||
{
|
||||
YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it
|
||||
YMIR_PROXY_SPHERE = 1,
|
||||
YMIR_PROXY_CAPSULE = 2, // segment along local Y
|
||||
YMIR_PROXY_BOX = 3
|
||||
};
|
||||
|
||||
// A lane and the generation it had when the handle was made.
|
||||
typedef struct ymir_handle
|
||||
{
|
||||
int32_t lane;
|
||||
uint32_t generation;
|
||||
} ymir_handle;
|
||||
|
||||
typedef struct ymir_particle_capacities
|
||||
{
|
||||
int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets, sensors; // fluid: the most live particles with the FLUID phase; wets: the most wet patches; sensors: the most liquid sensors
|
||||
} ymir_particle_capacities;
|
||||
|
||||
// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and
|
||||
// the self-collision filter read it); `material` indexes the material table.
|
||||
typedef struct ymir_particle_desc
|
||||
{
|
||||
float position[3];
|
||||
float rest[3];
|
||||
float velocity[3];
|
||||
float mass;
|
||||
float radius;
|
||||
uint32_t phase;
|
||||
uint32_t material;
|
||||
} ymir_particle_desc;
|
||||
|
||||
// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0.
|
||||
typedef struct ymir_distance_desc
|
||||
{
|
||||
ymir_handle a, b;
|
||||
float rest;
|
||||
float compliance;
|
||||
} ymir_distance_desc;
|
||||
|
||||
// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off;
|
||||
// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off.
|
||||
typedef struct ymir_bend_desc
|
||||
{
|
||||
ymir_handle e1, e2;
|
||||
float compliance;
|
||||
float max_angle;
|
||||
} ymir_bend_desc;
|
||||
|
||||
// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body)
|
||||
// or the world (static).
|
||||
typedef struct ymir_attachment_desc
|
||||
{
|
||||
uint32_t kind;
|
||||
uint32_t flags;
|
||||
ymir_handle particle;
|
||||
int32_t body;
|
||||
float point[3];
|
||||
float compliance; // m/N, >= 0
|
||||
uint32_t reserved;
|
||||
} ymir_attachment_desc;
|
||||
|
||||
// A liquid sensor to create: a sphere of `radius` m (> 0) centred on `point` in the frame of body lane `body`.
|
||||
typedef struct ymir_sensor_desc
|
||||
{
|
||||
int32_t body;
|
||||
float point[3];
|
||||
float radius;
|
||||
} ymir_sensor_desc;
|
||||
|
||||
typedef struct ymir_material_desc
|
||||
{
|
||||
float friction; // >= 0
|
||||
float viscosity; // >= 0, XSPH c (dimensionless): a fluid pair's velocities relax toward each other by c W / n0 per substep; mean of the pair's two
|
||||
float wet_friction; // >= 0: what settled liquid of this material does to friction where it lands; stored for the friction cut, read by nothing here
|
||||
uint32_t pad;
|
||||
uint64_t material_id;
|
||||
} ymir_material_desc;
|
||||
|
||||
// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse`
|
||||
// (N s, world, about the body position) are the totals the particle phase delivered, written by it.
|
||||
typedef struct ymir_particle_proxy
|
||||
{
|
||||
uint32_t shape;
|
||||
float size[3];
|
||||
float position[3];
|
||||
float rotation[4]; // x y z w
|
||||
float velocity[3];
|
||||
float angular_velocity[3];
|
||||
float inv_mass; // 0 for static, kinematic and anchor bodies
|
||||
float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz
|
||||
float impulse[3]; // N s, world: the tick's total, the sum of every substep's
|
||||
float angular_impulse[3];
|
||||
float sub_impulse[3]; // N s: this substep's, applied by the caller before the body's positions integrate
|
||||
float sub_angular[3];
|
||||
int32_t root; // the lane of the body's limb-tree root (the body itself when it has no parent); filled by the caller each step
|
||||
} ymir_particle_proxy;
|
||||
|
||||
typedef struct ymir_particles
|
||||
{
|
||||
int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity;
|
||||
int32_t body_capacity, fluid_capacity; // fluid_capacity: the most live fluid particles; it sizes the neighbour arena
|
||||
int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks
|
||||
int32_t tether_count; // derived: the live tethers
|
||||
int32_t body_count; // bodies filled in `proxies` this step
|
||||
int32_t live_particles;
|
||||
int32_t act_n, kin_n, act_dist_n, act_bend_n, act_att_n; // derived (rederive_active): the lengths of act, kin, act_dist, act_bend and act_att
|
||||
int32_t fluid_rings; // derived by fluid_density: rings of kernel cells (4 rfmax) that hold a kernel pair, 0 without fluid
|
||||
int32_t fluid_overflow; // kernel neighbours past a fluid particle's list in the last step, summed over substeps: a sensor
|
||||
int32_t wet_capacity, wet_count; // wet patches: the capacity and the high-water mark
|
||||
int32_t sensor_capacity, sensor_count; // liquid sensors: the capacity and the high-water mark
|
||||
int32_t live_fluid; // derived: the live particles with the FLUID phase bit; the create and destroy commands are its only writers
|
||||
ymir_particle_proxy* proxies;
|
||||
|
||||
// particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at
|
||||
float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass;
|
||||
float *rest_x, *rest_y, *rest_z;
|
||||
uint32_t *phase, *material, *particle_live, *particle_generation;
|
||||
uint64_t* particle_removed_at;
|
||||
uint32_t* pinned; // command-owned (set_pinned writes it; destroy_particles frees it to 0): a pinned particle is dormant, on no step walk, its pos and vel stale until wake; a reader draws it from its anchor
|
||||
// Derived by rederive_active alone, at command time; a step never writes them. act: the live unpinned particles; kin: the pinned particles an active
|
||||
// distance or bend reaches (the step sets their pos and pp from their anchor); act_dist and act_bend: the live constraints with an unpinned particle;
|
||||
// act_att: the live attachments of unpinned particles. All in lane order, so with nothing pinned they are every live lane and w is inv_mass.
|
||||
int32_t *act, *kin, *act_dist, *act_bend, *act_att;
|
||||
int32_t* anchor; // derived: the lane of the particle's lowest live non-TETHER attachment (BODY or STATIC), -1 for none; a pinned particle keeps the one it was pinned on
|
||||
float* w; // derived: the inverse mass the step reads: 0 for a pinned or free lane, else inv_mass
|
||||
int32_t* component; // derived: the lowest lane of the particle's distance-connected component
|
||||
int32_t *held_start, *held_count; // derived (rederive_topology): the slice of held_body that lists the bodies particle i is attached to (BODY attachments), contact skips them
|
||||
int32_t* held_body; // derived, attachment capacity: the live BODY attachments' bodies grouped by particle, in attachment lane order
|
||||
int32_t* limb_body; // derived: the body of the particle's lowest live LIMB attachment, -1 for none; contact skips every body in that body's limb tree
|
||||
int32_t *nbr, *nbr_start, *nbr_count; // scratch: the fluid rows' kernel neighbours in walk order, packed (CSR) in an arena of fluid_capacity * YMIR_FLUID_NEIGHBOURS; row i holds nbr_count[i] from nbr_start[i], this substep's
|
||||
int32_t *support_body, *support_particle; // sensor: what a fluid particle touched in the last substep, the highest body lane / the first solid lane its row listed touching it; -1 for none, and always -1 for a solid or free lane
|
||||
float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0
|
||||
|
||||
// wet lanes: a patch of settled liquid on one support, a body (wet_body, its point in the body frame) or a solid particle (wet_particle, point 0);
|
||||
// one of the two is -1, and a free lane holds -1 in both. Written by settle, take_wet, remove and destroy_particles only; the step never touches them.
|
||||
int32_t *wet_body, *wet_particle;
|
||||
float *wet_x, *wet_y, *wet_z, *wet_radius, *wet_volume; // wet_volume m^3; wet_radius = sqrt(volume / (pi YMIR_WET_FILM))
|
||||
uint32_t *wet_material, *wet_live, *wet_generation;
|
||||
uint64_t* wet_removed_at;
|
||||
int32_t *wet_order, *wet_body_start, *wet_body_count; // derived lookup index (rederive_wet): live body patches by body then centre x; each body's slice
|
||||
float* wet_body_box; // derived, 7 per body: min xyz and max xyz of its discs' boxes, then its largest radius
|
||||
float* particle_wet_mu; // derived, per particle lane: the wet friction of the lowest live patch on that solid particle, +inf when dry (rederive_wet)
|
||||
float* wet_volume_body; // derived, per body lane: the sum of the live patches on it in wet lane order (rederive_wet, at command time only)
|
||||
int32_t* wu_code; // settle's undo log, one entry per distinct drop: a patch lane (merged: its old lanes below) or -(lane + 1) (created)
|
||||
float *wu_x, *wu_y, *wu_z, *wu_volume;
|
||||
|
||||
// sensor lanes: a sphere fixed in a body; a free lane reads live 0, body -1 and 0 elsewhere except generation and removed_at. Written by create_sensors and
|
||||
// remove; sensor_liquid_volume and sensor_wet_volume are written by end alone, at the step's end (m^3): the sum of (2 r)^3 over the live fluid particles whose centre is inside,
|
||||
// and the sum of the volumes of the live wet patches whose centre is inside, on any body or solid particle
|
||||
int32_t* sensor_body;
|
||||
float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_volume, *sensor_wet_volume;
|
||||
uint32_t *sensor_live, *sensor_generation;
|
||||
uint64_t* sensor_removed_at;
|
||||
|
||||
// distance lanes
|
||||
int32_t *dist_a, *dist_b;
|
||||
float *dist_rest, *dist_compliance;
|
||||
float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor
|
||||
uint32_t *dist_live, *dist_generation;
|
||||
uint64_t* dist_removed_at;
|
||||
|
||||
// bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared)
|
||||
int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c;
|
||||
float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off
|
||||
uint32_t *bend_live, *bend_generation;
|
||||
uint64_t* bend_removed_at;
|
||||
|
||||
// attachment lanes
|
||||
uint32_t *att_kind, *att_flags, *att_generation;
|
||||
int32_t *att_particle, *att_body;
|
||||
float *att_point_x, *att_point_y, *att_point_z, *att_compliance;
|
||||
float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor
|
||||
uint64_t* att_removed_at;
|
||||
|
||||
// tether lanes: derived: grouped by island in lane order (an island: tether particles joined by live distances, named by its
|
||||
// lowest tether attachment), settle order within; per island one for each particle that is not a tether particle and holds the island
|
||||
// among its two nearest, to the attachment point it is nearest; then per attachment pair with a body among them a route of
|
||||
// booking lanes (attachment -1, edge only) along their rest path and the pair tether; parents come first;
|
||||
// other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point
|
||||
int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other;
|
||||
float* tether_bound;
|
||||
|
||||
// material table
|
||||
float *mat_friction, *mat_viscosity, *mat_wet_friction;
|
||||
uint64_t* mat_id;
|
||||
|
||||
// solver scratch, allocated once at create
|
||||
float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z, *lambda;
|
||||
float fluid_k; // n0(h) = fluid_k / h^3: the Poly6 sum over the simple-cubic lattice of spacing h / 2, a create-time constant
|
||||
int32_t *lane_list, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts;
|
||||
float *sx, *sy, *sz, *sw; // the fluid grid's lanes in sorted order (predicted position, inverse mass): scratch, only fluid_density reads them
|
||||
uint32_t* sphase; // the sorted lanes' phase
|
||||
int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *via, *owner, *tether_of, *queue, *comp_size, *isle, *near_isle;
|
||||
float *heap_key, *path, *near_path;
|
||||
uint8_t* done;
|
||||
uint32_t table_mask;
|
||||
uint32_t grid_mask; // scratch: the solid contact grid's bucket mask (build_grid writes it, walk_half reads it)
|
||||
void* arena;
|
||||
} ymir_particles;
|
||||
|
||||
// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure.
|
||||
ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, int32_t body_capacity);
|
||||
void ymir_particles_free(ymir_particles* p);
|
||||
|
||||
// The friction on body lane `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds it, never above mu.
|
||||
float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu);
|
||||
|
||||
// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest
|
||||
// lane first. Every refusal happens before anything changes; a command that would need more tethers than the
|
||||
// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command and set_pinned ends in
|
||||
// the one rederive_topology, which refuses whole (INVALID_ARGUMENT) a command that would leave one distance component holding both a pinned
|
||||
// particle and a live TETHER attachment (a tether loads every lane of its component, and no walk moves a pinned one): wake it first.
|
||||
int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out);
|
||||
int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count);
|
||||
int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out);
|
||||
int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out);
|
||||
// Attaches n particles in the lowest free lanes, by cursor, as a batch: every desc is validated, FULL when fewer than n lanes are free, one derivation, and a derivation that does not fit backs every lane out.
|
||||
int32_t ymir_particles_attach(ymir_particles* p, int32_t n, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
|
||||
int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count);
|
||||
// Pins (1) or wakes (0) the named particles. A pinned particle is dormant: on no step walk (a particle of a live distance or bend with an
|
||||
// unpinned particle is held on its anchor each substep instead), its pos and vel stale, drawn from its anchor. Refuses whole (INVALID_ARGUMENT,
|
||||
// nothing changed) a stale or dead handle, `pinned` not 0 or 1, a fluid particle, pinned 1 on a particle with no anchor, and what
|
||||
// rederive_topology refuses. The wake sets pos to the anchor's point at the proxies' pose now (the caller has filled
|
||||
// them) and vel to that point's velocity. Ends in rederive_topology. remove(ATTACHMENT) refuses a pinned particle's anchor.
|
||||
int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handle* h, uint32_t pinned);
|
||||
// Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else
|
||||
// support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole
|
||||
// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no live patch of its material anywhere to merge into, before any
|
||||
// change. A drop that finds no lane and no patch on its support adds its volume to the nearest patch of its material in the world (the patch's centre stays). `out` (NULL or n handles) receives the patch each drop landed in.
|
||||
int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count, ymir_handle* out);
|
||||
// Takes pooled liquid out of the wet patches a liquid sensor reads. Refuses whole (INVALID_ARGUMENT, nothing changed) n < 0, a NULL array with n > 0, a stale or dead
|
||||
// sensor, a sensor named twice, and a volume that is not finite or is < 0. Then per sensor in call order: W is the pooled volume of the patches whose centres lie in the
|
||||
// sensor's sphere (the walk the reading sums, at the proxies' pose now), f = W > 0 ? min(1, volume / W) : 0, and every patch in the sphere keeps (1 - f) of its volume
|
||||
// (radius recomputed; a patch at f == 1 is removed as remove(WET)): proportional, so no lane order decides which patch gives. A later sensor sees an earlier one's take.
|
||||
// `taken` (NULL or n floats) receives per sensor the summed volume that left the patches (m^3): float rounding can leave it below the ask, or 0. Readings change at the next step's end; none is written here. One rederive_wet at the end when anything changed.
|
||||
int32_t ymir_particles_take_wet(ymir_particles* p, int32_t n, const ymir_handle* sensors, const float* volumes, uint64_t step_count, float* taken);
|
||||
// Creates liquid sensors in the lowest free lanes. Refuses whole (INVALID_ARGUMENT) a body outside [0, body_count), a radius that is not finite and > 0, or a
|
||||
// non-finite point; FULL when there are not n free lanes; nothing changes. A sensor only reads: its volume moves nothing.
|
||||
int32_t ymir_particles_create_sensors(ymir_particles* p, int32_t n, const ymir_sensor_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
|
||||
// Frees what the particle layer holds on body lane `body` so the body can be removed: REFERENCED, changing nothing, while a live body
|
||||
// attachment or a live sensor names it (the caller removes those first); otherwise every live wet patch on it is removed (one rederive_wet) and
|
||||
// `patches` and `volume` (either may be NULL) receive their count and summed volume (m^3). No rigid-body call.
|
||||
int32_t ymir_particles_release_body(ymir_particles* p, int32_t body, uint64_t step_count, uint32_t* patches, float* volume);
|
||||
int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d);
|
||||
int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count);
|
||||
|
||||
// The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the
|
||||
// proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each
|
||||
// proxy's pose and velocity; it then applies each proxy's sub_impulse before positions integrate), end once.
|
||||
int32_t ymir_particles_begin(ymir_particles* p);
|
||||
void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz);
|
||||
void ymir_particles_end(ymir_particles* p, int32_t substeps);
|
||||
|
||||
#endif
|
||||
|
|
@ -1,277 +0,0 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Ymir.Box3D;
|
||||
|
||||
internal enum Box3DStatus
|
||||
{
|
||||
Ok = 0,
|
||||
InvalidArgument = 1,
|
||||
DuplicateId = 2,
|
||||
BufferTooSmall = 3,
|
||||
OutOfMemory = 4,
|
||||
InternalError = 5
|
||||
}
|
||||
|
||||
internal static partial class Box3DNative
|
||||
{
|
||||
internal const string LibraryName = "ymir_box3d";
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial uint ymir_box3d_get_abi_version();
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial nint ymir_box3d_get_build_id();
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_get_abi_layout(
|
||||
out uint bodyInputSize,
|
||||
out uint fieldInputSize,
|
||||
out uint bodyOutputSize,
|
||||
out uint contactOutputSize,
|
||||
out uint contactEventOutputSize);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_get_version(out int major, out int minor, out int revision);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DCastOutput ymir_box3d_cast_sphere(
|
||||
float originX,
|
||||
float originZ,
|
||||
float translationX,
|
||||
float translationZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius,
|
||||
int canEncroach);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DOverlapOutput ymir_box3d_overlap_spheres(
|
||||
float queryX,
|
||||
float queryZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_create(out nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial void ymir_box3d_session_destroy(nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_sync_bodies(
|
||||
Box3DSessionHandle session,
|
||||
Box3DBodyInput* bodies,
|
||||
int bodyCount);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_spawn(
|
||||
Box3DSessionHandle session,
|
||||
Box3DBodyInput* body);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_remove(Box3DSessionHandle session, ulong stableId);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_teleport(
|
||||
Box3DSessionHandle session,
|
||||
ulong stableId,
|
||||
float positionX,
|
||||
float positionZ,
|
||||
float directionX,
|
||||
float directionZ);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_set_velocity(
|
||||
Box3DSessionHandle session,
|
||||
ulong stableId,
|
||||
float velocityX,
|
||||
float velocityZ,
|
||||
float angularVelocity);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_configure(
|
||||
Box3DSessionHandle session,
|
||||
ulong stableId,
|
||||
float radius,
|
||||
float mass,
|
||||
float restitution,
|
||||
uint isStatic,
|
||||
uint isKinematic);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_apply_force(
|
||||
Box3DSessionHandle session,
|
||||
ulong stableId,
|
||||
float forceX,
|
||||
float forceZ);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DStatus ymir_box3d_session_apply_torque(
|
||||
Box3DSessionHandle session,
|
||||
ulong stableId,
|
||||
float torque);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_step(
|
||||
Box3DSessionHandle session,
|
||||
float deltaTime,
|
||||
int substepCount,
|
||||
Box3DRadialField* fields,
|
||||
int fieldCount);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_body_count(Box3DSessionHandle session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_copy_bodies(
|
||||
Box3DSessionHandle session,
|
||||
Box3DBodyOutput* output,
|
||||
int capacity,
|
||||
out int written);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_contact_count(Box3DSessionHandle session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_copy_contacts(
|
||||
Box3DSessionHandle session,
|
||||
Box3DContactOutput* output,
|
||||
int capacity,
|
||||
out int written);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_contact_event_count(Box3DSessionHandle session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial Box3DStatus ymir_box3d_session_copy_contact_events(
|
||||
Box3DSessionHandle session,
|
||||
Box3DContactEventOutput* output,
|
||||
int capacity,
|
||||
out int written);
|
||||
}
|
||||
|
||||
internal sealed class Box3DSessionHandle : SafeHandleZeroOrMinusOneIsInvalid
|
||||
{
|
||||
private Box3DSessionHandle() : base(true)
|
||||
{
|
||||
}
|
||||
|
||||
internal Box3DSessionHandle(nint value) : base(true) => SetHandle(value);
|
||||
|
||||
protected override bool ReleaseHandle()
|
||||
{
|
||||
Box3DNative.ymir_box3d_session_destroy(handle);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DBodyInput(
|
||||
ulong StableId,
|
||||
ulong CollisionCategoryBits,
|
||||
ulong CollisionMaskBits,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
uint IsStatic,
|
||||
uint IsKinematic,
|
||||
uint IsBullet,
|
||||
uint ParticipatesInFields,
|
||||
int CollisionGroupIndex);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DRadialField(
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float Strength,
|
||||
float Radius);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DBodyOutput(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DContactOutput(
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ,
|
||||
float Penetration,
|
||||
float RelativeSpeed);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DContactEventOutput(
|
||||
int Kind,
|
||||
uint HasDetails,
|
||||
uint ContactId0,
|
||||
uint ContactId1,
|
||||
uint ContactId2,
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ,
|
||||
float Penetration,
|
||||
float RelativeSpeed);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DCastOutput(
|
||||
int Hit,
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DOverlapOutput(
|
||||
int Hit,
|
||||
float Distance,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
namespace Ymir.Box3D;
|
||||
|
||||
internal readonly record struct Box3DSphereCastHit(
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ);
|
||||
|
||||
internal readonly record struct Box3DSphereOverlapHit(float Distance, float NormalX, float NormalZ);
|
||||
|
||||
internal static class Box3DQueries
|
||||
{
|
||||
internal static Box3DSphereOverlapHit? OverlapSpheres(
|
||||
float queryX,
|
||||
float queryZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius)
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
var output = Box3DNative.ymir_box3d_overlap_spheres(
|
||||
queryX,
|
||||
queryZ,
|
||||
queryRadius,
|
||||
bodyX,
|
||||
bodyZ,
|
||||
bodyRadius);
|
||||
return output.Hit == 0
|
||||
? null
|
||||
: new Box3DSphereOverlapHit(output.Distance, output.NormalX, output.NormalZ);
|
||||
}
|
||||
|
||||
internal static Box3DSphereCastHit? CastSphere(
|
||||
float originX,
|
||||
float originZ,
|
||||
float translationX,
|
||||
float translationZ,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyZ,
|
||||
float bodyRadius)
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
var output = Box3DNative.ymir_box3d_cast_sphere(
|
||||
originX,
|
||||
originZ,
|
||||
translationX,
|
||||
translationZ,
|
||||
queryRadius,
|
||||
bodyX,
|
||||
bodyZ,
|
||||
bodyRadius,
|
||||
canEncroach: 0);
|
||||
return output.Hit == 0
|
||||
? null
|
||||
: new Box3DSphereCastHit(
|
||||
output.Fraction,
|
||||
output.PointX,
|
||||
output.PointZ,
|
||||
output.NormalX,
|
||||
output.NormalZ);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
namespace Ymir.Box3D;
|
||||
|
||||
public static class Box3DRuntime
|
||||
{
|
||||
public const string NativeBuildId =
|
||||
"box3d-8441b4a06d6d09dcfb0b0f704df4d847d1437b92-abi5-f32";
|
||||
|
||||
public static string ValidatedBuildId
|
||||
{
|
||||
get
|
||||
{
|
||||
Box3DSession.EnsureCompatibleNativeLibrary();
|
||||
return NativeBuildId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,411 +0,0 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ymir.Box3D;
|
||||
|
||||
internal readonly record struct Box3DBody(
|
||||
ulong StableId,
|
||||
ulong CollisionCategoryBits,
|
||||
ulong CollisionMaskBits,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
bool IsStatic,
|
||||
bool IsKinematic,
|
||||
bool IsBullet,
|
||||
bool ParticipatesInFields,
|
||||
int CollisionGroupIndex);
|
||||
|
||||
internal readonly record struct Box3DField(float PositionX, float PositionZ, float Strength, float Radius);
|
||||
|
||||
internal readonly record struct Box3DBodyState(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionZ,
|
||||
float VelocityX,
|
||||
float VelocityZ,
|
||||
float DirectionX,
|
||||
float DirectionZ,
|
||||
float AngularVelocity);
|
||||
|
||||
internal readonly record struct Box3DContact(
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ,
|
||||
float Penetration,
|
||||
float RelativeSpeed);
|
||||
|
||||
internal enum Box3DContactKind
|
||||
{
|
||||
Begin = 1,
|
||||
Hit = 2,
|
||||
End = 3
|
||||
}
|
||||
|
||||
internal readonly record struct Box3DContactKey(uint Part0, uint Part1, uint Part2);
|
||||
|
||||
internal readonly record struct Box3DContactFact(
|
||||
Box3DContactKind Kind,
|
||||
Box3DContactKey ContactKey,
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
bool HasDetails,
|
||||
float PointX,
|
||||
float PointZ,
|
||||
float NormalX,
|
||||
float NormalZ,
|
||||
float Penetration,
|
||||
float RelativeSpeed);
|
||||
|
||||
internal sealed class Box3DSession : IDisposable
|
||||
{
|
||||
internal const uint AbiVersion = 5;
|
||||
internal const int DefaultSubstepCount = 4;
|
||||
|
||||
private readonly Box3DSessionHandle _handle;
|
||||
private bool _disposed;
|
||||
|
||||
internal Box3DSession()
|
||||
{
|
||||
EnsureCompatibleNativeLibrary();
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_create(out var value), "create session");
|
||||
if (value == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned a null Ymir session.");
|
||||
}
|
||||
|
||||
_handle = new Box3DSessionHandle(value);
|
||||
}
|
||||
|
||||
internal unsafe void SyncBodies(ReadOnlySpan<Box3DBody> bodies)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var native = new Box3DBodyInput[bodies.Length];
|
||||
for (var i = 0; i < bodies.Length; i++)
|
||||
{
|
||||
var body = bodies[i];
|
||||
native[i] = new Box3DBodyInput(
|
||||
body.StableId,
|
||||
body.CollisionCategoryBits,
|
||||
body.CollisionMaskBits,
|
||||
body.PositionX,
|
||||
body.PositionZ,
|
||||
body.VelocityX,
|
||||
body.VelocityZ,
|
||||
body.DirectionX,
|
||||
body.DirectionZ,
|
||||
body.AngularVelocity,
|
||||
body.Torque,
|
||||
body.Radius,
|
||||
body.Mass,
|
||||
body.Restitution,
|
||||
body.IsStatic ? 1u : 0u,
|
||||
body.IsKinematic ? 1u : 0u,
|
||||
body.IsBullet ? 1u : 0u,
|
||||
body.ParticipatesInFields ? 1u : 0u,
|
||||
body.CollisionGroupIndex);
|
||||
}
|
||||
|
||||
fixed (Box3DBodyInput* pointer = native)
|
||||
{
|
||||
var status = Box3DNative.ymir_box3d_session_sync_bodies(_handle, pointer, native.Length);
|
||||
if (status is Box3DStatus.OutOfMemory or Box3DStatus.InternalError)
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
ThrowIfFailed(status, "synchronize bodies");
|
||||
}
|
||||
}
|
||||
|
||||
internal unsafe void Spawn(Box3DBody body)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var native = ToNative(body);
|
||||
ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_spawn(_handle, &native), "spawn body");
|
||||
}
|
||||
|
||||
internal void Remove(ulong stableId)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_remove(_handle, stableId), "remove body");
|
||||
}
|
||||
|
||||
internal void Teleport(
|
||||
ulong stableId,
|
||||
float positionX,
|
||||
float positionZ,
|
||||
float directionX,
|
||||
float directionZ)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(
|
||||
Box3DNative.ymir_box3d_session_teleport(
|
||||
_handle, stableId, positionX, positionZ, directionX, directionZ),
|
||||
"teleport body");
|
||||
}
|
||||
|
||||
internal void SetVelocity(ulong stableId, float linearX, float linearZ, float angular)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(
|
||||
Box3DNative.ymir_box3d_session_set_velocity(_handle, stableId, linearX, linearZ, angular),
|
||||
"set body velocity");
|
||||
}
|
||||
|
||||
internal void Configure(
|
||||
ulong stableId,
|
||||
float radius,
|
||||
float mass,
|
||||
float restitution,
|
||||
bool isStatic,
|
||||
bool isKinematic)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(
|
||||
Box3DNative.ymir_box3d_session_configure(
|
||||
_handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u, isKinematic ? 1u : 0u),
|
||||
"configure body");
|
||||
}
|
||||
|
||||
internal void ApplyForce(ulong stableId, float x, float z)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_apply_force(_handle, stableId, x, z), "apply body force");
|
||||
}
|
||||
|
||||
internal void ApplyTorque(ulong stableId, float value)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_apply_torque(_handle, stableId, value), "apply body torque");
|
||||
}
|
||||
|
||||
internal unsafe void Step(float deltaTime, ReadOnlySpan<Box3DField> fields, int substepCount = DefaultSubstepCount)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (!float.IsFinite(deltaTime) || deltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(deltaTime), "Delta time must be finite and positive.");
|
||||
}
|
||||
|
||||
if (substepCount <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(substepCount), "Substep count must be positive.");
|
||||
}
|
||||
|
||||
var native = new Box3DRadialField[fields.Length];
|
||||
for (var i = 0; i < fields.Length; i++)
|
||||
{
|
||||
native[i] = new Box3DRadialField(fields[i].PositionX, fields[i].PositionZ, fields[i].Strength, fields[i].Radius);
|
||||
}
|
||||
|
||||
fixed (Box3DRadialField* pointer = native)
|
||||
{
|
||||
ThrowIfMutationFailed(
|
||||
Box3DNative.ymir_box3d_session_step(_handle, deltaTime, substepCount, pointer, native.Length),
|
||||
"step session");
|
||||
}
|
||||
}
|
||||
|
||||
internal unsafe Box3DBodyState[] CopyBodies()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var count = Box3DNative.ymir_box3d_session_get_body_count(_handle);
|
||||
if (count < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned an invalid body count.");
|
||||
}
|
||||
|
||||
var native = new Box3DBodyOutput[count];
|
||||
fixed (Box3DBodyOutput* pointer = native)
|
||||
{
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_copy_bodies(_handle, pointer, count, out var written), "copy bodies");
|
||||
if (written != count)
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D body snapshot changed during copy: expected {count}, received {written}.");
|
||||
}
|
||||
}
|
||||
|
||||
return native.Select(body => new Box3DBodyState(
|
||||
body.StableId,
|
||||
body.PositionX,
|
||||
body.PositionZ,
|
||||
body.VelocityX,
|
||||
body.VelocityZ,
|
||||
body.DirectionX,
|
||||
body.DirectionZ,
|
||||
body.AngularVelocity)).ToArray();
|
||||
}
|
||||
|
||||
internal unsafe Box3DContact[] CopyContacts()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var count = Box3DNative.ymir_box3d_session_get_contact_count(_handle);
|
||||
if (count < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned an invalid contact count.");
|
||||
}
|
||||
|
||||
var native = new Box3DContactOutput[count];
|
||||
fixed (Box3DContactOutput* pointer = native)
|
||||
{
|
||||
ThrowIfFailed(Box3DNative.ymir_box3d_session_copy_contacts(_handle, pointer, count, out var written), "copy contacts");
|
||||
if (written != count)
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D contact snapshot changed during copy: expected {count}, received {written}.");
|
||||
}
|
||||
}
|
||||
|
||||
return native.Select(contact => new Box3DContact(
|
||||
contact.StableIdA,
|
||||
contact.StableIdB,
|
||||
contact.PointX,
|
||||
contact.PointZ,
|
||||
contact.NormalX,
|
||||
contact.NormalZ,
|
||||
contact.Penetration,
|
||||
contact.RelativeSpeed)).ToArray();
|
||||
}
|
||||
|
||||
internal unsafe Box3DContactFact[] CopyContactEvents()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
var count = Box3DNative.ymir_box3d_session_get_contact_event_count(_handle);
|
||||
if (count < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Box3D returned an invalid contact event count.");
|
||||
}
|
||||
|
||||
var native = new Box3DContactEventOutput[count];
|
||||
fixed (Box3DContactEventOutput* pointer = native)
|
||||
{
|
||||
ThrowIfFailed(
|
||||
Box3DNative.ymir_box3d_session_copy_contact_events(_handle, pointer, count, out var written),
|
||||
"copy contact events");
|
||||
if (written != count)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Box3D contact event snapshot changed during copy: expected {count}, received {written}.");
|
||||
}
|
||||
}
|
||||
|
||||
return native.Select(contact => new Box3DContactFact(
|
||||
(Box3DContactKind)contact.Kind,
|
||||
new Box3DContactKey(contact.ContactId0, contact.ContactId1, contact.ContactId2),
|
||||
contact.StableIdA,
|
||||
contact.StableIdB,
|
||||
contact.HasDetails != 0,
|
||||
contact.PointX,
|
||||
contact.PointZ,
|
||||
contact.NormalX,
|
||||
contact.NormalZ,
|
||||
contact.Penetration,
|
||||
contact.RelativeSpeed)).ToArray();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_handle.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
internal static void EnsureCompatibleNativeLibrary()
|
||||
{
|
||||
var abi = Box3DNative.ymir_box3d_get_abi_version();
|
||||
if (abi != AbiVersion)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir Box3D ABI mismatch. Managed expects {AbiVersion}, native provides {abi}.");
|
||||
}
|
||||
|
||||
var buildId = Marshal.PtrToStringAnsi(Box3DNative.ymir_box3d_get_build_id());
|
||||
if (!string.Equals(buildId, Box3DRuntime.NativeBuildId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Ymir Box3D build mismatch. Managed expects '{Box3DRuntime.NativeBuildId}', native provides '{buildId ?? "<null>"}'.");
|
||||
}
|
||||
|
||||
ThrowIfFailed(
|
||||
Box3DNative.ymir_box3d_get_abi_layout(
|
||||
out var bodyInputSize,
|
||||
out var fieldInputSize,
|
||||
out var bodyOutputSize,
|
||||
out var contactOutputSize,
|
||||
out var contactEventOutputSize),
|
||||
"read native ABI layout");
|
||||
EnsureSize<Box3DBodyInput>(bodyInputSize);
|
||||
EnsureSize<Box3DRadialField>(fieldInputSize);
|
||||
EnsureSize<Box3DBodyOutput>(bodyOutputSize);
|
||||
EnsureSize<Box3DContactOutput>(contactOutputSize);
|
||||
EnsureSize<Box3DContactEventOutput>(contactEventOutputSize);
|
||||
|
||||
Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision);
|
||||
if (major != 0 || minor != 1 || revision != 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir requires Box3D 0.1.0, but loaded {major}.{minor}.{revision}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureSize<T>(uint nativeSize) where T : struct
|
||||
{
|
||||
var managedSize = checked((uint)Marshal.SizeOf<T>());
|
||||
if (managedSize != nativeSize)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Ymir Box3D ABI layout mismatch for {typeof(T).Name}. Managed expects {managedSize} bytes, native provides {nativeSize}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ThrowIfFailed(Box3DStatus status, string operation)
|
||||
{
|
||||
if (status != Box3DStatus.Ok)
|
||||
{
|
||||
throw new InvalidOperationException($"Ymir could not {operation}: native Box3D status {status}.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfMutationFailed(Box3DStatus status, string operation)
|
||||
{
|
||||
if (status is Box3DStatus.OutOfMemory or Box3DStatus.InternalError)
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
ThrowIfFailed(status, operation);
|
||||
}
|
||||
|
||||
private static Box3DBodyInput ToNative(Box3DBody body) => new(
|
||||
body.StableId,
|
||||
body.CollisionCategoryBits,
|
||||
body.CollisionMaskBits,
|
||||
body.PositionX,
|
||||
body.PositionZ,
|
||||
body.VelocityX,
|
||||
body.VelocityZ,
|
||||
body.DirectionX,
|
||||
body.DirectionZ,
|
||||
body.AngularVelocity,
|
||||
body.Torque,
|
||||
body.Radius,
|
||||
body.Mass,
|
||||
body.Restitution,
|
||||
body.IsStatic ? 1u : 0u,
|
||||
body.IsKinematic ? 1u : 0u,
|
||||
body.IsBullet ? 1u : 0u,
|
||||
body.ParticipatesInFields ? 1u : 0u,
|
||||
body.CollisionGroupIndex);
|
||||
|
||||
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,3 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Ymir.Core")]
|
||||
[assembly: InternalsVisibleTo("Ymir.Box3D.Soa.Tests")]
|
||||
[assembly: InternalsVisibleTo("Lodur.Body.Ymir")]
|
||||
[assembly: InternalsVisibleTo("Lodur.Tests")]
|
||||
|
|
|
|||
|
|
@ -1,13 +1,7 @@
|
|||
# GameCult.Ymir.Box3D
|
||||
|
||||
This is Ymir's private managed/native boundary for pinned Box3D v0.1.0. It is
|
||||
installed transitively by Ymir; products and clients should reference Ymir's
|
||||
typed session contracts instead of this package.
|
||||
Managed and native 3D SoA rigid-body + PBD/SPH particle boundary around pinned Box3D (`extern/box3d`), consumed by `Lodur` and `BadDaySimulator`.
|
||||
|
||||
The package includes the compiled native facade under `runtimes/<rid>/native`.
|
||||
Package consumers do not need CMake, a C compiler, or the Box3D submodule.
|
||||
Missing or ABI-incompatible native assets fail closed when Ymir opens a physics
|
||||
session.
|
||||
The NuGet package bundles the compiled native library under `runtimes/<rid>/native`, so package consumers do not need CMake, a C compiler, or the Box3D submodule. Source builds use CMake to compile `native/Ymir.Box3D` (`ymir_box3d_soa.c`, `ymir_particles.c`, and `extern/box3d`).
|
||||
|
||||
Source builds of Ymir use CMake to compile the pinned submodule. Box3D is MIT
|
||||
licensed; its license is included in the package.
|
||||
Box3D is MIT licensed; its license is included in the package.
|
||||
|
|
|
|||
|
|
@ -13,31 +13,34 @@
|
|||
<Authors>GameCult</Authors>
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
<YmirNativeConfiguration Condition="'$(YmirNativeConfiguration)' == ''">$(Configuration)</YmirNativeConfiguration>
|
||||
<OutputPath Condition="'$(YmirNativeConfiguration)' != '$(Configuration)'">bin\$(Configuration)-native-$(YmirNativeConfiguration)\</OutputPath>
|
||||
<IntermediateOutputPath Condition="'$(YmirNativeConfiguration)' != '$(Configuration)'">obj\$(Configuration)-native-$(YmirNativeConfiguration)\</IntermediateOutputPath>
|
||||
<NativeSourceDir>$(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D</NativeSourceDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\production\$(Configuration)</NativeBuildDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\production\$(YmirNativeConfiguration)</NativeBuildDir>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == '' and '$(OS)' == 'Windows_NT' and Exists('C:\Program Files\CMake\bin\cmake.exe')">C:\Program Files\CMake\bin\cmake.exe</CMakeExe>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == ''">cmake</CMakeExe>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(NativeBuildDir)\bin\$(Configuration)\ymir_box3d.dll"
|
||||
<None Include="$(NativeBuildDir)\bin\$(YmirNativeConfiguration)\ymir_box3d.dll"
|
||||
Link="ymir_box3d.dll"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
CopyToOutputDirectory="Always"
|
||||
CopyToPublishDirectory="Always"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/win-x64/native/ymir_box3d.dll"
|
||||
Condition="'$(OS)' == 'Windows_NT'" />
|
||||
<None Include="$(NativeBuildDir)\bin\libymir_box3d.so"
|
||||
<None Include="$(NativeBuildDir)\bin\$(YmirNativeConfiguration)\libymir_box3d.so"
|
||||
Link="libymir_box3d.so"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
CopyToOutputDirectory="Always"
|
||||
CopyToPublishDirectory="Always"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/linux-x64/native/libymir_box3d.so"
|
||||
Condition="'$(OS)' != 'Windows_NT' and !$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<None Include="$(NativeBuildDir)\bin\libymir_box3d.dylib"
|
||||
<None Include="$(NativeBuildDir)\bin\$(YmirNativeConfiguration)\libymir_box3d.dylib"
|
||||
Link="libymir_box3d.dylib"
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
CopyToPublishDirectory="PreserveNewest"
|
||||
CopyToOutputDirectory="Always"
|
||||
CopyToPublishDirectory="Always"
|
||||
Pack="true"
|
||||
PackagePath="runtimes/osx-x64/native/libymir_box3d.dylib"
|
||||
Condition="$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
|
|
@ -51,8 +54,8 @@
|
|||
<Target Name="BuildYmirBox3DNative"
|
||||
BeforeTargets="PrepareForBuild;GetCopyToOutputDirectoryItems;GetCopyToPublishDirectoryItems"
|
||||
Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Exec Command=""$(CMakeExe)" -S "$(NativeSourceDir)" -B "$(NativeBuildDir)" -DBUILD_SHARED_LIBS=OFF" />
|
||||
<Exec Command=""$(CMakeExe)" --build "$(NativeBuildDir)" --config $(Configuration) --target ymir_box3d" />
|
||||
<Exec Command=""$(CMakeExe)" -S "$(NativeSourceDir)" -B "$(NativeBuildDir)" -DBUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=$(YmirNativeConfiguration)" />
|
||||
<Exec Command=""$(CMakeExe)" --build "$(NativeBuildDir)" --config $(YmirNativeConfiguration) --target ymir_box3d" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,85 +0,0 @@
|
|||
using CultMath;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public readonly record struct Vec2(float X, float Y)
|
||||
{
|
||||
public static Vec2 Zero => new(0.0f, 0.0f);
|
||||
|
||||
public float2 ToCultMath() => new(X, Y);
|
||||
|
||||
public static Vec2 FromCultMath(float2 value) => new(value.x, value.y);
|
||||
}
|
||||
|
||||
public sealed record PhysicsBody(
|
||||
string Id,
|
||||
Vec2 Position,
|
||||
Vec2 Velocity,
|
||||
float Radius,
|
||||
float Mass,
|
||||
bool IsStatic = false,
|
||||
float Restitution = 0.2f,
|
||||
Vec2? Direction = null,
|
||||
float AngularVelocity = 0.0f,
|
||||
float Torque = 0.0f,
|
||||
bool IsKinematic = false,
|
||||
bool IsBullet = false,
|
||||
bool ParticipatesInFields = true,
|
||||
ulong CollisionCategoryBits = 1UL,
|
||||
ulong CollisionMaskBits = ulong.MaxValue,
|
||||
int CollisionGroupIndex = 0);
|
||||
|
||||
public sealed record RadialField(
|
||||
string Id,
|
||||
Vec2 Position,
|
||||
float Strength,
|
||||
float Radius);
|
||||
|
||||
public sealed record YmirWorld(
|
||||
float Time,
|
||||
IReadOnlyList<PhysicsBody> Bodies,
|
||||
IReadOnlyList<RadialField> Fields);
|
||||
|
||||
public sealed record SimulationStepRequest(
|
||||
float DeltaTime,
|
||||
YmirWorld World);
|
||||
|
||||
public sealed record ContactEvent(
|
||||
string BodyA,
|
||||
string BodyB,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Penetration,
|
||||
float RelativeSpeed);
|
||||
|
||||
public sealed record SimulationStepResult(
|
||||
YmirWorld World,
|
||||
IReadOnlyList<ContactEvent> Contacts);
|
||||
|
||||
public sealed record CircleCastQueryRequest(
|
||||
Vec2 Origin,
|
||||
Vec2 Direction,
|
||||
float Distance,
|
||||
float Radius,
|
||||
IReadOnlyList<PhysicsBody> Bodies);
|
||||
|
||||
public sealed record CircleCastHit(
|
||||
string BodyId,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Distance);
|
||||
|
||||
public sealed record CircleCastQueryResult(IReadOnlyList<CircleCastHit> Hits);
|
||||
|
||||
public sealed record CircleOverlapQueryRequest(
|
||||
Vec2 Center,
|
||||
float Radius,
|
||||
IReadOnlyList<PhysicsBody> Bodies);
|
||||
|
||||
public sealed record CircleOverlapHit(
|
||||
string BodyId,
|
||||
Vec2 Point,
|
||||
Vec2 Normal,
|
||||
float Distance);
|
||||
|
||||
public sealed record CircleOverlapQueryResult(IReadOnlyList<CircleOverlapHit> Hits);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Ymir.Tests")]
|
||||
|
|
@ -1,239 +0,0 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public sealed record YmirSessionCreateRequest(
|
||||
string SessionId,
|
||||
IReadOnlyList<PhysicsBody> InitialBodies,
|
||||
float InitialTime = 0.0f);
|
||||
|
||||
public static class YmirSessionCheckpointContract
|
||||
{
|
||||
public const string FormatId = "gamecult.ymir.session_checkpoint.replay.v1";
|
||||
public const string JournalChunkFormatId = "gamecult.ymir.session_journal_chunk.v1";
|
||||
public const string ResumeDescriptorFormatId = "gamecult.ymir.session_resume.v1";
|
||||
public static string RuntimeFingerprint =>
|
||||
$"gamecult.ymir.replay.v1|{Box3DRuntime.ValidatedBuildId}";
|
||||
}
|
||||
|
||||
public sealed record YmirSessionJournalChunk(
|
||||
string FormatId,
|
||||
string RuntimeFingerprint,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long FirstEntryIndex,
|
||||
IReadOnlyList<YmirSessionJournalEntry> Entries);
|
||||
|
||||
public sealed record YmirSessionResumeDescriptor(
|
||||
string FormatId,
|
||||
string RuntimeFingerprint,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long Revision,
|
||||
long StepIndex,
|
||||
float Time,
|
||||
long NextBodyGeneration,
|
||||
IReadOnlyList<PhysicsBody> InitialBodies,
|
||||
float InitialTime,
|
||||
long JournalEntryCount,
|
||||
string JournalDigest,
|
||||
YmirWorld World,
|
||||
IReadOnlyList<YmirContactEpisodeCheckpoint> ActiveContactEpisodes);
|
||||
|
||||
public sealed record YmirSessionPersistenceCapture(
|
||||
YmirSessionJournalChunk? JournalChunk,
|
||||
YmirSessionResumeDescriptor ResumeDescriptor);
|
||||
|
||||
public sealed record YmirSessionCheckpoint(
|
||||
string FormatId,
|
||||
string RuntimeFingerprint,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long Revision,
|
||||
long StepIndex,
|
||||
float Time,
|
||||
long NextBodyGeneration,
|
||||
IReadOnlyList<PhysicsBody> InitialBodies,
|
||||
float InitialTime,
|
||||
IReadOnlyList<YmirSessionJournalEntry> Journal,
|
||||
string JournalDigest,
|
||||
YmirWorld World,
|
||||
IReadOnlyList<YmirContactEpisodeCheckpoint> ActiveContactEpisodes);
|
||||
|
||||
public sealed record YmirContactEpisodeCheckpoint(
|
||||
string BodyA,
|
||||
long BodyAGeneration,
|
||||
string BodyB,
|
||||
long BodyBGeneration,
|
||||
long StartStepIndex,
|
||||
long Ordinal);
|
||||
|
||||
public abstract record YmirSessionJournalEntry;
|
||||
|
||||
public sealed record YmirSpawnBodyJournalEntry(YmirSpawnBodyCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirRemoveBodyJournalEntry(YmirRemoveBodyCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirTeleportBodyJournalEntry(YmirTeleportBodyCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirSetBodyVelocityJournalEntry(YmirSetBodyVelocityCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirConfigureBodyJournalEntry(YmirConfigureBodyCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirApplyForceJournalEntry(YmirApplyForceCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirApplyTorqueJournalEntry(YmirApplyTorqueCommand Command) : YmirSessionJournalEntry;
|
||||
public sealed record YmirStepSessionJournalEntry(YmirStepSessionCommand Command) : YmirSessionJournalEntry;
|
||||
|
||||
public sealed record YmirCommandHeader(string CommandId, long ExpectedRevision);
|
||||
|
||||
public sealed record YmirSpawnBodyCommand(YmirCommandHeader Header, PhysicsBody Body);
|
||||
|
||||
public sealed record YmirRemoveBodyCommand(YmirCommandHeader Header, string BodyId);
|
||||
|
||||
public sealed record YmirTeleportBodyCommand(
|
||||
YmirCommandHeader Header,
|
||||
string BodyId,
|
||||
Vec2 Position,
|
||||
Vec2 Direction);
|
||||
|
||||
public sealed record YmirSetBodyVelocityCommand(
|
||||
YmirCommandHeader Header,
|
||||
string BodyId,
|
||||
Vec2 LinearVelocity,
|
||||
float AngularVelocity);
|
||||
|
||||
public sealed record YmirConfigureBodyCommand(
|
||||
YmirCommandHeader Header,
|
||||
string BodyId,
|
||||
float Radius,
|
||||
float Mass,
|
||||
bool IsStatic,
|
||||
float Restitution,
|
||||
bool IsKinematic = false);
|
||||
|
||||
public sealed record YmirApplyForceCommand(
|
||||
YmirCommandHeader Header,
|
||||
string BodyId,
|
||||
Vec2 Force);
|
||||
|
||||
public sealed record YmirApplyTorqueCommand(
|
||||
YmirCommandHeader Header,
|
||||
string BodyId,
|
||||
float Torque);
|
||||
|
||||
public sealed record YmirStepSessionCommand(
|
||||
YmirCommandHeader Header,
|
||||
float DeltaTime,
|
||||
IReadOnlyList<RadialField> Fields,
|
||||
int SubstepCount = 4);
|
||||
|
||||
public sealed record YmirDisposeSessionCommand(YmirCommandHeader Header);
|
||||
|
||||
public enum YmirCommandOutcome
|
||||
{
|
||||
Accepted,
|
||||
Rejected
|
||||
}
|
||||
|
||||
public enum YmirCommandError
|
||||
{
|
||||
None,
|
||||
StaleRevision,
|
||||
CommandIdConflict,
|
||||
DuplicateBody,
|
||||
UnknownBody,
|
||||
StaticBody,
|
||||
InvalidCommand,
|
||||
SessionDisposed,
|
||||
SessionFaulted
|
||||
}
|
||||
|
||||
public sealed record YmirCommandReceipt(
|
||||
string ReceiptId,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
string CommandId,
|
||||
string CommandKind,
|
||||
YmirCommandOutcome Outcome,
|
||||
YmirCommandError Error,
|
||||
long BeforeRevision,
|
||||
long AfterRevision,
|
||||
long ObservedStepIndex,
|
||||
IReadOnlyList<string> ProducedFactIds);
|
||||
|
||||
public enum YmirContactFactKind
|
||||
{
|
||||
Begin,
|
||||
Hit,
|
||||
End
|
||||
}
|
||||
|
||||
public sealed record YmirContactFact(
|
||||
string FactId,
|
||||
string ContactId,
|
||||
YmirContactFactKind Kind,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long StepIndex,
|
||||
string BodyA,
|
||||
long BodyAGeneration,
|
||||
string BodyB,
|
||||
long BodyBGeneration,
|
||||
Vec2? Point,
|
||||
Vec2? Normal,
|
||||
float? Penetration,
|
||||
float? RelativeSpeed);
|
||||
|
||||
public sealed record YmirSessionStepResult(
|
||||
YmirCommandReceipt Receipt,
|
||||
YmirWorld World,
|
||||
long Revision,
|
||||
long StepIndex,
|
||||
IReadOnlyList<YmirContactFact> ContactFacts);
|
||||
|
||||
public sealed record YmirSessionCircleCastQuery(
|
||||
string QueryId,
|
||||
long ExpectedRevision,
|
||||
Vec2 Origin,
|
||||
Vec2 Direction,
|
||||
float Distance,
|
||||
float Radius,
|
||||
IReadOnlyList<string> CandidateBodyIds);
|
||||
|
||||
public sealed record YmirSessionCircleOverlapQuery(
|
||||
string QueryId,
|
||||
long ExpectedRevision,
|
||||
Vec2 Center,
|
||||
float Radius,
|
||||
IReadOnlyList<string> CandidateBodyIds);
|
||||
|
||||
public enum YmirQueryError
|
||||
{
|
||||
None,
|
||||
StaleRevision,
|
||||
UnknownBody,
|
||||
InvalidQuery,
|
||||
SessionDisposed,
|
||||
SessionFaulted
|
||||
}
|
||||
|
||||
public sealed record YmirSessionCircleCastResult(
|
||||
string QueryId,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long ObservedRevision,
|
||||
long ObservedStepIndex,
|
||||
YmirQueryError Error,
|
||||
IReadOnlyList<CircleCastHit> Hits);
|
||||
|
||||
public sealed record YmirSessionCircleOverlapResult(
|
||||
string QueryId,
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long ObservedRevision,
|
||||
long ObservedStepIndex,
|
||||
YmirQueryError Error,
|
||||
IReadOnlyList<CircleOverlapHit> Hits);
|
||||
|
||||
public sealed record YmirSessionInfo(
|
||||
string SessionId,
|
||||
string SessionGeneration,
|
||||
long Revision,
|
||||
long StepIndex,
|
||||
bool IsDisposed,
|
||||
bool IsFaulted);
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Ymir.Box3D\Ymir.Box3D.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\packages\cultmath\src\CultMath\CultMath.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>Ymir.Core</RootNamespace>
|
||||
<AssemblyName>Ymir.Core</AssemblyName>
|
||||
<Description>GameCult retained physics session library and optional daemon contracts backed by pinned Box3D.</Description>
|
||||
<Authors>GameCult</Authors>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,116 +0,0 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public static class YmirQueries
|
||||
{
|
||||
public static CircleOverlapQueryResult OverlapCircle(CircleOverlapQueryRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Overlap radius must be finite and positive.");
|
||||
}
|
||||
if (!float.IsFinite(request.Center.X) || !float.IsFinite(request.Center.Y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Overlap center must be finite.");
|
||||
}
|
||||
|
||||
var hits = new List<CircleOverlapHit>();
|
||||
foreach (var body in request.Bodies)
|
||||
{
|
||||
ValidateQueryBody(body, request);
|
||||
var hit = Box3DQueries.OverlapSpheres(
|
||||
request.Center.X,
|
||||
request.Center.Y,
|
||||
request.Radius,
|
||||
body.Position.X,
|
||||
body.Position.Y,
|
||||
body.Radius);
|
||||
if (hit is not { } value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hits.Add(new CircleOverlapHit(
|
||||
body.Id,
|
||||
request.Center,
|
||||
new Vec2(value.NormalX, value.NormalZ),
|
||||
value.Distance));
|
||||
}
|
||||
|
||||
return new CircleOverlapQueryResult(hits
|
||||
.OrderBy(hit => hit.Distance)
|
||||
.ThenBy(hit => hit.BodyId, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
public static CircleCastQueryResult CastCircle(CircleCastQueryRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.Distance) || request.Distance < 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast distance must be finite and non-negative.");
|
||||
}
|
||||
if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast radius must be finite and positive.");
|
||||
}
|
||||
if (!float.IsFinite(request.Origin.X) || !float.IsFinite(request.Origin.Y))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast origin must be finite.");
|
||||
}
|
||||
|
||||
var directionLengthSquared = request.Direction.X * request.Direction.X + request.Direction.Y * request.Direction.Y;
|
||||
if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Cast direction must be finite and non-zero.");
|
||||
}
|
||||
|
||||
var inverseLength = 1.0f / MathF.Sqrt(directionLengthSquared);
|
||||
var translationX = request.Direction.X * inverseLength * request.Distance;
|
||||
var translationY = request.Direction.Y * inverseLength * request.Distance;
|
||||
var hits = new List<CircleCastHit>();
|
||||
foreach (var body in request.Bodies)
|
||||
{
|
||||
ValidateQueryBody(body, request);
|
||||
|
||||
var hit = Box3DQueries.CastSphere(
|
||||
request.Origin.X,
|
||||
request.Origin.Y,
|
||||
translationX,
|
||||
translationY,
|
||||
request.Radius,
|
||||
body.Position.X,
|
||||
body.Position.Y,
|
||||
body.Radius);
|
||||
if (hit is not { } value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hits.Add(new CircleCastHit(
|
||||
body.Id,
|
||||
new Vec2(value.PointX, value.PointZ),
|
||||
new Vec2(value.NormalX, value.NormalZ),
|
||||
value.Fraction * request.Distance));
|
||||
}
|
||||
|
||||
return new CircleCastQueryResult(hits
|
||||
.OrderBy(hit => hit.Distance)
|
||||
.ThenBy(hit => hit.BodyId, StringComparer.Ordinal)
|
||||
.ToArray());
|
||||
}
|
||||
|
||||
private static void ValidateQueryBody(PhysicsBody body, object request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(body.Id) ||
|
||||
!float.IsFinite(body.Position.X) ||
|
||||
!float.IsFinite(body.Position.Y) ||
|
||||
!float.IsFinite(body.Radius) ||
|
||||
body.Radius <= 0.0f)
|
||||
{
|
||||
throw new ArgumentException("Query bodies require stable ids and finite positive radii.", nameof(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,168 +0,0 @@
|
|||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
[CultDocument("gamecult.ymir.provider_advertisement", "gamecult.ymir.provider_advertisement.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirProviderAdvertisementDocument
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string ProviderId { get; set; } = "ymir.physics";
|
||||
|
||||
[Key(1)]
|
||||
public string Title { get; set; } = "Ymir Physics";
|
||||
|
||||
[Key(2)]
|
||||
public string Description { get; set; } = "GameCult Box3D retained-session library and optional physics-daemon surface.";
|
||||
|
||||
[Key(3)]
|
||||
public string[] Owns { get; set; } = [];
|
||||
|
||||
[Key(4)]
|
||||
public string[] DoesNotOwn { get; set; } = [];
|
||||
|
||||
[Key(5)]
|
||||
public YmirTransportLoweringDocument[] CommandLowerings { get; set; } = [];
|
||||
|
||||
[Key(6)]
|
||||
public string UpdatedAtUtc { get; set; } = "";
|
||||
}
|
||||
|
||||
[CultDocument("gamecult.ymir.operator_state", "gamecult.ymir.operator_state.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirOperatorStateDocument
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string ProviderId { get; set; } = "ymir.physics";
|
||||
|
||||
[Key(1)]
|
||||
public string Status { get; set; } = "box3d-cutover";
|
||||
|
||||
[Key(2)]
|
||||
public string StateOwner { get; set; } = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections";
|
||||
|
||||
[Key(3)]
|
||||
public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)";
|
||||
|
||||
[Key(4)]
|
||||
public string BatchKernel { get; set; } = "";
|
||||
|
||||
[Key(5)]
|
||||
public string Persistence { get; set; } = "Checksummed replay checkpoint v1; host-owned private journal persistence; world_state.v2 inspection snapshot";
|
||||
|
||||
[Key(6)]
|
||||
public string UpdatedAtUtc { get; set; } = "";
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class YmirTransportLoweringDocument
|
||||
{
|
||||
[Key(0)]
|
||||
public string Label { get; set; } = "";
|
||||
|
||||
[Key(1)]
|
||||
public string Method { get; set; } = "POST";
|
||||
|
||||
[Key(2)]
|
||||
public string Path { get; set; } = "";
|
||||
|
||||
[Key(3)]
|
||||
public string Purpose { get; set; } = "";
|
||||
}
|
||||
|
||||
public static class YmirServicePublication
|
||||
{
|
||||
public static YmirProviderAdvertisementDocument ProviderAdvertisement(DateTimeOffset now) => new()
|
||||
{
|
||||
ProviderId = "ymir.physics",
|
||||
Title = "Ymir Physics",
|
||||
Description = "GameCult Box3D retained-session library and optional physics-daemon surface.",
|
||||
Owns =
|
||||
[
|
||||
"Box3D-only isolated snapshot stepping",
|
||||
"public in-process retained sessions with explicit mutation receipts",
|
||||
"typed Begin, Hit, and End contact facts for retained steps",
|
||||
"stable GameCult id to transient Box3D handle projection",
|
||||
"Box3D-backed circle overlap and cast queries over submitted bodies",
|
||||
"deterministic result ordering",
|
||||
"checksummed replay checkpoint reconstruction bound to the pinned native build",
|
||||
"CultCache world snapshot v2 with explicit v1/v0 read migration"
|
||||
],
|
||||
DoesNotOwn =
|
||||
[
|
||||
"daemon-owned named session registry or CultMesh command lowering yet",
|
||||
"host-owned durable journal storage or atomic frame persistence",
|
||||
"physics algorithm invention",
|
||||
"Box3D solver and collision semantics",
|
||||
"CultMesh provider sessions or discovery during cutover",
|
||||
"Unity scene truth",
|
||||
"rendering",
|
||||
"gameplay damage policy",
|
||||
"editor authoring truth"
|
||||
],
|
||||
CommandLowerings = [],
|
||||
UpdatedAtUtc = FormatUtc(now)
|
||||
};
|
||||
|
||||
public static YmirOperatorStateDocument OperatorState(DateTimeOffset now) => new()
|
||||
{
|
||||
ProviderId = "ymir.physics",
|
||||
Status = "box3d-retained-session",
|
||||
StateOwner = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections",
|
||||
NumericSubstrate = "Box3D v0.1.0 (C17)",
|
||||
BatchKernel = "Box3D native solver; Ymir does not own physics algorithms",
|
||||
Persistence = "Checksummed replay checkpoint v1; host-owned private journal persistence; world_state.v2 inspection snapshot",
|
||||
UpdatedAtUtc = FormatUtc(now)
|
||||
};
|
||||
|
||||
private static string FormatUtc(DateTimeOffset value) => value.UtcDateTime.ToString("O");
|
||||
}
|
||||
|
||||
public static class YmirServicePublicationStore
|
||||
{
|
||||
public static async Task RegenerateDerivedStoreAsync(string path, DateTimeOffset now)
|
||||
{
|
||||
DeleteDerivedStore(path);
|
||||
await PublishAsync(path, now).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async Task PublishAsync(string path, DateTimeOffset now)
|
||||
{
|
||||
var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions
|
||||
{
|
||||
UseDirectoryStore = true,
|
||||
FlushOnDispose = true,
|
||||
StoreFlushOnDispose = true
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
using (cache)
|
||||
{
|
||||
var operatorState = YmirServicePublication.OperatorState(now);
|
||||
await cache.UpsertAsync(
|
||||
YmirServicePublication.ProviderAdvertisement(now),
|
||||
new CultRecordHandle<YmirProviderAdvertisementDocument>(new CultRecordKey("ymir:provider:ymir.physics")))
|
||||
.ConfigureAwait(false);
|
||||
await cache.UpsertAsync(
|
||||
operatorState,
|
||||
new CultRecordHandle<YmirOperatorStateDocument>(new CultRecordKey("ymir:operator:ymir.physics")))
|
||||
.ConfigureAwait(false);
|
||||
await cache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void DeleteDerivedStore(string path)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
|
||||
var recordsPath = DirectoryMessagePackBackingStore.DefaultRecordDirectoryPath(path);
|
||||
if (Directory.Exists(recordsPath))
|
||||
Directory.Delete(recordsPath, recursive: true);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,447 +0,0 @@
|
|||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public static class YmirSessionCheckpointCodec
|
||||
{
|
||||
private const uint Magic = 0x43534D59; // YMSC
|
||||
private const uint JournalMagic = 0x4A534D59; // YMSJ
|
||||
private const uint ResumeMagic = 0x52534D59; // YMSR
|
||||
private const int Version = 1;
|
||||
private const int MaximumPayloadBytes = 256 * 1024 * 1024;
|
||||
private const int MaximumCollectionCount = 4 * 1024 * 1024;
|
||||
private const int MaximumStringBytes = 1024 * 1024;
|
||||
private const int ChecksumBytes = 32;
|
||||
|
||||
public static byte[] Encode(YmirSessionCheckpoint checkpoint)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checkpoint);
|
||||
using var stream = new MemoryStream();
|
||||
using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true);
|
||||
writer.Write(Magic);
|
||||
writer.Write(Version);
|
||||
WriteString(writer, checkpoint.FormatId);
|
||||
WriteString(writer, checkpoint.RuntimeFingerprint);
|
||||
WriteString(writer, checkpoint.SessionId);
|
||||
WriteString(writer, checkpoint.SessionGeneration);
|
||||
writer.Write(checkpoint.Revision);
|
||||
writer.Write(checkpoint.StepIndex);
|
||||
writer.Write(checkpoint.Time);
|
||||
writer.Write(checkpoint.NextBodyGeneration);
|
||||
WriteBodies(writer, checkpoint.InitialBodies);
|
||||
writer.Write(checkpoint.InitialTime);
|
||||
WriteJournal(writer, checkpoint.Journal);
|
||||
WriteString(writer, checkpoint.JournalDigest);
|
||||
WriteWorld(writer, checkpoint.World);
|
||||
WriteEpisodes(writer, checkpoint.ActiveContactEpisodes);
|
||||
writer.Flush();
|
||||
if (stream.Length > MaximumPayloadBytes - ChecksumBytes)
|
||||
throw new InvalidOperationException("Ymir checkpoint exceeds the supported payload size.");
|
||||
var content = stream.ToArray();
|
||||
var checksum = SHA256.HashData(content);
|
||||
return [.. content, .. checksum];
|
||||
}
|
||||
|
||||
public static YmirSessionCheckpoint Decode(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
var content = VerifiedContent(payload);
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(content, writable: false);
|
||||
using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
|
||||
if (reader.ReadUInt32() != Magic || reader.ReadInt32() != Version)
|
||||
throw new InvalidDataException("Ymir checkpoint codec header is incompatible.");
|
||||
var checkpoint = new YmirSessionCheckpoint(
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
reader.ReadInt64(),
|
||||
reader.ReadInt64(),
|
||||
reader.ReadSingle(),
|
||||
reader.ReadInt64(),
|
||||
ReadBodies(reader),
|
||||
reader.ReadSingle(),
|
||||
ReadJournal(reader),
|
||||
ReadString(reader),
|
||||
ReadWorld(reader),
|
||||
ReadEpisodes(reader));
|
||||
if (stream.Position != stream.Length)
|
||||
throw new InvalidDataException("Ymir checkpoint contains trailing data.");
|
||||
return checkpoint;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception error) when (error is EndOfStreamException or IOException or ArgumentException or OverflowException)
|
||||
{
|
||||
throw new InvalidDataException("Ymir checkpoint payload is corrupt.", error);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] Encode(YmirSessionJournalChunk chunk)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(chunk);
|
||||
return EncodeChecksummed(writer =>
|
||||
{
|
||||
writer.Write(JournalMagic);
|
||||
writer.Write(Version);
|
||||
WriteString(writer, chunk.FormatId);
|
||||
WriteString(writer, chunk.RuntimeFingerprint);
|
||||
WriteString(writer, chunk.SessionId);
|
||||
WriteString(writer, chunk.SessionGeneration);
|
||||
writer.Write(chunk.FirstEntryIndex);
|
||||
WriteJournal(writer, chunk.Entries);
|
||||
});
|
||||
}
|
||||
|
||||
public static YmirSessionJournalChunk DecodeJournalChunk(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
var content = VerifiedContent(payload);
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(content, writable: false);
|
||||
using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
|
||||
if (reader.ReadUInt32() != JournalMagic || reader.ReadInt32() != Version)
|
||||
throw new InvalidDataException("Ymir journal chunk codec header is incompatible.");
|
||||
var chunk = new YmirSessionJournalChunk(
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
reader.ReadInt64(),
|
||||
ReadJournal(reader));
|
||||
if (stream.Position != stream.Length)
|
||||
throw new InvalidDataException("Ymir journal chunk contains trailing data.");
|
||||
return chunk;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception error) when (error is EndOfStreamException or IOException or ArgumentException or OverflowException)
|
||||
{
|
||||
throw new InvalidDataException("Ymir journal chunk payload is corrupt.", error);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] Encode(YmirSessionResumeDescriptor descriptor)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
return EncodeChecksummed(writer =>
|
||||
{
|
||||
writer.Write(ResumeMagic);
|
||||
writer.Write(Version);
|
||||
WriteString(writer, descriptor.FormatId);
|
||||
WriteString(writer, descriptor.RuntimeFingerprint);
|
||||
WriteString(writer, descriptor.SessionId);
|
||||
WriteString(writer, descriptor.SessionGeneration);
|
||||
writer.Write(descriptor.Revision);
|
||||
writer.Write(descriptor.StepIndex);
|
||||
writer.Write(descriptor.Time);
|
||||
writer.Write(descriptor.NextBodyGeneration);
|
||||
WriteBodies(writer, descriptor.InitialBodies);
|
||||
writer.Write(descriptor.InitialTime);
|
||||
writer.Write(descriptor.JournalEntryCount);
|
||||
WriteString(writer, descriptor.JournalDigest);
|
||||
WriteWorld(writer, descriptor.World);
|
||||
WriteEpisodes(writer, descriptor.ActiveContactEpisodes);
|
||||
});
|
||||
}
|
||||
|
||||
public static YmirSessionResumeDescriptor DecodeResumeDescriptor(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
var content = VerifiedContent(payload);
|
||||
try
|
||||
{
|
||||
using var stream = new MemoryStream(content, writable: false);
|
||||
using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
|
||||
if (reader.ReadUInt32() != ResumeMagic || reader.ReadInt32() != Version)
|
||||
throw new InvalidDataException("Ymir resume descriptor codec header is incompatible.");
|
||||
var descriptor = new YmirSessionResumeDescriptor(
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
ReadString(reader),
|
||||
reader.ReadInt64(),
|
||||
reader.ReadInt64(),
|
||||
reader.ReadSingle(),
|
||||
reader.ReadInt64(),
|
||||
ReadBodies(reader),
|
||||
reader.ReadSingle(),
|
||||
reader.ReadInt64(),
|
||||
ReadString(reader),
|
||||
ReadWorld(reader),
|
||||
ReadEpisodes(reader));
|
||||
if (stream.Position != stream.Length)
|
||||
throw new InvalidDataException("Ymir resume descriptor contains trailing data.");
|
||||
return descriptor;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception error) when (error is EndOfStreamException or IOException or ArgumentException or OverflowException)
|
||||
{
|
||||
throw new InvalidDataException("Ymir resume descriptor payload is corrupt.", error);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] EncodeChecksummed(Action<BinaryWriter> write)
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true))
|
||||
{
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
}
|
||||
if (stream.Length > MaximumPayloadBytes - ChecksumBytes)
|
||||
throw new InvalidOperationException("Ymir persistence payload exceeds the supported size.");
|
||||
var content = stream.ToArray();
|
||||
return [.. content, .. SHA256.HashData(content)];
|
||||
}
|
||||
|
||||
private static byte[] VerifiedContent(ReadOnlySpan<byte> payload)
|
||||
{
|
||||
if (payload.Length <= ChecksumBytes || payload.Length > MaximumPayloadBytes)
|
||||
throw new InvalidDataException("Ymir persistence payload size is invalid.");
|
||||
var content = payload[..^ChecksumBytes];
|
||||
var expectedChecksum = payload[^ChecksumBytes..];
|
||||
Span<byte> actualChecksum = stackalloc byte[ChecksumBytes];
|
||||
SHA256.HashData(content, actualChecksum);
|
||||
if (!CryptographicOperations.FixedTimeEquals(actualChecksum, expectedChecksum))
|
||||
throw new InvalidDataException("Ymir persistence payload checksum is invalid.");
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private static void WriteJournal(BinaryWriter writer, IReadOnlyList<YmirSessionJournalEntry> entries)
|
||||
{
|
||||
WriteCount(writer, entries?.Count ?? -1);
|
||||
foreach (var entry in entries!)
|
||||
{
|
||||
switch (entry)
|
||||
{
|
||||
case YmirSpawnBodyJournalEntry value:
|
||||
writer.Write((byte)1); WriteHeader(writer, value.Command.Header); WriteBody(writer, value.Command.Body); break;
|
||||
case YmirRemoveBodyJournalEntry value:
|
||||
writer.Write((byte)2); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); break;
|
||||
case YmirTeleportBodyJournalEntry value:
|
||||
writer.Write((byte)3); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); WriteVec2(writer, value.Command.Position); WriteVec2(writer, value.Command.Direction); break;
|
||||
case YmirSetBodyVelocityJournalEntry value:
|
||||
writer.Write((byte)4); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); WriteVec2(writer, value.Command.LinearVelocity); writer.Write(value.Command.AngularVelocity); break;
|
||||
case YmirConfigureBodyJournalEntry value:
|
||||
writer.Write((byte)5); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); writer.Write(value.Command.Radius); writer.Write(value.Command.Mass); writer.Write(value.Command.IsStatic); writer.Write(value.Command.Restitution); writer.Write(value.Command.IsKinematic); break;
|
||||
case YmirApplyForceJournalEntry value:
|
||||
writer.Write((byte)6); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); WriteVec2(writer, value.Command.Force); break;
|
||||
case YmirApplyTorqueJournalEntry value:
|
||||
writer.Write((byte)7); WriteHeader(writer, value.Command.Header); WriteString(writer, value.Command.BodyId); writer.Write(value.Command.Torque); break;
|
||||
case YmirStepSessionJournalEntry value:
|
||||
writer.Write((byte)8); WriteHeader(writer, value.Command.Header); writer.Write(value.Command.DeltaTime); WriteFields(writer, value.Command.Fields); writer.Write(value.Command.SubstepCount); break;
|
||||
default:
|
||||
throw new InvalidOperationException($"Unknown Ymir checkpoint journal entry '{entry?.GetType().FullName ?? "<null>"}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static YmirSessionJournalEntry[] ReadJournal(BinaryReader reader)
|
||||
{
|
||||
var count = ReadCount(reader);
|
||||
var values = new YmirSessionJournalEntry[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
values[index] = reader.ReadByte() switch
|
||||
{
|
||||
1 => new YmirSpawnBodyJournalEntry(new YmirSpawnBodyCommand(ReadHeader(reader), ReadBody(reader)!)),
|
||||
2 => new YmirRemoveBodyJournalEntry(new YmirRemoveBodyCommand(ReadHeader(reader), ReadString(reader))),
|
||||
3 => new YmirTeleportBodyJournalEntry(new YmirTeleportBodyCommand(ReadHeader(reader), ReadString(reader), ReadVec2(reader), ReadVec2(reader))),
|
||||
4 => new YmirSetBodyVelocityJournalEntry(new YmirSetBodyVelocityCommand(ReadHeader(reader), ReadString(reader), ReadVec2(reader), reader.ReadSingle())),
|
||||
5 => new YmirConfigureBodyJournalEntry(new YmirConfigureBodyCommand(ReadHeader(reader), ReadString(reader), reader.ReadSingle(), reader.ReadSingle(), reader.ReadBoolean(), reader.ReadSingle(), reader.ReadBoolean())),
|
||||
6 => new YmirApplyForceJournalEntry(new YmirApplyForceCommand(ReadHeader(reader), ReadString(reader), ReadVec2(reader))),
|
||||
7 => new YmirApplyTorqueJournalEntry(new YmirApplyTorqueCommand(ReadHeader(reader), ReadString(reader), reader.ReadSingle())),
|
||||
8 => new YmirStepSessionJournalEntry(new YmirStepSessionCommand(ReadHeader(reader), reader.ReadSingle(), ReadFields(reader)!, reader.ReadInt32())),
|
||||
var kind => throw new InvalidDataException($"Unknown Ymir checkpoint journal kind {kind}.")
|
||||
};
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static void WriteWorld(BinaryWriter writer, YmirWorld world)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(world);
|
||||
writer.Write(world.Time);
|
||||
WriteBodies(writer, world.Bodies);
|
||||
WriteFields(writer, world.Fields);
|
||||
}
|
||||
|
||||
private static YmirWorld ReadWorld(BinaryReader reader)
|
||||
{
|
||||
var time = reader.ReadSingle();
|
||||
var bodies = ReadBodies(reader);
|
||||
var fields = ReadFields(reader) ?? throw new InvalidDataException("Ymir checkpoint world fields cannot be null.");
|
||||
return new YmirWorld(time, bodies, fields);
|
||||
}
|
||||
|
||||
private static void WriteBodies(BinaryWriter writer, IReadOnlyList<PhysicsBody> bodies)
|
||||
{
|
||||
WriteCount(writer, bodies?.Count ?? -1);
|
||||
foreach (var body in bodies!) WriteBody(writer, body);
|
||||
}
|
||||
|
||||
private static PhysicsBody[] ReadBodies(BinaryReader reader)
|
||||
{
|
||||
var count = ReadCount(reader);
|
||||
var values = new PhysicsBody[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
values[index] = ReadBody(reader) ?? throw new InvalidDataException("Ymir body list contains null.");
|
||||
return values;
|
||||
}
|
||||
|
||||
private static void WriteBody(BinaryWriter writer, PhysicsBody? body)
|
||||
{
|
||||
writer.Write(body != null);
|
||||
if (body == null) return;
|
||||
WriteString(writer, body.Id);
|
||||
WriteVec2(writer, body.Position);
|
||||
WriteVec2(writer, body.Velocity);
|
||||
writer.Write(body.Radius);
|
||||
writer.Write(body.Mass);
|
||||
writer.Write(body.IsStatic);
|
||||
writer.Write(body.Restitution);
|
||||
writer.Write(body.Direction.HasValue);
|
||||
if (body.Direction is { } direction) WriteVec2(writer, direction);
|
||||
writer.Write(body.AngularVelocity);
|
||||
writer.Write(body.Torque);
|
||||
writer.Write(body.IsKinematic);
|
||||
writer.Write(body.IsBullet);
|
||||
writer.Write(body.ParticipatesInFields);
|
||||
writer.Write(body.CollisionCategoryBits);
|
||||
writer.Write(body.CollisionMaskBits);
|
||||
writer.Write(body.CollisionGroupIndex);
|
||||
}
|
||||
|
||||
private static PhysicsBody? ReadBody(BinaryReader reader)
|
||||
{
|
||||
if (!reader.ReadBoolean()) return null;
|
||||
var id = ReadString(reader);
|
||||
var position = ReadVec2(reader);
|
||||
var velocity = ReadVec2(reader);
|
||||
var radius = reader.ReadSingle();
|
||||
var mass = reader.ReadSingle();
|
||||
var isStatic = reader.ReadBoolean();
|
||||
var restitution = reader.ReadSingle();
|
||||
var direction = reader.ReadBoolean() ? ReadVec2(reader) : (Vec2?)null;
|
||||
return new PhysicsBody(
|
||||
id, position, velocity, radius, mass, isStatic, restitution, direction,
|
||||
reader.ReadSingle(), reader.ReadSingle(), reader.ReadBoolean(), reader.ReadBoolean(),
|
||||
reader.ReadBoolean(), reader.ReadUInt64(), reader.ReadUInt64(), reader.ReadInt32());
|
||||
}
|
||||
|
||||
private static void WriteFields(BinaryWriter writer, IReadOnlyList<RadialField>? fields)
|
||||
{
|
||||
writer.Write(fields != null);
|
||||
if (fields == null) return;
|
||||
WriteCount(writer, fields.Count);
|
||||
foreach (var field in fields)
|
||||
{
|
||||
writer.Write(field != null);
|
||||
if (field == null) continue;
|
||||
WriteString(writer, field.Id);
|
||||
WriteVec2(writer, field.Position);
|
||||
writer.Write(field.Strength);
|
||||
writer.Write(field.Radius);
|
||||
}
|
||||
}
|
||||
|
||||
private static RadialField[]? ReadFields(BinaryReader reader)
|
||||
{
|
||||
if (!reader.ReadBoolean()) return null;
|
||||
var count = ReadCount(reader);
|
||||
var values = new RadialField[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
if (!reader.ReadBoolean())
|
||||
{
|
||||
values[index] = null!;
|
||||
continue;
|
||||
}
|
||||
values[index] = new RadialField(ReadString(reader), ReadVec2(reader), reader.ReadSingle(), reader.ReadSingle());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static void WriteEpisodes(BinaryWriter writer, IReadOnlyList<YmirContactEpisodeCheckpoint> episodes)
|
||||
{
|
||||
WriteCount(writer, episodes?.Count ?? -1);
|
||||
foreach (var value in episodes!)
|
||||
{
|
||||
WriteString(writer, value.BodyA); writer.Write(value.BodyAGeneration);
|
||||
WriteString(writer, value.BodyB); writer.Write(value.BodyBGeneration);
|
||||
writer.Write(value.StartStepIndex); writer.Write(value.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
private static YmirContactEpisodeCheckpoint[] ReadEpisodes(BinaryReader reader)
|
||||
{
|
||||
var count = ReadCount(reader);
|
||||
var values = new YmirContactEpisodeCheckpoint[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
values[index] = new YmirContactEpisodeCheckpoint(
|
||||
ReadString(reader), reader.ReadInt64(), ReadString(reader), reader.ReadInt64(),
|
||||
reader.ReadInt64(), reader.ReadInt64());
|
||||
return values;
|
||||
}
|
||||
|
||||
private static void WriteHeader(BinaryWriter writer, YmirCommandHeader header)
|
||||
{
|
||||
WriteString(writer, header.CommandId);
|
||||
writer.Write(header.ExpectedRevision);
|
||||
}
|
||||
|
||||
private static YmirCommandHeader ReadHeader(BinaryReader reader) => new(ReadString(reader), reader.ReadInt64());
|
||||
|
||||
private static void WriteVec2(BinaryWriter writer, Vec2 value)
|
||||
{
|
||||
writer.Write(value.X);
|
||||
writer.Write(value.Y);
|
||||
}
|
||||
|
||||
private static Vec2 ReadVec2(BinaryReader reader) => new(reader.ReadSingle(), reader.ReadSingle());
|
||||
|
||||
private static void WriteString(BinaryWriter writer, string value)
|
||||
{
|
||||
if (value == null) throw new InvalidOperationException("Ymir checkpoint strings cannot be null.");
|
||||
var bytes = Encoding.UTF8.GetBytes(value);
|
||||
if (bytes.Length > MaximumStringBytes)
|
||||
throw new InvalidOperationException("Ymir checkpoint string exceeds the supported size.");
|
||||
writer.Write(bytes.Length);
|
||||
writer.Write(bytes);
|
||||
}
|
||||
|
||||
private static string ReadString(BinaryReader reader)
|
||||
{
|
||||
var length = reader.ReadInt32();
|
||||
if (length < 0 || length > MaximumStringBytes)
|
||||
throw new InvalidDataException("Ymir checkpoint string length is invalid.");
|
||||
var bytes = reader.ReadBytes(length);
|
||||
if (bytes.Length != length)
|
||||
throw new EndOfStreamException();
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
private static void WriteCount(BinaryWriter writer, int count)
|
||||
{
|
||||
if (count < 0 || count > MaximumCollectionCount)
|
||||
throw new InvalidOperationException("Ymir checkpoint collection count is invalid.");
|
||||
writer.Write(count);
|
||||
}
|
||||
|
||||
private static int ReadCount(BinaryReader reader)
|
||||
{
|
||||
var count = reader.ReadInt32();
|
||||
return count is < 0 or > MaximumCollectionCount
|
||||
? throw new InvalidDataException("Ymir checkpoint collection count is invalid.")
|
||||
: count;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
namespace Ymir.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Compatibility façade for the snapshot-in/snapshot-out Ymir contract.
|
||||
/// Calls are isolated by design; retained world ownership is not inferred from snapshots.
|
||||
/// </summary>
|
||||
public sealed class YmirSimulator
|
||||
{
|
||||
public SimulationStepResult Step(SimulationStepRequest request)
|
||||
{
|
||||
using var session = new YmirWorldSession();
|
||||
return session.Step(request);
|
||||
}
|
||||
|
||||
public SoASimulationStepResult Step(SoASimulationStepRequest request)
|
||||
{
|
||||
using var session = new YmirWorldSession();
|
||||
return session.Step(request);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,293 +0,0 @@
|
|||
using CultMath;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
public sealed class YmirSoAWorld
|
||||
{
|
||||
public float Time { get; set; }
|
||||
public string[] BodyIds { get; set; } = [];
|
||||
public float[] PositionX { get; set; } = [];
|
||||
public float[] PositionY { get; set; } = [];
|
||||
public float[] VelocityX { get; set; } = [];
|
||||
public float[] VelocityY { get; set; } = [];
|
||||
public float[] DirectionX { get; set; } = [];
|
||||
public float[] DirectionY { get; set; } = [];
|
||||
public float[] AngularVelocity { get; set; } = [];
|
||||
public float[] Torque { get; set; } = [];
|
||||
public float[] Radius { get; set; } = [];
|
||||
public float[] Mass { get; set; } = [];
|
||||
public float[] DynamicMask { get; set; } = [];
|
||||
public float[] Restitution { get; set; } = [];
|
||||
public float[] KinematicMask { get; set; } = [];
|
||||
public float[] BulletMask { get; set; } = [];
|
||||
public float[] FieldParticipationMask { get; set; } = [];
|
||||
public ulong[] CollisionCategoryBits { get; set; } = [];
|
||||
public ulong[] CollisionMaskBits { get; set; } = [];
|
||||
public int[] CollisionGroupIndex { get; set; } = [];
|
||||
public string[] FieldIds { get; set; } = [];
|
||||
public float[] FieldPositionX { get; set; } = [];
|
||||
public float[] FieldPositionY { get; set; } = [];
|
||||
public float[] FieldStrength { get; set; } = [];
|
||||
public float[] FieldRadius { get; set; } = [];
|
||||
|
||||
public int BodyCount => BodyIds.Length;
|
||||
|
||||
public int FieldCount => FieldIds.Length;
|
||||
|
||||
public static YmirSoAWorld FromWorld(YmirWorld world)
|
||||
{
|
||||
var bodies = world.Bodies.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray();
|
||||
var fields = world.Fields.OrderBy(field => field.Id, StringComparer.Ordinal).ToArray();
|
||||
|
||||
return new YmirSoAWorld
|
||||
{
|
||||
Time = world.Time,
|
||||
BodyIds = bodies.Select(body => body.Id).ToArray(),
|
||||
PositionX = bodies.Select(body => body.Position.X).ToArray(),
|
||||
PositionY = bodies.Select(body => body.Position.Y).ToArray(),
|
||||
VelocityX = bodies.Select(body => body.Velocity.X).ToArray(),
|
||||
VelocityY = bodies.Select(body => body.Velocity.Y).ToArray(),
|
||||
DirectionX = bodies.Select(body => DirectionOrDefault(body.Direction).X).ToArray(),
|
||||
DirectionY = bodies.Select(body => DirectionOrDefault(body.Direction).Y).ToArray(),
|
||||
AngularVelocity = bodies.Select(body => body.AngularVelocity).ToArray(),
|
||||
Torque = bodies.Select(body => body.Torque).ToArray(),
|
||||
Radius = bodies.Select(body => body.Radius).ToArray(),
|
||||
Mass = bodies.Select(body => body.Mass).ToArray(),
|
||||
DynamicMask = bodies.Select(body => body.IsStatic ? 0.0f : 1.0f).ToArray(),
|
||||
Restitution = bodies.Select(body => body.Restitution).ToArray(),
|
||||
KinematicMask = bodies.Select(body => body.IsKinematic ? 1.0f : 0.0f).ToArray(),
|
||||
BulletMask = bodies.Select(body => body.IsBullet ? 1.0f : 0.0f).ToArray(),
|
||||
FieldParticipationMask = bodies.Select(body => body.ParticipatesInFields ? 1.0f : 0.0f).ToArray(),
|
||||
CollisionCategoryBits = bodies.Select(body => body.CollisionCategoryBits).ToArray(),
|
||||
CollisionMaskBits = bodies.Select(body => body.CollisionMaskBits).ToArray(),
|
||||
CollisionGroupIndex = bodies.Select(body => body.CollisionGroupIndex).ToArray(),
|
||||
FieldIds = fields.Select(field => field.Id).ToArray(),
|
||||
FieldPositionX = fields.Select(field => field.Position.X).ToArray(),
|
||||
FieldPositionY = fields.Select(field => field.Position.Y).ToArray(),
|
||||
FieldStrength = fields.Select(field => field.Strength).ToArray(),
|
||||
FieldRadius = fields.Select(field => field.Radius).ToArray()
|
||||
};
|
||||
}
|
||||
|
||||
public YmirWorld ToWorld() => new(
|
||||
Time,
|
||||
Enumerable.Range(0, BodyCount)
|
||||
.Select(i => new PhysicsBody(
|
||||
BodyIds[i],
|
||||
new Vec2(PositionX[i], PositionY[i]),
|
||||
new Vec2(VelocityX[i], VelocityY[i]),
|
||||
Radius[i],
|
||||
Mass[i],
|
||||
DynamicMask[i] <= 0.0f,
|
||||
Restitution[i],
|
||||
new Vec2(DirectionX[i], DirectionY[i]),
|
||||
AngularVelocity[i],
|
||||
Torque[i],
|
||||
KinematicMask[i] > 0.0f,
|
||||
BulletMask[i] > 0.0f,
|
||||
FieldParticipationMask[i] > 0.0f,
|
||||
CollisionCategoryBits[i],
|
||||
CollisionMaskBits[i],
|
||||
CollisionGroupIndex[i]))
|
||||
.ToArray(),
|
||||
Enumerable.Range(0, FieldCount)
|
||||
.Select(i => new RadialField(
|
||||
FieldIds[i],
|
||||
new Vec2(FieldPositionX[i], FieldPositionY[i]),
|
||||
FieldStrength[i],
|
||||
FieldRadius[i]))
|
||||
.ToArray());
|
||||
|
||||
public YmirSoAWorld Clone() => new()
|
||||
{
|
||||
Time = Time,
|
||||
BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(),
|
||||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(),
|
||||
DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone(),
|
||||
Torque = (float[])Torque.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
Restitution = (float[])Restitution.Clone(),
|
||||
KinematicMask = (float[])KinematicMask.Clone(),
|
||||
BulletMask = (float[])BulletMask.Clone(),
|
||||
FieldParticipationMask = (float[])FieldParticipationMask.Clone(),
|
||||
CollisionCategoryBits = (ulong[])CollisionCategoryBits.Clone(),
|
||||
CollisionMaskBits = (ulong[])CollisionMaskBits.Clone(),
|
||||
CollisionGroupIndex = (int[])CollisionGroupIndex.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(),
|
||||
FieldRadius = (float[])FieldRadius.Clone()
|
||||
};
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
ValidateBodyLengths();
|
||||
ValidateFieldLengths();
|
||||
|
||||
for (var i = 0; i < BodyCount; i++)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(BodyIds[i]))
|
||||
{
|
||||
throw new ArgumentException("Ymir bodies must have stable ids.");
|
||||
}
|
||||
|
||||
if (Radius[i] <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Radius), "Body radius must be positive.");
|
||||
}
|
||||
|
||||
if (DynamicMask[i] > 0.0f && Mass[i] <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Mass), "Dynamic body mass must be positive.");
|
||||
}
|
||||
|
||||
if (DynamicMask[i] <= 0.0f && KinematicMask[i] > 0.0f)
|
||||
{
|
||||
throw new ArgumentException("A body cannot be both static and kinematic.");
|
||||
}
|
||||
|
||||
if (CollisionCategoryBits[i] == 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(CollisionCategoryBits), "Collision category bits must be non-zero.");
|
||||
}
|
||||
|
||||
var directionLengthSquared = DirectionX[i] * DirectionX[i] + DirectionY[i] * DirectionY[i];
|
||||
if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(DirectionX), "Body direction must be finite and non-zero.");
|
||||
}
|
||||
|
||||
if (!float.IsFinite(AngularVelocity[i]) || !float.IsFinite(Torque[i]))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(AngularVelocity), "Body angular state must be finite.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public float2 PositionAt(int index) => new(PositionX[index], PositionY[index]);
|
||||
|
||||
public float2 VelocityAt(int index) => new(VelocityX[index], VelocityY[index]);
|
||||
|
||||
public void SetPosition(int index, float2 value)
|
||||
{
|
||||
PositionX[index] = value.x;
|
||||
PositionY[index] = value.y;
|
||||
}
|
||||
|
||||
public void SetVelocity(int index, float2 value)
|
||||
{
|
||||
VelocityX[index] = value.x;
|
||||
VelocityY[index] = value.y;
|
||||
}
|
||||
|
||||
private void ValidateBodyLengths()
|
||||
{
|
||||
var expected = BodyIds.Length;
|
||||
FillMissingAngularState(expected);
|
||||
FillMissingCollisionState(expected);
|
||||
foreach (var length in new[]
|
||||
{
|
||||
PositionX.Length,
|
||||
PositionY.Length,
|
||||
VelocityX.Length,
|
||||
VelocityY.Length,
|
||||
DirectionX.Length,
|
||||
DirectionY.Length,
|
||||
AngularVelocity.Length,
|
||||
Torque.Length,
|
||||
Radius.Length,
|
||||
Mass.Length,
|
||||
DynamicMask.Length,
|
||||
Restitution.Length,
|
||||
KinematicMask.Length,
|
||||
BulletMask.Length,
|
||||
FieldParticipationMask.Length,
|
||||
CollisionCategoryBits.Length,
|
||||
CollisionMaskBits.Length,
|
||||
CollisionGroupIndex.Length
|
||||
})
|
||||
{
|
||||
if (length != expected)
|
||||
{
|
||||
throw new ArgumentException("Ymir body SoA arrays must have equal length.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void FillMissingCollisionState(int expected)
|
||||
{
|
||||
if (KinematicMask.Length == 0 && expected > 0) KinematicMask = new float[expected];
|
||||
if (BulletMask.Length == 0 && expected > 0) BulletMask = new float[expected];
|
||||
if (FieldParticipationMask.Length == 0 && expected > 0)
|
||||
FieldParticipationMask = Enumerable.Repeat(1.0f, expected).ToArray();
|
||||
if (CollisionCategoryBits.Length == 0 && expected > 0)
|
||||
CollisionCategoryBits = Enumerable.Repeat(1UL, expected).ToArray();
|
||||
if (CollisionMaskBits.Length == 0 && expected > 0)
|
||||
CollisionMaskBits = Enumerable.Repeat(ulong.MaxValue, expected).ToArray();
|
||||
if (CollisionGroupIndex.Length == 0 && expected > 0) CollisionGroupIndex = new int[expected];
|
||||
}
|
||||
|
||||
private void FillMissingAngularState(int expected)
|
||||
{
|
||||
if (DirectionX.Length == 0 && expected > 0)
|
||||
{
|
||||
DirectionX = new float[expected];
|
||||
}
|
||||
|
||||
if (DirectionY.Length == 0 && expected > 0)
|
||||
{
|
||||
DirectionY = Enumerable.Repeat(1.0f, expected).ToArray();
|
||||
}
|
||||
|
||||
if (AngularVelocity.Length == 0 && expected > 0)
|
||||
{
|
||||
AngularVelocity = new float[expected];
|
||||
}
|
||||
|
||||
if (Torque.Length == 0 && expected > 0)
|
||||
{
|
||||
Torque = new float[expected];
|
||||
}
|
||||
}
|
||||
|
||||
private static Vec2 DirectionOrDefault(Vec2? direction)
|
||||
{
|
||||
if (direction is not { } value ||
|
||||
value.X * value.X + value.Y * value.Y <= 1.0e-8f)
|
||||
{
|
||||
return new Vec2(0.0f, 1.0f);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
private void ValidateFieldLengths()
|
||||
{
|
||||
var expected = FieldIds.Length;
|
||||
foreach (var length in new[]
|
||||
{
|
||||
FieldPositionX.Length,
|
||||
FieldPositionY.Length,
|
||||
FieldStrength.Length,
|
||||
FieldRadius.Length
|
||||
})
|
||||
{
|
||||
if (length != expected)
|
||||
{
|
||||
throw new ArgumentException("Ymir field SoA arrays must have equal length.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record SoASimulationStepRequest(float DeltaTime, YmirSoAWorld World);
|
||||
|
||||
public sealed record SoASimulationStepResult(YmirSoAWorld World, IReadOnlyList<ContactEvent> Contacts);
|
||||
|
|
@ -1,206 +0,0 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Owns one retained Box3D world and its stable GameCult identity projection.
|
||||
/// Callers own the session lifetime; body snapshots do not imply session identity.
|
||||
/// </summary>
|
||||
internal sealed class YmirWorldSession : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Box3DSession _session = new();
|
||||
private readonly Dictionary<string, ulong> _keysById = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<ulong, string> _idsByKey = new();
|
||||
private ulong _nextKey = 1;
|
||||
private bool _disposed;
|
||||
|
||||
public SimulationStepResult Step(SimulationStepRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var result = Step(new SoASimulationStepRequest(
|
||||
request.DeltaTime,
|
||||
YmirSoAWorld.FromWorld(request.World)));
|
||||
|
||||
return new SimulationStepResult(result.World.ToWorld(), result.Contacts);
|
||||
}
|
||||
|
||||
public SoASimulationStepResult Step(SoASimulationStepRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (!float.IsFinite(request.DeltaTime) || request.DeltaTime <= 0.0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be finite and positive.");
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var world = request.World.Clone();
|
||||
world.Validate();
|
||||
ValidateStableIds(world.BodyIds);
|
||||
|
||||
var indicesByKey = new Dictionary<ulong, int>(world.BodyCount);
|
||||
foreach (var id in world.BodyIds.OrderBy(id => id, StringComparer.Ordinal))
|
||||
{
|
||||
GetOrCreateKey(id);
|
||||
}
|
||||
|
||||
var bodies = new Box3DBody[world.BodyCount];
|
||||
for (var i = 0; i < world.BodyCount; i++)
|
||||
{
|
||||
var key = GetOrCreateKey(world.BodyIds[i]);
|
||||
indicesByKey.Add(key, i);
|
||||
bodies[i] = new Box3DBody(
|
||||
key,
|
||||
world.CollisionCategoryBits[i],
|
||||
world.CollisionMaskBits[i],
|
||||
world.PositionX[i],
|
||||
world.PositionY[i],
|
||||
world.VelocityX[i],
|
||||
world.VelocityY[i],
|
||||
world.DirectionX[i],
|
||||
world.DirectionY[i],
|
||||
world.AngularVelocity[i],
|
||||
world.Torque[i],
|
||||
world.Radius[i],
|
||||
world.Mass[i],
|
||||
world.Restitution[i],
|
||||
world.DynamicMask[i] <= 0.0f,
|
||||
world.KinematicMask[i] > 0.0f,
|
||||
world.BulletMask[i] > 0.0f,
|
||||
world.FieldParticipationMask[i] > 0.0f,
|
||||
world.CollisionGroupIndex[i]);
|
||||
}
|
||||
|
||||
Array.Sort(bodies, static (left, right) => left.StableId.CompareTo(right.StableId));
|
||||
|
||||
var fields = Enumerable.Range(0, world.FieldCount)
|
||||
.OrderBy(index => world.FieldIds[index], StringComparer.Ordinal)
|
||||
.Select(index => new Box3DField(
|
||||
world.FieldPositionX[index],
|
||||
world.FieldPositionY[index],
|
||||
world.FieldStrength[index],
|
||||
world.FieldRadius[index]))
|
||||
.ToArray();
|
||||
|
||||
_session.SyncBodies(bodies);
|
||||
_session.Step(request.DeltaTime, fields);
|
||||
|
||||
foreach (var body in _session.CopyBodies())
|
||||
{
|
||||
if (!indicesByKey.TryGetValue(body.StableId, out var index))
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D returned unknown stable body key {body.StableId}.");
|
||||
}
|
||||
|
||||
world.PositionX[index] = body.PositionX;
|
||||
world.PositionY[index] = body.PositionZ;
|
||||
world.VelocityX[index] = body.VelocityX;
|
||||
world.VelocityY[index] = body.VelocityZ;
|
||||
world.DirectionX[index] = body.DirectionX;
|
||||
world.DirectionY[index] = body.DirectionZ;
|
||||
world.AngularVelocity[index] = body.AngularVelocity;
|
||||
world.Torque[index] = 0.0f;
|
||||
}
|
||||
|
||||
var contacts = _session.CopyContacts()
|
||||
.Select(ProjectContact)
|
||||
.OrderBy(contact => contact.BodyA, StringComparer.Ordinal)
|
||||
.ThenBy(contact => contact.BodyB, StringComparer.Ordinal)
|
||||
.ThenBy(contact => contact.Point.X)
|
||||
.ThenBy(contact => contact.Point.Y)
|
||||
.ToArray();
|
||||
|
||||
PruneInactiveIds(world.BodyIds);
|
||||
|
||||
world.Time += request.DeltaTime;
|
||||
return new SoASimulationStepResult(world, contacts);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_session.Dispose();
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private ulong GetOrCreateKey(string id)
|
||||
{
|
||||
if (_keysById.TryGetValue(id, out var existing))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
|
||||
if (_nextKey == 0)
|
||||
{
|
||||
throw new InvalidOperationException("Ymir exhausted its stable native body key space.");
|
||||
}
|
||||
|
||||
var key = _nextKey++;
|
||||
_keysById.Add(id, key);
|
||||
_idsByKey.Add(key, id);
|
||||
return key;
|
||||
}
|
||||
|
||||
private ContactEvent ProjectContact(Box3DContact contact)
|
||||
{
|
||||
var bodyA = ResolveId(contact.StableIdA);
|
||||
var bodyB = ResolveId(contact.StableIdB);
|
||||
var normal = new Vec2(contact.NormalX, contact.NormalZ);
|
||||
if (StringComparer.Ordinal.Compare(bodyA, bodyB) > 0)
|
||||
{
|
||||
(bodyA, bodyB) = (bodyB, bodyA);
|
||||
normal = new Vec2(-normal.X, -normal.Y);
|
||||
}
|
||||
|
||||
return new ContactEvent(
|
||||
bodyA,
|
||||
bodyB,
|
||||
new Vec2(contact.PointX, contact.PointZ),
|
||||
normal,
|
||||
contact.Penetration,
|
||||
contact.RelativeSpeed);
|
||||
}
|
||||
|
||||
private string ResolveId(ulong key)
|
||||
{
|
||||
if (!_idsByKey.TryGetValue(key, out var id))
|
||||
{
|
||||
throw new InvalidOperationException($"Box3D returned unknown stable body key {key}.");
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private void PruneInactiveIds(IReadOnlyList<string> activeIds)
|
||||
{
|
||||
var active = activeIds.ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var id in _keysById.Keys.Where(id => !active.Contains(id)).ToArray())
|
||||
{
|
||||
var key = _keysById[id];
|
||||
_keysById.Remove(id);
|
||||
_idsByKey.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateStableIds(IReadOnlyList<string> bodyIds)
|
||||
{
|
||||
var unique = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var id in bodyIds)
|
||||
{
|
||||
if (!unique.Add(id))
|
||||
{
|
||||
throw new ArgumentException($"Ymir body id '{id}' occurs more than once.", nameof(bodyIds));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,273 +0,0 @@
|
|||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
|
||||
namespace Ymir.Core;
|
||||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v0")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocumentV0
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string WorldId { get; set; } = "default";
|
||||
|
||||
[Key(1)]
|
||||
public float Time { get; set; }
|
||||
|
||||
[Key(2)]
|
||||
public string[] BodyIds { get; set; } = [];
|
||||
|
||||
[Key(3)]
|
||||
public float[] PositionX { get; set; } = [];
|
||||
|
||||
[Key(4)]
|
||||
public float[] PositionY { get; set; } = [];
|
||||
|
||||
[Key(5)]
|
||||
public float[] VelocityX { get; set; } = [];
|
||||
|
||||
[Key(6)]
|
||||
public float[] VelocityY { get; set; } = [];
|
||||
|
||||
[Key(7)]
|
||||
public float[] Radius { get; set; } = [];
|
||||
|
||||
[Key(8)]
|
||||
public float[] Mass { get; set; } = [];
|
||||
|
||||
[Key(9)]
|
||||
public float[] DynamicMask { get; set; } = [];
|
||||
|
||||
[Key(10)]
|
||||
public float[] Restitution { get; set; } = [];
|
||||
|
||||
[Key(11)]
|
||||
public string[] FieldIds { get; set; } = [];
|
||||
|
||||
[Key(12)]
|
||||
public float[] FieldPositionX { get; set; } = [];
|
||||
|
||||
[Key(13)]
|
||||
public float[] FieldPositionY { get; set; } = [];
|
||||
|
||||
[Key(14)]
|
||||
public float[] FieldStrength { get; set; } = [];
|
||||
|
||||
[Key(15)]
|
||||
public float[] FieldRadius { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocumentV0 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId,
|
||||
Time = world.Time,
|
||||
BodyIds = (string[])world.BodyIds.Clone(),
|
||||
PositionX = (float[])world.PositionX.Clone(),
|
||||
PositionY = (float[])world.PositionY.Clone(),
|
||||
VelocityX = (float[])world.VelocityX.Clone(),
|
||||
VelocityY = (float[])world.VelocityY.Clone(),
|
||||
Radius = (float[])world.Radius.Clone(),
|
||||
Mass = (float[])world.Mass.Clone(),
|
||||
DynamicMask = (float[])world.DynamicMask.Clone(),
|
||||
Restitution = (float[])world.Restitution.Clone(),
|
||||
FieldIds = (string[])world.FieldIds.Clone(),
|
||||
FieldPositionX = (float[])world.FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])world.FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])world.FieldStrength.Clone(),
|
||||
FieldRadius = (float[])world.FieldRadius.Clone()
|
||||
};
|
||||
|
||||
public YmirSoAWorld ToSoA() => new()
|
||||
{
|
||||
Time = Time,
|
||||
BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(),
|
||||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
Restitution = (float[])Restitution.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(),
|
||||
FieldRadius = (float[])FieldRadius.Clone()
|
||||
};
|
||||
}
|
||||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocumentV1
|
||||
{
|
||||
[Key(0), CultName] public string WorldId { get; set; } = "default";
|
||||
[Key(1)] public float Time { get; set; }
|
||||
[Key(2)] public string[] BodyIds { get; set; } = [];
|
||||
[Key(3)] public float[] PositionX { get; set; } = [];
|
||||
[Key(4)] public float[] PositionY { get; set; } = [];
|
||||
[Key(5)] public float[] VelocityX { get; set; } = [];
|
||||
[Key(6)] public float[] VelocityY { get; set; } = [];
|
||||
[Key(7)] public float[] Radius { get; set; } = [];
|
||||
[Key(8)] public float[] Mass { get; set; } = [];
|
||||
[Key(9)] public float[] DynamicMask { get; set; } = [];
|
||||
[Key(10)] public float[] Restitution { get; set; } = [];
|
||||
[Key(11)] public string[] FieldIds { get; set; } = [];
|
||||
[Key(12)] public float[] FieldPositionX { get; set; } = [];
|
||||
[Key(13)] public float[] FieldPositionY { get; set; } = [];
|
||||
[Key(14)] public float[] FieldStrength { get; set; } = [];
|
||||
[Key(15)] public float[] FieldRadius { get; set; } = [];
|
||||
[Key(16)] public float[] DirectionX { get; set; } = [];
|
||||
[Key(17)] public float[] DirectionY { get; set; } = [];
|
||||
[Key(18)] public float[] AngularVelocity { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocumentV1 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId,
|
||||
Time = world.Time,
|
||||
BodyIds = (string[])world.BodyIds.Clone(),
|
||||
PositionX = (float[])world.PositionX.Clone(),
|
||||
PositionY = (float[])world.PositionY.Clone(),
|
||||
VelocityX = (float[])world.VelocityX.Clone(),
|
||||
VelocityY = (float[])world.VelocityY.Clone(),
|
||||
Radius = (float[])world.Radius.Clone(),
|
||||
Mass = (float[])world.Mass.Clone(),
|
||||
DynamicMask = (float[])world.DynamicMask.Clone(),
|
||||
Restitution = (float[])world.Restitution.Clone(),
|
||||
FieldIds = (string[])world.FieldIds.Clone(),
|
||||
FieldPositionX = (float[])world.FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])world.FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])world.FieldStrength.Clone(),
|
||||
FieldRadius = (float[])world.FieldRadius.Clone(),
|
||||
DirectionX = (float[])world.DirectionX.Clone(),
|
||||
DirectionY = (float[])world.DirectionY.Clone(),
|
||||
AngularVelocity = (float[])world.AngularVelocity.Clone()
|
||||
};
|
||||
|
||||
public YmirSoAWorld ToSoA() => new()
|
||||
{
|
||||
Time = Time,
|
||||
BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(),
|
||||
PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(),
|
||||
VelocityY = (float[])VelocityY.Clone(),
|
||||
Radius = (float[])Radius.Clone(),
|
||||
Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(),
|
||||
Restitution = (float[])Restitution.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(),
|
||||
FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(),
|
||||
FieldRadius = (float[])FieldRadius.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(),
|
||||
DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone()
|
||||
};
|
||||
}
|
||||
|
||||
[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v2")]
|
||||
[MessagePackObject]
|
||||
public sealed class YmirWorldStateDocumentV2
|
||||
{
|
||||
[Key(0), CultName] public string WorldId { get; set; } = "default";
|
||||
[Key(1)] public float Time { get; set; }
|
||||
[Key(2)] public string[] BodyIds { get; set; } = [];
|
||||
[Key(3)] public float[] PositionX { get; set; } = [];
|
||||
[Key(4)] public float[] PositionY { get; set; } = [];
|
||||
[Key(5)] public float[] VelocityX { get; set; } = [];
|
||||
[Key(6)] public float[] VelocityY { get; set; } = [];
|
||||
[Key(7)] public float[] Radius { get; set; } = [];
|
||||
[Key(8)] public float[] Mass { get; set; } = [];
|
||||
[Key(9)] public float[] DynamicMask { get; set; } = [];
|
||||
[Key(10)] public float[] Restitution { get; set; } = [];
|
||||
[Key(11)] public string[] FieldIds { get; set; } = [];
|
||||
[Key(12)] public float[] FieldPositionX { get; set; } = [];
|
||||
[Key(13)] public float[] FieldPositionY { get; set; } = [];
|
||||
[Key(14)] public float[] FieldStrength { get; set; } = [];
|
||||
[Key(15)] public float[] FieldRadius { get; set; } = [];
|
||||
[Key(16)] public float[] DirectionX { get; set; } = [];
|
||||
[Key(17)] public float[] DirectionY { get; set; } = [];
|
||||
[Key(18)] public float[] AngularVelocity { get; set; } = [];
|
||||
[Key(19)] public float[] KinematicMask { get; set; } = [];
|
||||
[Key(20)] public float[] BulletMask { get; set; } = [];
|
||||
[Key(21)] public float[] FieldParticipationMask { get; set; } = [];
|
||||
[Key(22)] public ulong[] CollisionCategoryBits { get; set; } = [];
|
||||
[Key(23)] public ulong[] CollisionMaskBits { get; set; } = [];
|
||||
[Key(24)] public int[] CollisionGroupIndex { get; set; } = [];
|
||||
|
||||
public static YmirWorldStateDocumentV2 FromSoA(string worldId, YmirSoAWorld world) => new()
|
||||
{
|
||||
WorldId = worldId, Time = world.Time,
|
||||
BodyIds = (string[])world.BodyIds.Clone(),
|
||||
PositionX = (float[])world.PositionX.Clone(), PositionY = (float[])world.PositionY.Clone(),
|
||||
VelocityX = (float[])world.VelocityX.Clone(), VelocityY = (float[])world.VelocityY.Clone(),
|
||||
Radius = (float[])world.Radius.Clone(), Mass = (float[])world.Mass.Clone(),
|
||||
DynamicMask = (float[])world.DynamicMask.Clone(), Restitution = (float[])world.Restitution.Clone(),
|
||||
FieldIds = (string[])world.FieldIds.Clone(),
|
||||
FieldPositionX = (float[])world.FieldPositionX.Clone(), FieldPositionY = (float[])world.FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])world.FieldStrength.Clone(), FieldRadius = (float[])world.FieldRadius.Clone(),
|
||||
DirectionX = (float[])world.DirectionX.Clone(), DirectionY = (float[])world.DirectionY.Clone(),
|
||||
AngularVelocity = (float[])world.AngularVelocity.Clone(),
|
||||
KinematicMask = (float[])world.KinematicMask.Clone(), BulletMask = (float[])world.BulletMask.Clone(),
|
||||
FieldParticipationMask = (float[])world.FieldParticipationMask.Clone(),
|
||||
CollisionCategoryBits = (ulong[])world.CollisionCategoryBits.Clone(),
|
||||
CollisionMaskBits = (ulong[])world.CollisionMaskBits.Clone(),
|
||||
CollisionGroupIndex = (int[])world.CollisionGroupIndex.Clone()
|
||||
};
|
||||
|
||||
public YmirSoAWorld ToSoA() => new()
|
||||
{
|
||||
Time = Time, BodyIds = (string[])BodyIds.Clone(),
|
||||
PositionX = (float[])PositionX.Clone(), PositionY = (float[])PositionY.Clone(),
|
||||
VelocityX = (float[])VelocityX.Clone(), VelocityY = (float[])VelocityY.Clone(),
|
||||
Radius = (float[])Radius.Clone(), Mass = (float[])Mass.Clone(),
|
||||
DynamicMask = (float[])DynamicMask.Clone(), Restitution = (float[])Restitution.Clone(),
|
||||
FieldIds = (string[])FieldIds.Clone(),
|
||||
FieldPositionX = (float[])FieldPositionX.Clone(), FieldPositionY = (float[])FieldPositionY.Clone(),
|
||||
FieldStrength = (float[])FieldStrength.Clone(), FieldRadius = (float[])FieldRadius.Clone(),
|
||||
DirectionX = (float[])DirectionX.Clone(), DirectionY = (float[])DirectionY.Clone(),
|
||||
AngularVelocity = (float[])AngularVelocity.Clone(),
|
||||
KinematicMask = (float[])KinematicMask.Clone(), BulletMask = (float[])BulletMask.Clone(),
|
||||
FieldParticipationMask = (float[])FieldParticipationMask.Clone(),
|
||||
CollisionCategoryBits = (ulong[])CollisionCategoryBits.Clone(),
|
||||
CollisionMaskBits = (ulong[])CollisionMaskBits.Clone(),
|
||||
CollisionGroupIndex = (int[])CollisionGroupIndex.Clone()
|
||||
};
|
||||
}
|
||||
|
||||
public static class YmirCultCacheStore
|
||||
{
|
||||
public static async Task SaveWorldAsync(string path, string worldId, YmirSoAWorld world)
|
||||
{
|
||||
var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions
|
||||
{
|
||||
UseDirectoryStore = true,
|
||||
FlushOnDispose = true,
|
||||
StoreFlushOnDispose = true
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
using (cache)
|
||||
{
|
||||
await cache.UpsertAsync(
|
||||
YmirWorldStateDocumentV2.FromSoA(worldId, world),
|
||||
new CultRecordHandle<YmirWorldStateDocumentV2>(new CultRecordKey($"ymir:world:{worldId}")))
|
||||
.ConfigureAwait(false);
|
||||
await cache.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<YmirSoAWorld?> LoadWorldAsync(string path, string worldId)
|
||||
{
|
||||
using var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions { UseDirectoryStore = true }).ConfigureAwait(false);
|
||||
var key = new CultRecordKey($"ymir:world:{worldId}");
|
||||
return cache.Get<YmirWorldStateDocumentV2>(key)?.ToSoA()
|
||||
?? cache.Get<YmirWorldStateDocumentV1>(key)?.ToSoA()
|
||||
?? cache.Get<YmirWorldStateDocumentV0>(key)?.ToSoA();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
using System.Text.Json;
|
||||
using CultMath;
|
||||
using Ymir.Core;
|
||||
|
||||
namespace Ymir.Daemon;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
var command = args.FirstOrDefault() ?? "help";
|
||||
|
||||
switch (command)
|
||||
{
|
||||
case "publish-service":
|
||||
await PublishServiceAsync(ValueAfter(args, "--path") ?? ".ymir/service.cc");
|
||||
return 0;
|
||||
case "step-sample":
|
||||
WriteJson(new YmirSimulator().Step(SampleRequest()));
|
||||
return 0;
|
||||
case "save-sample":
|
||||
await SaveSampleAsync(ValueAfter(args, "--path") ?? ".ymir/worlds.cc");
|
||||
return 0;
|
||||
case "step":
|
||||
return RunStep(args);
|
||||
default:
|
||||
PrintHelp();
|
||||
return command is "help" or "-h" or "--help" ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
private static int RunStep(string[] args)
|
||||
{
|
||||
var requestPath = ValueAfter(args, "--request");
|
||||
if (string.IsNullOrWhiteSpace(requestPath))
|
||||
{
|
||||
Console.Error.WriteLine("step requires --request <path>.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var request = JsonSerializer.Deserialize<SimulationStepRequest>(
|
||||
File.ReadAllText(requestPath),
|
||||
JsonOptions);
|
||||
|
||||
if (request is null)
|
||||
{
|
||||
Console.Error.WriteLine("Could not deserialize simulation step request.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
WriteJson(new YmirSimulator().Step(request));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static SimulationStepRequest SampleRequest() => new(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
new[]
|
||||
{
|
||||
new PhysicsBody("projectile", new Vec2(-2.0f, 0.0f), new Vec2(4.0f, 0.0f), 0.1f, 1.0f, Restitution: 0.0f),
|
||||
new PhysicsBody("target", new Vec2(0.5f, 0.0f), Vec2.Zero, 0.5f, 1.0f, IsStatic: true)
|
||||
},
|
||||
new[]
|
||||
{
|
||||
new RadialField("gravity-well", new Vec2(0.0f, 1.0f), 2.0f, 8.0f)
|
||||
}));
|
||||
|
||||
private static async Task SaveSampleAsync(string path)
|
||||
{
|
||||
var result = new YmirSimulator().Step(new SoASimulationStepRequest(
|
||||
SampleRequest().DeltaTime,
|
||||
YmirSoAWorld.FromWorld(SampleRequest().World)));
|
||||
await YmirCultCacheStore.SaveWorldAsync(path, "sample", result.World);
|
||||
WriteJson(new
|
||||
{
|
||||
ok = true,
|
||||
path,
|
||||
record = "ymir:world:sample",
|
||||
schema = "gamecult.ymir.world_state.v2",
|
||||
bodyCount = result.World.BodyCount,
|
||||
fieldCount = result.World.FieldCount
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task PublishServiceAsync(string path)
|
||||
{
|
||||
await YmirServicePublicationStore.RegenerateDerivedStoreAsync(path, DateTimeOffset.UtcNow);
|
||||
WriteJson(new
|
||||
{
|
||||
ok = true,
|
||||
path,
|
||||
records = new[]
|
||||
{
|
||||
"ymir:provider:ymir.physics",
|
||||
"ymir:operator:ymir.physics",
|
||||
"surface:ymir.physics.operator"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void WriteJson(object value) => Console.WriteLine(JsonSerializer.Serialize(value, JsonOptions));
|
||||
|
||||
private static string? ValueAfter(string[] args, string key)
|
||||
{
|
||||
var index = Array.IndexOf(args, key);
|
||||
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
private static void PrintHelp()
|
||||
{
|
||||
Console.WriteLine("""
|
||||
Ymir physics cutover CLI
|
||||
|
||||
Commands:
|
||||
publish-service [--path .ymir/service.cc] Regenerate the derived service publication.
|
||||
step-sample
|
||||
save-sample [--path .ymir/worlds.cc]
|
||||
step --request <path>
|
||||
""");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Ymir.Core\Ymir.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Ymir.Daemon</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>ymir-daemon</AssemblyName>
|
||||
<Description>Ymir cutover CLI; the retained Box3D daemon session is not active yet.</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,213 +0,0 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Ymir.Box3D.Parity;
|
||||
|
||||
internal static partial class Box3DOracle
|
||||
{
|
||||
private const string LibraryName = "ymir_box3d";
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_get_version(out int major, out int minor, out int revision);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DOverlapResult ymir_box3d_overlap_spheres(
|
||||
float queryX,
|
||||
float queryY,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyY,
|
||||
float bodyRadius);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DOverlapResult ymir_box3d_overlap_capsule_sphere(
|
||||
float startX,
|
||||
float startY,
|
||||
float endX,
|
||||
float endY,
|
||||
float capsuleRadius,
|
||||
float bodyX,
|
||||
float bodyY,
|
||||
float bodyRadius);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DCastResult ymir_box3d_cast_sphere(
|
||||
float originX,
|
||||
float originY,
|
||||
float translationX,
|
||||
float translationY,
|
||||
float queryRadius,
|
||||
float bodyX,
|
||||
float bodyY,
|
||||
float bodyRadius,
|
||||
int canEncroach);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial void ymir_box3d_step_pair(
|
||||
in Box3DBodyInput bodyA,
|
||||
in Box3DBodyInput bodyB,
|
||||
float timeStep,
|
||||
int subStepCount,
|
||||
float restitutionThreshold,
|
||||
out Box3DPairStepResult result);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial Box3DTorqueResult ymir_box3d_torque_lifetime(float torque, float timeStep, int subStepCount);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial uint ymir_box3d_get_abi_version();
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_create(out nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial void ymir_box3d_session_destroy(nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial int ymir_box3d_session_spawn(nint session, Box3DSessionBodyInput* body);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_remove(nint session, ulong stableId);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial int ymir_box3d_session_step(
|
||||
nint session,
|
||||
float deltaTime,
|
||||
int substepCount,
|
||||
void* fields,
|
||||
int fieldCount);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_contact_event_count(nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static partial int ymir_box3d_session_get_body_count(nint session);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial int ymir_box3d_session_copy_bodies(
|
||||
nint session,
|
||||
Box3DSessionBodyOutput* bodies,
|
||||
int capacity,
|
||||
out int written);
|
||||
|
||||
[LibraryImport(LibraryName)]
|
||||
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
|
||||
internal static unsafe partial int ymir_box3d_session_copy_contact_events(
|
||||
nint session,
|
||||
Box3DSessionContactEvent* events,
|
||||
int capacity,
|
||||
out int written);
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DOverlapResult(int Hit, float Distance, float NormalX, float NormalY)
|
||||
{
|
||||
public bool IsHit => Hit != 0;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DCastResult(
|
||||
int Hit,
|
||||
float Fraction,
|
||||
float PointX,
|
||||
float PointY,
|
||||
float NormalX,
|
||||
float NormalY)
|
||||
{
|
||||
public bool IsHit => Hit != 0;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DBodyInput(
|
||||
float PositionX,
|
||||
float PositionY,
|
||||
float VelocityX,
|
||||
float VelocityY,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
int IsStatic);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DBodyOutput(
|
||||
float PositionX,
|
||||
float PositionY,
|
||||
float VelocityX,
|
||||
float VelocityY,
|
||||
float AngularVelocity);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DPairStepResult(
|
||||
Box3DBodyOutput BodyA,
|
||||
Box3DBodyOutput BodyB,
|
||||
int BeginContactCount,
|
||||
int EndContactCount,
|
||||
int HitContactCount);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DTorqueResult(
|
||||
float AngularVelocityAfterAppliedStep,
|
||||
float AngularVelocityAfterUnforcedStep);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DSessionBodyInput(
|
||||
ulong StableId,
|
||||
ulong CollisionCategoryBits,
|
||||
ulong CollisionMaskBits,
|
||||
float PositionX,
|
||||
float PositionY,
|
||||
float VelocityX,
|
||||
float VelocityY,
|
||||
float DirectionX,
|
||||
float DirectionY,
|
||||
float AngularVelocity,
|
||||
float Torque,
|
||||
float Radius,
|
||||
float Mass,
|
||||
float Restitution,
|
||||
uint IsStatic,
|
||||
uint IsKinematic,
|
||||
uint IsBullet,
|
||||
uint ParticipatesInFields,
|
||||
int CollisionGroupIndex);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DSessionContactEvent(
|
||||
int Kind,
|
||||
uint HasDetails,
|
||||
uint ContactId0,
|
||||
uint ContactId1,
|
||||
uint ContactId2,
|
||||
ulong StableIdA,
|
||||
ulong StableIdB,
|
||||
float PointX,
|
||||
float PointY,
|
||||
float NormalX,
|
||||
float NormalY,
|
||||
float Penetration,
|
||||
float RelativeSpeed);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal readonly record struct Box3DSessionBodyOutput(
|
||||
ulong StableId,
|
||||
float PositionX,
|
||||
float PositionY,
|
||||
float VelocityX,
|
||||
float VelocityY,
|
||||
float DirectionX,
|
||||
float DirectionY,
|
||||
float AngularVelocity);
|
||||
|
|
@ -1,249 +0,0 @@
|
|||
namespace Ymir.Box3D.Parity;
|
||||
|
||||
public sealed class Box3DParityTests
|
||||
{
|
||||
[Fact]
|
||||
public void OracleIsPinnedBox3DRelease()
|
||||
{
|
||||
var doublePrecision = Box3DOracle.ymir_box3d_get_version(out var major, out var minor, out var revision);
|
||||
|
||||
Assert.Equal((0, 1, 0), (major, minor, revision));
|
||||
Assert.Equal(0, doublePrecision);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1.9f, true)]
|
||||
[InlineData(2.0f, true)]
|
||||
[InlineData(2.00049f, true)]
|
||||
[InlineData(2.00051f, false)]
|
||||
public void SphereOverlapClassificationMatchesBox3DSlop(float centerDistance, bool expected)
|
||||
{
|
||||
var result = Box3DOracle.ymir_box3d_overlap_spheres(0.0f, 0.0f, 1.0f, centerDistance, 0.0f, 1.0f);
|
||||
|
||||
Assert.Equal(expected, result.IsHit);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1.00049f, true)]
|
||||
[InlineData(-1.00051f, false)]
|
||||
[InlineData(5.0f, true)]
|
||||
[InlineData(11.00049f, true)]
|
||||
[InlineData(11.00051f, false)]
|
||||
public void TractorCapsuleMembershipUsesBox3DRoundedCapsAndSlop(float pickupX, bool expected)
|
||||
{
|
||||
var result = Box3DOracle.ymir_box3d_overlap_capsule_sphere(
|
||||
0.0f,
|
||||
0.0f,
|
||||
10.0f,
|
||||
0.0f,
|
||||
0.5f,
|
||||
pickupX,
|
||||
0.0f,
|
||||
0.5f);
|
||||
|
||||
Assert.Equal(expected, result.IsHit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SphereCastReturnsBox3DFractionAndNormal()
|
||||
{
|
||||
var result = Box3DOracle.ymir_box3d_cast_sphere(
|
||||
-5.0f,
|
||||
0.0f,
|
||||
10.0f,
|
||||
0.0f,
|
||||
0.5f,
|
||||
0.0f,
|
||||
0.0f,
|
||||
1.0f,
|
||||
0);
|
||||
|
||||
Assert.True(result.IsHit);
|
||||
Assert.Equal(0.3505f, result.Fraction, precision: 4);
|
||||
Assert.Equal(-1.0f, result.NormalX, precision: 4);
|
||||
Assert.Equal(0.0f, result.NormalY, precision: 4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1.5f)]
|
||||
[InlineData(-1.4f)]
|
||||
[InlineData(0.0f)]
|
||||
public void SphereCastInitiallyTouchingOrOverlappingIsAHit(float originX)
|
||||
{
|
||||
var result = Box3DOracle.ymir_box3d_cast_sphere(
|
||||
originX,
|
||||
0.0f,
|
||||
5.0f,
|
||||
0.0f,
|
||||
0.5f,
|
||||
0.0f,
|
||||
0.0f,
|
||||
1.0f,
|
||||
0);
|
||||
|
||||
Assert.True(result.IsHit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PairStepEmitsBeginContactAndSeparatesOverlappingSpheres()
|
||||
{
|
||||
var bodyA = new Box3DBodyInput(-0.9f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0);
|
||||
var bodyB = new Box3DBodyInput(0.9f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0);
|
||||
|
||||
Box3DOracle.ymir_box3d_step_pair(in bodyA, in bodyB, 1.0f / 60.0f, 4, 0.0f, out var result);
|
||||
|
||||
Assert.Equal(1, result.BeginContactCount);
|
||||
Assert.True(result.BodyA.PositionX < -0.9f);
|
||||
Assert.True(result.BodyB.PositionX > 0.9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PairStepUsesMaximumRestitution()
|
||||
{
|
||||
var bodyA = new Box3DBodyInput(-1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.1f, 0);
|
||||
var bodyB = new Box3DBodyInput(1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.8f, 0);
|
||||
|
||||
Box3DOracle.ymir_box3d_step_pair(in bodyA, in bodyB, 1.0f / 60.0f, 4, 0.0f, out var result);
|
||||
|
||||
Assert.True(result.BodyA.VelocityX < -0.7f);
|
||||
Assert.True(result.BodyB.VelocityX > 0.7f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TorqueIsClearedAfterEachWorldStep()
|
||||
{
|
||||
var result = Box3DOracle.ymir_box3d_torque_lifetime(0.4f, 0.1f, 4);
|
||||
|
||||
Assert.True(result.AngularVelocityAfterAppliedStep > 0.0f);
|
||||
Assert.Equal(
|
||||
result.AngularVelocityAfterAppliedStep,
|
||||
result.AngularVelocityAfterUnforcedStep,
|
||||
precision: 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void RetainedSessionCommandsPreserveTypedContactLifecycle()
|
||||
{
|
||||
Assert.Equal(5u, Box3DOracle.ymir_box3d_get_abi_version());
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session));
|
||||
try
|
||||
{
|
||||
var bodyA = SessionBody(1, -0.9f);
|
||||
var bodyB = SessionBody(2, 0.9f);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyB));
|
||||
Assert.Equal(2, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA));
|
||||
Assert.Equal(1, Box3DOracle.ymir_box3d_session_remove(session, 999));
|
||||
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
|
||||
var beginEvents = CopyEvents(session);
|
||||
var begin = Assert.Single(beginEvents, value => value.Kind == 1);
|
||||
Assert.Equal(new HashSet<ulong> { 1, 2 }, new HashSet<ulong> { begin.StableIdA, begin.StableIdB });
|
||||
Assert.Equal(1u, begin.HasDetails);
|
||||
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_remove(session, 2));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
|
||||
var end = Assert.Single(CopyEvents(session), value => value.Kind == 3);
|
||||
Assert.Equal(new HashSet<ulong> { 1, 2 }, new HashSet<ulong> { end.StableIdA, end.StableIdB });
|
||||
Assert.Equal(0u, end.HasDetails);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Box3DOracle.ymir_box3d_session_destroy(session);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void NegativeGroupAndCategoryMasksAreBox3DCollisionAuthority()
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session));
|
||||
try
|
||||
{
|
||||
var source = SessionBody(1, 0.0f, category: 1, mask: 2, group: -7);
|
||||
var ownPayload = SessionBody(2, 0.0f, category: 2, mask: 1, group: -7);
|
||||
var otherPayload = SessionBody(3, 0.0f, category: 2, mask: 1, group: -8);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &source));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &ownPayload));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &otherPayload));
|
||||
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
|
||||
var pairs = CopyEvents(session)
|
||||
.Where(value => value.Kind == 1)
|
||||
.Select(value => new HashSet<ulong> { value.StableIdA, value.StableIdB })
|
||||
.ToArray();
|
||||
|
||||
Assert.Single(pairs);
|
||||
Assert.Equal(new HashSet<ulong> { 1, 3 }, pairs[0]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Box3DOracle.ymir_box3d_session_destroy(session);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void BulletUsesBox3DContinuousCollisionAgainstKinematicTarget()
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session));
|
||||
try
|
||||
{
|
||||
var bullet = SessionBody(1, -10.0f, velocityX: 100.0f, isBullet: true);
|
||||
var target = SessionBody(2, 0.0f, isKinematic: true);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bullet));
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &target));
|
||||
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 0.2f, 4, null, 0));
|
||||
Assert.Empty(CopyEvents(session));
|
||||
var ccdBodies = CopyBodies(session);
|
||||
Assert.True(ccdBodies.Single(value => value.StableId == 1).PositionX < 0.0f);
|
||||
Assert.Equal(0.0f, ccdBodies.Single(value => value.StableId == 2).PositionX, precision: 5);
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0));
|
||||
Assert.Contains(CopyEvents(session), value =>
|
||||
(value.Kind == 1 || value.Kind == 2) &&
|
||||
new HashSet<ulong> { value.StableIdA, value.StableIdB }.SetEquals([1UL, 2UL]));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Box3DOracle.ymir_box3d_session_destroy(session);
|
||||
}
|
||||
}
|
||||
|
||||
private static Box3DSessionBodyInput SessionBody(
|
||||
ulong id,
|
||||
float positionX,
|
||||
float velocityX = 0.0f,
|
||||
ulong category = 1,
|
||||
ulong mask = ulong.MaxValue,
|
||||
int group = 0,
|
||||
bool isKinematic = false,
|
||||
bool isBullet = false) => new(
|
||||
id, category, mask, positionX, 0.0f, velocityX, 0.0f, 0.0f, 1.0f,
|
||||
0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0,
|
||||
isKinematic ? 1u : 0u, isBullet ? 1u : 0u, 1u, group);
|
||||
|
||||
private static unsafe Box3DSessionContactEvent[] CopyEvents(nint session)
|
||||
{
|
||||
var count = Box3DOracle.ymir_box3d_session_get_contact_event_count(session);
|
||||
Assert.True(count >= 0);
|
||||
var events = new Box3DSessionContactEvent[count];
|
||||
fixed (Box3DSessionContactEvent* pointer = events)
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_copy_contact_events(session, pointer, count, out var written));
|
||||
Assert.Equal(count, written);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
private static unsafe Box3DSessionBodyOutput[] CopyBodies(nint session)
|
||||
{
|
||||
var count = Box3DOracle.ymir_box3d_session_get_body_count(session);
|
||||
Assert.True(count >= 0);
|
||||
var bodies = new Box3DSessionBodyOutput[count];
|
||||
fixed (Box3DSessionBodyOutput* pointer = bodies)
|
||||
{
|
||||
Assert.Equal(0, Box3DOracle.ymir_box3d_session_copy_bodies(session, pointer, count, out var written));
|
||||
Assert.Equal(count, written);
|
||||
}
|
||||
return bodies;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<IsPackable>false</IsPackable>
|
||||
<NativeSourceDir>$(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D</NativeSourceDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\parity\$(Configuration)</NativeBuildDir>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == '' and '$(OS)' == 'Windows_NT' and Exists('C:\Program Files\CMake\bin\cmake.exe')">C:\Program Files\CMake\bin\cmake.exe</CMakeExe>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == ''">cmake</CMakeExe>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="BuildBox3DParityOracle" BeforeTargets="Build" Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Exec Command=""$(CMakeExe)" -S "$(NativeSourceDir)" -B "$(NativeBuildDir)" -DBUILD_SHARED_LIBS=OFF" />
|
||||
<Exec Command=""$(CMakeExe)" --build "$(NativeBuildDir)" --config $(Configuration) --target ymir_box3d" />
|
||||
<Copy SourceFiles="$(NativeBuildDir)\bin\$(Configuration)\ymir_box3d.dll" DestinationFolder="$(OutDir)" Condition="'$(OS)' == 'Windows_NT'" />
|
||||
<Copy SourceFiles="$(NativeBuildDir)\bin\libymir_box3d.so" DestinationFolder="$(OutDir)" Condition="'$(OS)' != 'Windows_NT' and !$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<Copy SourceFiles="$(NativeBuildDir)\bin\libymir_box3d.dylib" DestinationFolder="$(OutDir)" Condition="$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
// Box3D world creation is not safe to run concurrently in one process: two threads calling
|
||||
// b3CreateWorld abort the host (found when two test classes created worlds at once). Tests that create
|
||||
// worlds run one at a time.
|
||||
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
||||
46
tests/Ymir.Box3D.Soa.Tests/Box3DSoaConcurrentCreateTests.cs
Normal file
46
tests/Ymir.Box3D.Soa.Tests/Box3DSoaConcurrentCreateTests.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
public sealed class Box3DSoaConcurrentCreateTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Box3D's world pool is a process-global array scanned without a lock; without the native
|
||||
/// create/destroy lock, concurrent creation claims one slot twice and aborts the host.
|
||||
/// Each thread creates, steps and disposes many worlds while the others do the same.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Worlds_created_stepped_and_disposed_from_many_threads_do_not_crash()
|
||||
{
|
||||
const int threads = 8;
|
||||
const int rounds = 200;
|
||||
using var start = new ManualResetEventSlim(false);
|
||||
var failures = new List<Exception>();
|
||||
|
||||
var workers = Enumerable.Range(0, threads).Select(t => new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
start.Wait();
|
||||
for (var r = 0; r < rounds; r++)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 8);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (10f, 0.5f, 10f));
|
||||
world.AddSphere(2, (0f, 2f, 0f), radius: 0.5f, density: 1f, velocity: (0f, 0f, 0f));
|
||||
for (var s = 0; s < 3; s++) world.Step(1f / 60f);
|
||||
if (world.View.Count != 2) throw new InvalidOperationException("lane count");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
lock (failures) failures.Add(e);
|
||||
}
|
||||
})).ToArray();
|
||||
|
||||
foreach (var w in workers) w.Start();
|
||||
start.Set();
|
||||
foreach (var w in workers) w.Join();
|
||||
|
||||
Assert.Empty(failures);
|
||||
}
|
||||
}
|
||||
255
tests/Ymir.Box3D.Soa.Tests/Box3DSoaContactTests.cs
Normal file
255
tests/Ymir.Box3D.Soa.Tests/Box3DSoaContactTests.cs
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
public sealed class Box3DSoaContactTests
|
||||
{
|
||||
private const float Dt = 1f / 60f;
|
||||
private const float G = 10f;
|
||||
private const float Radius = 0.5f;
|
||||
private const ulong GroundId = 1;
|
||||
private const ulong BallId = 2;
|
||||
|
||||
private static float BallMass => 4f / 3f * MathF.PI * Radius * Radius * Radius; // density 1
|
||||
|
||||
/// <summary>A ground slab with its top face at y = 0 (lane 0) and a ball (lane 1) dropped from 1.4 m above it.</summary>
|
||||
private static Box3DSoaWorld Drop(float height = 1.4f, int? factCapacity = null, float hitThreshold = 1f)
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: 8, gravityY: -G, factCapacity: factCapacity, hitThreshold: hitThreshold);
|
||||
world.AddStaticBox(GroundId, (0f, -0.5f, 0f), (50f, 0.5f, 50f), materialId: 7);
|
||||
world.AddSphere(BallId, (0f, Radius + height, 0f), Radius, density: 1f, materialId: 42);
|
||||
return world;
|
||||
}
|
||||
|
||||
/// <summary>Steps until the first step that reports a begin; returns false if none within the budget.</summary>
|
||||
private static bool StepToFirstBegin(Box3DSoaWorld world, int budget = 120)
|
||||
{
|
||||
for (var i = 0; i < budget; i++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
if (world.Facts.Begin.Length > 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_drop_gives_one_begin_and_one_hit()
|
||||
{
|
||||
using var world = Drop();
|
||||
int begins = 0, hits = 0, ends = 0;
|
||||
Box3DSoaHit hit = default;
|
||||
Box3DSoaTouch begin = default;
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
var facts = world.Facts;
|
||||
if (facts.Begin.Length > 0) begin = facts.Begin[0];
|
||||
if (facts.Hit.Length > 0) hit = facts.Hit[0];
|
||||
begins += facts.Begin.Length;
|
||||
hits += facts.Hit.Length;
|
||||
ends += facts.End.Length;
|
||||
Assert.Equal(0u, facts.Dropped.Begin + facts.Dropped.End + facts.Dropped.Hit);
|
||||
}
|
||||
Assert.Equal((1, 1, 0), (begins, hits, ends));
|
||||
|
||||
Assert.Equal(new[] { 0, 1 }, new[] { begin.LaneA, begin.LaneB }.Order());
|
||||
Assert.Equal(new[] { GroundId, BallId }, new[] { begin.StableIdA, begin.StableIdB }.Order());
|
||||
Assert.Equal((begin.LaneA, begin.LaneB, begin.StableIdA, begin.StableIdB), (hit.LaneA, hit.LaneB, hit.StableIdA, hit.StableIdB));
|
||||
Assert.Equal(begin.LaneA == 0 ? GroundId : BallId, begin.StableIdA); // the stable id is the lane's own
|
||||
|
||||
var expected = MathF.Sqrt(2f * G * 1.4f);
|
||||
Assert.InRange(hit.ApproachSpeed, expected * 0.95f, expected * 1.05f);
|
||||
Assert.InRange(hit.PointY, -0.02f, 0.02f);
|
||||
Assert.InRange(MathF.Abs(hit.PointX), 0f, 0.05f);
|
||||
Assert.InRange(MathF.Abs(hit.NormalY), 0.99f, 1.001f);
|
||||
// A to B: the normal points from the ground up to the ball when the ground is A.
|
||||
Assert.True(hit.LaneA == 0 ? hit.NormalY > 0f : hit.NormalY < 0f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lifting_gives_one_end()
|
||||
{
|
||||
using var world = Drop();
|
||||
Run(world, 240);
|
||||
Assert.Equal(1, world.View.ContactCount[1]);
|
||||
|
||||
world.View.ForceY[1] = 100f; // one step's push: about 3 m/s upward, well clear of the slab within a few steps
|
||||
var begins = 0;
|
||||
var ends = new List<Box3DSoaTouch>();
|
||||
for (var i = 0; i < 20; i++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
begins += world.Facts.Begin.Length;
|
||||
ends.AddRange(world.Facts.End.ToArray());
|
||||
}
|
||||
Assert.Equal(0, begins);
|
||||
var end = Assert.Single(ends);
|
||||
Assert.Equal(new[] { 0, 1 }, new[] { end.LaneA, end.LaneB }.Order());
|
||||
Assert.Equal(new[] { GroundId, BallId }, new[] { end.StableIdA, end.StableIdB }.Order());
|
||||
Assert.Equal(0, world.View.ContactCount[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Materials_ride_hits_in_pair_order_and_read_back_as_a_lane()
|
||||
{
|
||||
using var world = Drop();
|
||||
Assert.Equal(new ulong[] { 7, 42 }, world.View.MaterialId.ToArray());
|
||||
Assert.True(StepToFirstBegin(world));
|
||||
var hit = Assert.Single(world.Facts.Hit.ToArray());
|
||||
var material = new Dictionary<int, ulong> { [0] = 7, [1] = 42 };
|
||||
Assert.Equal((material[hit.LaneA], material[hit.LaneB]), (hit.MaterialA, hit.MaterialB));
|
||||
Assert.Equal(new ulong[] { 7, 42 }, world.View.MaterialId.ToArray()); // unchanged by stepping
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Facts_last_one_step()
|
||||
{
|
||||
using var world = Drop();
|
||||
Assert.True(StepToFirstBegin(world));
|
||||
Assert.Equal(1, world.Facts.Hit.Length);
|
||||
world.Step(Dt);
|
||||
var facts = world.Facts;
|
||||
Assert.Equal((0, 0, 0), (facts.Begin.Length, facts.End.Length, facts.Hit.Length));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Overflow_is_counted_and_a_zero_capacity_is_refused()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G, factCapacity: 1);
|
||||
world.AddStaticBox(GroundId, (0f, -0.5f, 0f), (50f, 0.5f, 50f));
|
||||
world.AddSphere(2, (-3f, 1.9f, 0f), Radius, density: 1f);
|
||||
world.AddSphere(3, (3f, 1.9f, 0f), Radius, density: 1f);
|
||||
Assert.True(StepToFirstBegin(world));
|
||||
var facts = world.Facts;
|
||||
Assert.Equal(1, facts.Begin.Length);
|
||||
Assert.Equal(1, facts.Hit.Length);
|
||||
Assert.Equal(1u, facts.Dropped.Begin);
|
||||
Assert.Equal(1u, facts.Dropped.Hit);
|
||||
Assert.Equal(1, facts.Capacity);
|
||||
for (var i = 0; i < 400 && world.Facts.Dropped.Touching == 0; i++) world.Step(Dt);
|
||||
Assert.Equal(1, world.Facts.Touching.Length);
|
||||
Assert.True(world.Facts.Dropped.Touching >= 1u);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => new Box3DSoaWorld(capacity: 8, factCapacity: 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dropped_counters_reset_every_step()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G, factCapacity: 1);
|
||||
world.AddStaticBox(GroundId, (0f, -0.5f, 0f), (50f, 0.5f, 50f));
|
||||
world.AddSphere(2, (-3f, 1.9f, 0f), Radius, density: 1f);
|
||||
world.AddSphere(3, (3f, 1.9f, 0f), Radius, density: 1f);
|
||||
Assert.True(StepToFirstBegin(world));
|
||||
Assert.Equal(1u, world.Facts.Dropped.Begin);
|
||||
world.Step(Dt);
|
||||
Assert.Equal(new Box3DSoaDropped(0, 0, 0, 1), world.Facts.Dropped); // the two resting spheres still touch the ground: one pair kept, one dropped, every step
|
||||
}
|
||||
|
||||
private static Box3DSoaWorld Pile()
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: 32, gravityY: -G);
|
||||
world.AddStaticBox(GroundId, (0f, -0.5f, 0f), (50f, 0.5f, 50f), materialId: 3);
|
||||
ulong id = 100;
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
for (var z = 0; z < 3; z++)
|
||||
{
|
||||
world.AddSphere(id++, (x * 0.9f - 1.4f, 2f + 0.6f * (x + z), z * 0.9f - 0.9f), Radius, density: 1f,
|
||||
velocity: (0.2f * z, 0f, -0.1f * x), materialId: (ulong)(x + 10));
|
||||
}
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
private static byte[] Snapshot(Box3DSoaWorld world)
|
||||
{
|
||||
var facts = world.Facts;
|
||||
var view = world.View;
|
||||
return MemoryMarshal.AsBytes(facts.Begin).ToArray()
|
||||
.Concat(MemoryMarshal.AsBytes(facts.End).ToArray())
|
||||
.Concat(MemoryMarshal.AsBytes(facts.Hit).ToArray())
|
||||
.Concat(MemoryMarshal.AsBytes(view.ContactImpulse).ToArray())
|
||||
.Concat(MemoryMarshal.AsBytes(view.ContactCount).ToArray())
|
||||
.Concat(MemoryMarshal.AsBytes(facts.Touching).ToArray())
|
||||
.Concat(BitConverter.GetBytes(facts.Dropped.Begin + facts.Dropped.End + facts.Dropped.Hit + facts.Dropped.Touching))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Determinism_covers_facts_and_contact_lanes_at_every_step()
|
||||
{
|
||||
using var a = Pile();
|
||||
using var b = Pile();
|
||||
var factsSeen = 0;
|
||||
for (var step = 0; step < 300; step++)
|
||||
{
|
||||
a.Step(Dt);
|
||||
b.Step(Dt);
|
||||
var snapshot = Snapshot(a);
|
||||
Assert.True(snapshot.AsSpan().SequenceEqual(Snapshot(b)), $"facts or contact lanes diverged at step {step}");
|
||||
factsSeen += a.Facts.Begin.Length + a.Facts.Hit.Length + a.Facts.End.Length;
|
||||
}
|
||||
Assert.True(factsSeen > 12, "the pile produced facts, so equality is not trivially empty");
|
||||
Assert.Contains(a.View.ContactImpulse.ToArray(), f => f > 0f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Touching_pairs_are_each_touch_once_and_agree_with_contact_counts()
|
||||
{
|
||||
using var world = Pile();
|
||||
var pairsSeen = 0;
|
||||
for (var step = 0; step < 300; step++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
var touching = world.Facts.Touching;
|
||||
var contacts = world.View.ContactCount;
|
||||
var count = new int[contacts.Length];
|
||||
var seen = new HashSet<(int, int)>();
|
||||
foreach (var t in touching)
|
||||
{
|
||||
Assert.True(t.LaneA < t.LaneB, $"pair {t.LaneA},{t.LaneB} is not ordered at step {step}");
|
||||
Assert.True(seen.Add((t.LaneA, t.LaneB)), $"pair {t.LaneA},{t.LaneB} repeated at step {step}");
|
||||
count[t.LaneA]++;
|
||||
count[t.LaneB]++;
|
||||
}
|
||||
for (var lane = 0; lane < contacts.Length; lane++)
|
||||
{
|
||||
Assert.True(contacts[lane] == count[lane], $"lane {lane}: ContactCount {contacts[lane]} but {count[lane]} pairs at step {step}");
|
||||
}
|
||||
Assert.Equal(0u, world.Facts.Dropped.Touching);
|
||||
pairsSeen += touching.Length;
|
||||
}
|
||||
Assert.True(pairsSeen > 50, "the pile touched, so agreement is not trivially empty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_steady_state_step_with_fact_reads_allocates_nothing()
|
||||
{
|
||||
using var world = Pile();
|
||||
Run(world, 120); // warm up: JIT, and the pile has settled into steady contact
|
||||
long Read()
|
||||
{
|
||||
var facts = world.Facts;
|
||||
var view = world.View;
|
||||
return facts.Begin.Length + facts.End.Length + facts.Hit.Length + (long)view.ContactImpulse[1] + view.ContactCount[1];
|
||||
}
|
||||
Read();
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
long sink = 0;
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
sink += Read();
|
||||
}
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
Assert.Equal(0L, allocated);
|
||||
Assert.True(sink != long.MinValue);
|
||||
}
|
||||
|
||||
private static void Run(Box3DSoaWorld world, int steps)
|
||||
{
|
||||
for (var i = 0; i < steps; i++) world.Step(Dt);
|
||||
}
|
||||
}
|
||||
401
tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingBatchTests.cs
Normal file
401
tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingBatchTests.cs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Attach as a batch ending in one derivation, and the ONE_WAY flag (docs/soa-world.md, attachment lanes).</summary>
|
||||
public sealed partial class Box3DSoaCouplingTests
|
||||
{
|
||||
private static ulong FnvOf(ulong h, ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
foreach (var b in bytes) { h ^= b; h *= 1099511628211ul; }
|
||||
return h;
|
||||
}
|
||||
|
||||
/// <summary>Every attachment lane, the tether count and the particle position and velocity lanes, as one hash.</summary>
|
||||
private static ulong StateHash(Box3DSoaView v)
|
||||
{
|
||||
var h = 1469598103934665603ul;
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentKind));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentFlags));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentGeneration));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentParticle));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentBody));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentPointX));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentPointY));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentPointZ));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.AttachmentCompliance));
|
||||
h = FnvOf(h, BitConverter.GetBytes(v.AttachmentCount));
|
||||
h = FnvOf(h, BitConverter.GetBytes(v.TetherCount));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.ParticleX)); h = FnvOf(h, MemoryMarshal.AsBytes(v.ParticleY)); h = FnvOf(h, MemoryMarshal.AsBytes(v.ParticleZ));
|
||||
h = FnvOf(h, MemoryMarshal.AsBytes(v.ParticleVx)); h = FnvOf(h, MemoryMarshal.AsBytes(v.ParticleVy)); h = FnvOf(h, MemoryMarshal.AsBytes(v.ParticleVz));
|
||||
return h;
|
||||
}
|
||||
|
||||
private static Box3DSoaConstraintHandle AttachOne(Box3DSoaWorld world, in Box3DSoaAttachmentDesc d) =>
|
||||
world.Attach((Box3DSoaAttachKind)d.Kind, d.Particle, d.Body, (d.PointX, d.PointY, d.PointZ), d.Compliance,
|
||||
tether: (d.Flags & 1u) != 0, limb: (d.Flags & 2u) != 0, oneWay: (d.Flags & 4u) != 0);
|
||||
|
||||
/// <summary>
|
||||
/// A 16 x 16 sheet (256 particles, distances and bends) and four capsules; attachment k ties particle k to the capsule of its quadrant at the
|
||||
/// particle's own place. Every 7th is ONE_WAY, every 11th LIMB, so the batch carries each flag.
|
||||
/// </summary>
|
||||
private static (Box3DSoaWorld World, Box3DSoaAttachmentDesc[] Descs) SheetOnCapsules()
|
||||
{
|
||||
var world = Box3DSoaParticleTests.World(bodies: 8, particles: 264, distances: 600, bends: 600, attachments: 256, tethers: 8, gravityY: -G);
|
||||
Pos origin = (-0.225f, 0.5f, -0.225f);
|
||||
var sheet = Graph.Sheet(world, origin, (Spacing, 0f, 0f), (0f, 0f, Spacing), 16, 16, ParticleMass, ParticleRadius);
|
||||
var bodies = new Pos[] { (-0.11f, 0.3f, -0.11f), (0.11f, 0.3f, -0.11f), (-0.11f, 0.3f, 0.11f), (0.11f, 0.3f, 0.11f) };
|
||||
var lanes = new int[4];
|
||||
for (var q = 0; q < 4; q++) lanes[q] = world.AddCapsule((ulong)(q + 1), bodies[q], 0.05f, 0.1f, 1000f);
|
||||
var descs = new Box3DSoaAttachmentDesc[256];
|
||||
for (var k = 0; k < 256; k++)
|
||||
{
|
||||
int i = k % 16, j = k / 16, q = (i / 8) + 2 * (j / 8);
|
||||
Pos at = (origin.X + Spacing * i, origin.Y, origin.Z + Spacing * j);
|
||||
descs[k] = new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, sheet.Particles[k], lanes[q], (at.X - bodies[q].X, at.Y - bodies[q].Y, at.Z - bodies[q].Z),
|
||||
compliance: 1e-5f, limb: k % 11 == 0, oneWay: k % 7 == 0);
|
||||
}
|
||||
return (world, descs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attach_batch_equals_the_same_attaches_one_by_one()
|
||||
{
|
||||
var (singles, descs) = SheetOnCapsules();
|
||||
var (batch, _) = SheetOnCapsules();
|
||||
var one = new Box3DSoaConstraintHandle[256];
|
||||
var many = new Box3DSoaConstraintHandle[256];
|
||||
using (singles)
|
||||
using (batch)
|
||||
{
|
||||
for (var k = 0; k < 256; k++) one[k] = AttachOne(singles, descs[k]);
|
||||
batch.Attach(descs, many);
|
||||
Assert.Equal(one, many);
|
||||
Assert.Equal(256, batch.View.AttachmentCount);
|
||||
Assert.Equal(StateHash(singles.View), StateHash(batch.View));
|
||||
Box3DSoaParticleTests.Run(singles, 120);
|
||||
Box3DSoaParticleTests.Run(batch, 120);
|
||||
Assert.Equal(StateHash(singles.View), StateHash(batch.View));
|
||||
var line = $"ATTACH_BATCH 256 attachments, 120 steps: lanes and generations equal, state hash {StateHash(batch.View):x16}";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attach_batch_reuses_lanes_lowest_first_as_singles_would()
|
||||
{
|
||||
var (singles, descs) = SheetOnCapsules();
|
||||
var (batch, _) = SheetOnCapsules();
|
||||
using (singles)
|
||||
using (batch)
|
||||
{
|
||||
var first = new Box3DSoaConstraintHandle[256];
|
||||
batch.Attach(descs, first);
|
||||
foreach (var d in descs) AttachOne(singles, d);
|
||||
// remove every third lane in both worlds, step, then attach 40 again: the same lowest free lanes with new generations
|
||||
var gone = first.Where((_, k) => k % 3 == 0).ToArray();
|
||||
singles.Remove(gone);
|
||||
batch.Remove(gone);
|
||||
Box3DSoaParticleTests.Run(singles, 1);
|
||||
Box3DSoaParticleTests.Run(batch, 1);
|
||||
var again = descs.Where((_, k) => k % 3 == 0).Take(40).ToArray();
|
||||
var viaSingles = again.Select(d => AttachOne(singles, d)).ToArray();
|
||||
var viaBatch = new Box3DSoaConstraintHandle[40];
|
||||
batch.Attach(again, viaBatch);
|
||||
Assert.Equal(viaSingles, viaBatch);
|
||||
Assert.True(viaBatch.Zip(gone, (n, o) => n.Lane == o.Lane && n.Generation == o.Generation + 1).Take(40).All(x => x));
|
||||
Assert.Equal(StateHash(singles.View), StateHash(batch.View));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Snapshot(Box3DSoaWorld world)
|
||||
{
|
||||
var v = world.View;
|
||||
return $"{v.AttachmentCount}|{v.TetherCount}|{StateHash(v):x16}|{string.Join(",", v.AttachmentKind.ToArray())}|{string.Join(",", v.AttachmentGeneration.ToArray())}";
|
||||
}
|
||||
|
||||
// A batch is atomic and N single Attach calls are not: on a refusal the batch leaves the world as it was, while a loop of singles keeps the
|
||||
// attachments accepted before the refused one. So "a batch equals N singles" holds for an accepted batch (the tests above), and a refused batch
|
||||
// is pinned on its own below. The status can also differ when a bad desc and too few free lanes meet: the batch validates first (INVALID_ARGUMENT),
|
||||
// singles reach FULL at the overflow. Callers that tolerated a late refusal in a loop lose the whole batch.
|
||||
private static void AssertRefusedWhole(Box3DSoaWorld world, Box3DSoaAttachmentDesc[] batch, string status, string what)
|
||||
{
|
||||
var before = Snapshot(world);
|
||||
var e = Assert.Throws<InvalidOperationException>(() => world.Attach(batch));
|
||||
Assert.Contains($"status {status}", e.Message);
|
||||
Assert.True(before == Snapshot(world), $"{what}: the refusal changed a lane");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_batch_with_one_bad_desc_changes_nothing()
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(bodies: 4, particles: 64, distances: 64, bends: 8, attachments: 16, tethers: 600, gravityY: 0f, fluid: 4);
|
||||
var ps = new Box3DSoaParticleHandle[16];
|
||||
world.CreateParticles(Graph.Line((0f, 1f, 0f), (Spacing, 0f, 0f), 16).Select(q => new Box3DSoaParticleDesc(q, ParticleMass, ParticleRadius)).ToArray(), ps);
|
||||
world.CreateDistances(Enumerable.Range(0, 15).Select(i => new Box3DSoaDistanceDesc(ps[i], ps[i + 1])).ToArray());
|
||||
var fluid = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, 3f, 0f), ParticleMass, ParticleRadius, Box3DSoaPhase.Of(2, fluid: true))], fluid);
|
||||
var live = world.AddCapsule(1, (0f, 0f, 0f), 0.05f, 0.1f, 1000f);
|
||||
var dead = world.AddCapsule(2, (1f, 0f, 0f), 0.05f, 0.1f, 1000f);
|
||||
world.RemoveBody(dead);
|
||||
world.Attach(Box3DSoaAttachKind.Static, ps[0], point: (0f, 1f, 0f), tether: true); // a held tether lane to keep unchanged
|
||||
world.Attach(Box3DSoaAttachKind.Body, ps[15], live, (0f, 0f, 0f));
|
||||
Assert.True(world.View.TetherCount > 0);
|
||||
|
||||
Box3DSoaAttachmentDesc[] Batch(Box3DSoaAttachmentDesc bad)
|
||||
{
|
||||
var b = new Box3DSoaAttachmentDesc[8];
|
||||
for (var k = 0; k < 8; k++) b[k] = new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[1 + k], live, (0.01f * k, 0.05f, 0f), tether: k % 2 == 0);
|
||||
b[5] = bad;
|
||||
return b;
|
||||
}
|
||||
AssertRefusedWhole(world, Batch(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, fluid[0], live)), "1", "a fluid particle");
|
||||
AssertRefusedWhole(world, Batch(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[9], dead.Lane)), "1", "a removed body");
|
||||
AssertRefusedWhole(world, Batch(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, ps[9], point: (0f, 1f, 0f), oneWay: true)), "1", "STATIC with ONE_WAY");
|
||||
AssertRefusedWhole(world, Batch(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, ps[9], point: (0f, 1f, 0f), limb: true)), "1", "STATIC with LIMB");
|
||||
AssertRefusedWhole(world, Batch(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[9], live, compliance: -1f)), "1", "a negative compliance");
|
||||
// a batch that fits is taken whole afterwards
|
||||
world.Attach(Batch(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[9], live, (0f, 0.05f, 0f))));
|
||||
Assert.Equal(10, world.View.AttachmentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_batch_past_the_free_lanes_or_the_tether_capacity_changes_nothing()
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(bodies: 4, particles: 32, distances: 32, bends: 8, attachments: 8, tethers: 5, gravityY: 0f);
|
||||
var ps = new Box3DSoaParticleHandle[10];
|
||||
world.CreateParticles(Graph.Line((0f, 1f, 0f), (Spacing, 0f, 0f), 10).Select(q => new Box3DSoaParticleDesc(q, ParticleMass, ParticleRadius)).ToArray(), ps);
|
||||
world.CreateDistances(Enumerable.Range(0, 9).Select(i => new Box3DSoaDistanceDesc(ps[i], ps[i + 1])).ToArray()); // no tether attachment yet: no tethers
|
||||
var body = world.AddCapsule(1, (0f, 0f, 0f), 0.05f, 0.1f, 1000f);
|
||||
world.Attach(Box3DSoaAttachKind.Body, ps[9], body, (0f, 0f, 0f));
|
||||
var spare = new Box3DSoaConstraintHandle[2]; // two tombstones below the count, which the tether batch below would reuse
|
||||
world.Attach([new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[7], body), new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[8], body)], spare);
|
||||
world.Remove(spare);
|
||||
Box3DSoaParticleTests.Run(world, 1);
|
||||
var free = new Box3DSoaAttachmentDesc[8]; // one lane is taken: 8 do not fit in 7
|
||||
for (var k = 0; k < 8; k++) free[k] = new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[k], body);
|
||||
AssertRefusedWhole(world, free, "3", "more descs than free lanes");
|
||||
// two tether attachments over the 10-rope need more tethers than the capacity of 5: the derivation refuses and every lane of the batch backs out
|
||||
var tether = new[]
|
||||
{
|
||||
new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, ps[0], point: (0f, 1f, 0f), tether: true),
|
||||
new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, ps[8], point: (8 * Spacing, 1f, 0f), tether: true),
|
||||
};
|
||||
var before = Snapshot(world);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(tether));
|
||||
Assert.True(before == Snapshot(world), "a derivation that does not fit left a lane of the batch");
|
||||
Assert.Equal(3, world.View.AttachmentCount);
|
||||
Assert.Equal(0, world.View.TetherCount);
|
||||
Assert.Equal(2u, world.View.AttachmentKind[1]); // the tombstones read as they did
|
||||
Assert.Equal(2u, world.View.AttachmentKind[2]);
|
||||
}
|
||||
|
||||
private static (Box3DSoaWorld World, int Box, Box3DSoaParticleHandle Particle) OneWayScene(bool oneWay)
|
||||
{
|
||||
var world = Box3DSoaParticleTests.World(bodies: 4, particles: 8, distances: 1, bends: 1, attachments: 4, tethers: 1, gravityY: 0f);
|
||||
var box = world.AddBox(1, (0f, 0f, 0f), (0.1f, 0.1f, 0.1f), 125f); // 1 kg
|
||||
var p = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0.2f, 0f, 0f), 0.5f, ParticleRadius, velocity: (0f, 1f, 0f))], p);
|
||||
world.Attach(Box3DSoaAttachKind.Body, p[0], box, (0.2f, 0f, 0f), oneWay: oneWay);
|
||||
return (world, box, p[0]);
|
||||
}
|
||||
|
||||
/// <summary>The box's top speed and largest impulse lane magnitude, and the particle's worst distance from its point, over 60 ticks.</summary>
|
||||
private static (float Speed, float Impulse, float Deviation) OneWayRun(bool oneWay)
|
||||
{
|
||||
var (world, box, particle) = OneWayScene(oneWay);
|
||||
using (world)
|
||||
{
|
||||
var speed = 0f; var impulse = 0f; var deviation = 0f;
|
||||
for (var i = 0; i < 60; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
var v = world.View;
|
||||
speed = MathF.Max(speed, MathF.Sqrt(Sq(v.VelocityX[box]) + Sq(v.VelocityY[box]) + Sq(v.VelocityZ[box])));
|
||||
impulse = MathF.Max(impulse, MathF.Sqrt(Sq(v.ParticleImpulseX[box]) + Sq(v.ParticleImpulseY[box]) + Sq(v.ParticleImpulseZ[box])));
|
||||
// the point is the box's local (0.2, 0, 0); a one-way box does not move or turn, and the plain run is not judged on this
|
||||
deviation = MathF.Max(deviation, MathF.Sqrt(Sq(v.ParticleX[particle.Lane] - (v.PositionX[box] + 0.2f)) + Sq(v.ParticleY[particle.Lane] - v.PositionY[box]) + Sq(v.ParticleZ[particle.Lane] - v.PositionZ[box])));
|
||||
}
|
||||
return (speed, impulse, deviation);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_one_way_attachment_holds_its_particle_and_leaves_its_body_alone()
|
||||
{
|
||||
var plain = OneWayRun(false);
|
||||
var one = OneWayRun(true);
|
||||
var line = $"ONE_WAY box speed / impulse lane / particle deviation: plain {F(plain.Speed)} / {F(plain.Impulse)} / {F(plain.Deviation)}; one-way {F(one.Speed)} / {F(one.Impulse)} / {F(one.Deviation)}";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
Assert.True(plain.Impulse > 0f && plain.Speed > 0.05f, "without the flag the particle did not move the box: " + line);
|
||||
Assert.Equal(0f, one.Speed);
|
||||
Assert.Equal(0f, one.Impulse);
|
||||
Assert.True(one.Deviation < OneWayDeviation, "the one-way particle left its point: " + line);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A 10-particle rope sliding at 3 m/s, its first particle tethered to box <c>a</c>, with the tether solved on its own (the particle-tether branch)
|
||||
/// or against a plain second tether on box <c>b</c> (the pair-tether branch). Returns the worst of box <c>a</c>'s impulse lane magnitude plus its
|
||||
/// speed over 60 ticks: what the rope books on the box.
|
||||
/// </summary>
|
||||
private static float TetherLoad(bool oneWay, bool pair)
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(bodies: 4, particles: 32, distances: 32, bends: 8, attachments: 8, tethers: 600, gravityY: 0f);
|
||||
var ps = new Box3DSoaParticleHandle[10];
|
||||
world.CreateParticles(Graph.Line((0f, 0f, 0f), (Spacing, 0f, 0f), 10).Select(q => new Box3DSoaParticleDesc(q, ParticleMass, ParticleRadius, velocity: (3f, 0f, 0f))).ToArray(), ps);
|
||||
world.CreateDistances(Enumerable.Range(0, 9).Select(i => new Box3DSoaDistanceDesc(ps[i], ps[i + 1])).ToArray());
|
||||
var a = world.AddBox(1, (-0.3f, 0f, 0f), (0.1f, 0.1f, 0.1f), 125f);
|
||||
var b = world.AddBox(2, (9 * Spacing + 0.3f, 0f, 0f), (0.1f, 0.1f, 0.1f), 125f);
|
||||
world.Attach([new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[0], a, (0.3f, 0f, 0f), tether: true, oneWay: oneWay)]);
|
||||
if (pair) world.Attach([new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, ps[9], b, (-0.3f, 0f, 0f), tether: true)]);
|
||||
Assert.True(world.View.TetherCount > 0);
|
||||
var worst = 0f; var v = world.View;
|
||||
for (var i = 0; i < 60; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
worst = MathF.Max(worst, MathF.Sqrt(Sq(v.ParticleImpulseX[a]) + Sq(v.ParticleImpulseY[a]) + Sq(v.ParticleImpulseZ[a])) + MathF.Abs(v.VelocityX[a]));
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_one_way_tether_books_nothing_on_its_body_in_either_tether_branch()
|
||||
{
|
||||
// end_w and end_push carry the ONE_WAY guard for solve_attachments and for both tether branches. Pinned only through solve_attachments, the
|
||||
// guard could move out of them and the tethers would load the box again.
|
||||
var plain = TetherLoad(false, false); var one = TetherLoad(true, false);
|
||||
var plainPair = TetherLoad(false, true); var onePair = TetherLoad(true, true);
|
||||
var line = $"ONE_WAY_TETHER box load, particle-tether: plain {F(plain)} one-way {F(one)}; pair-tether: plain {F(plainPair)} one-way {F(onePair)}";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
Assert.True(plain > OneWayTetherLoad && plainPair > OneWayTetherLoad, "without the flag the tether did not load the box: " + line);
|
||||
Assert.True(one < OneWayTetherLoad, "a one-way particle tether loaded its body: " + line);
|
||||
Assert.True(onePair < OneWayTetherLoad, "a one-way pair tether loaded its body: " + line);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_one_way_attachment_is_refused_on_a_world_point()
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
var p = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, 1f, 0f), ParticleMass, ParticleRadius)], p);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(Box3DSoaAttachKind.Static, p[0], point: (0f, 1f, 0f), oneWay: true));
|
||||
Assert.Equal(0, world.View.AttachmentCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_flag_bit_outside_the_known_mask_is_refused()
|
||||
{
|
||||
// The world is valid in every other respect (a live body, a live particle, a legal point and compliance), so only the unknown bit can refuse it.
|
||||
// The managed single Attach cannot send a bit, the descriptor can. Bit 8 is the next bit after ONE_WAY (lodur:ruling:ymir-new-flag-value-no-abi-bump).
|
||||
using var world = Box3DSoaParticleTests.World(bodies: 2, particles: 4, distances: 1, bends: 1, attachments: 4, tethers: 4, gravityY: 0f);
|
||||
var p = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, 1f, 0f), ParticleMass, ParticleRadius)], p);
|
||||
var body = world.AddCapsule(1, (0f, 0f, 0f), 0.05f, 0.1f, 1000f);
|
||||
// the same desc with a known flag is taken, so the refusal below is the bit and nothing else
|
||||
var valid = new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, p[0], body, (0f, 1f, 0f), oneWay: true);
|
||||
var taken = new Box3DSoaConstraintHandle[1];
|
||||
world.Attach([valid], taken);
|
||||
Assert.Equal(1, world.View.AttachmentCount);
|
||||
world.Remove(taken);
|
||||
Box3DSoaParticleTests.Run(world, 1);
|
||||
var unknown = valid;
|
||||
unknown.Flags = 8u;
|
||||
AssertRefusedWhole(world, [unknown], "1", "an unknown flag bit"); // status INVALID_ARGUMENT, no lane changed
|
||||
}
|
||||
|
||||
/// <summary>One Fella's flesh in the probe's counts: 661 particles (a 22 x 30 sheet and one more), a distance per sheet link, every particle attached to one of 19 bones.</summary>
|
||||
private static double Spawn(int fellas, bool batch)
|
||||
{
|
||||
const int per = 661, sheet = 660;
|
||||
using var world = Box3DSoaParticleTests.World(bodies: 19 * fellas + 1, particles: per * fellas + 8, distances: 1300 * fellas, bends: 8,
|
||||
attachments: per * fellas, tethers: 8, gravityY: 0f);
|
||||
var bones = new int[19 * fellas];
|
||||
for (var b = 0; b < bones.Length; b++) bones[b] = world.AddCapsule((ulong)(b + 1), (0.12f * (b % 19), 0f, 0.5f * (b / 19)), 0.05f, 0.1f, 100f);
|
||||
var all = new List<Box3DSoaAttachmentDesc>();
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
for (var f = 0; f < fellas; f++)
|
||||
{
|
||||
var desc = new Box3DSoaParticleDesc[per];
|
||||
for (var k = 0; k < per; k++)
|
||||
desc[k] = new Box3DSoaParticleDesc((0.04f * (k % 22), 0.04f * (k / 22), 0.5f * f), ParticleMass, ParticleRadius, Box3DSoaPhase.Of((uint)(f + 1), noParticleContact: true));
|
||||
var p = new Box3DSoaParticleHandle[per];
|
||||
world.CreateParticles(desc, p);
|
||||
var d = new List<Box3DSoaDistanceDesc>();
|
||||
for (var k = 0; k < sheet; k++)
|
||||
{
|
||||
if (k % 22 != 21 && k + 1 < sheet) d.Add(new(p[k], p[k + 1]));
|
||||
if (k + 22 < sheet) d.Add(new(p[k], p[k + 22]));
|
||||
}
|
||||
world.CreateDistances(d.ToArray());
|
||||
for (var k = 0; k < per; k++)
|
||||
{
|
||||
var bone = bones[19 * f + k % 19];
|
||||
all.Add(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, p[k], bone, (desc[k].X - 0.12f * (k % 19), desc[k].Y, desc[k].Z - 0.5f * f), compliance: 1e-4f, limb: true, oneWay: k % 2 == 0));
|
||||
}
|
||||
}
|
||||
if (batch) world.Attach(all.ToArray());
|
||||
else foreach (var a in all) AttachOne(world, a);
|
||||
return watch.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attach_spawn_cost_line()
|
||||
{
|
||||
// The 256-attachment sheet as 256 single attaches and as one batch, alternately 5 times; then Fella-scale spawns (661 attachments each, one and
|
||||
// four) the same way, 3 times, the whole spawn timed. Printed, no bound: a batch ending in one derivation against one per attachment.
|
||||
static double Median(double[] x) { Array.Sort(x); return x[x.Length / 2]; }
|
||||
var single = new double[5]; var batch = new double[5];
|
||||
for (var r = 0; r < 5; r++)
|
||||
{
|
||||
foreach (var asBatch in r % 2 == 0 ? new[] { false, true } : new[] { true, false })
|
||||
{
|
||||
var (world, descs) = SheetOnCapsules();
|
||||
using (world)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
if (asBatch) world.Attach(descs);
|
||||
else foreach (var d in descs) AttachOne(world, d);
|
||||
(asBatch ? batch : single)[r] = watch.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
var line = $"ATTACH_SPAWN 256 attachments: singles median {F(Median(single))} ms, one batch {F(Median(batch))} ms";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
foreach (var fellas in new[] { 1, 4 })
|
||||
{
|
||||
var s = new double[3]; var b = new double[3];
|
||||
for (var r = 0; r < 3; r++)
|
||||
{
|
||||
s[r] = Spawn(fellas, false);
|
||||
b[r] = Spawn(fellas, true);
|
||||
}
|
||||
var fella = $"FELLA_SPAWN {fellas} Fella(s), {661 * fellas} attachments, whole spawn: singles median {F(Median(s))} ms, batched attach median {F(Median(b))} ms";
|
||||
Console.Error.WriteLine(fella);
|
||||
Reading(fella);
|
||||
}
|
||||
Assert.True(Median(batch) > 0);
|
||||
}
|
||||
|
||||
// Bounds by lodur:ruling:deterministic-bound-margin and deterministic-bound-zero-reading (the unit is 1 um; a shipped zero counts as half a unit).
|
||||
// The mutants, each a one-line change to ymir_particles.c or ymir_box3d_soa.c, and what separates them:
|
||||
// Mo end_push books on a ONE_WAY body the box's speed reads 400 m/s: Assert.Equal(0f, speed) and the impulse lane 310
|
||||
// Mw end_w weighs a ONE_WAY body particle deviation below
|
||||
// Mb the batch's back-out skips the lanes A_batch_past_the_free_lanes_or_the_tether_capacity fails (a reused tombstone reads live)
|
||||
// Mv only the first desc validated A_batch_with_one_bad_desc fails; Mq ONE_WAY accepted on STATIC: both refusal tests fail
|
||||
// Ms the removed-body check on the first desc only: A_batch_with_one_bad_desc fails
|
||||
// Mc the cursor not advanced: reads identical (lane k is live once written, so the scan skips it): a cost-only equivalent mutant, unclaimed.
|
||||
// Mr a rederive per desc: cost only (the cost line), unclaimed.
|
||||
// OneWayDeviation: shipped worst 0 (-> 5e-7), least claimed mutant Mw 2.17828e-3, separation 4357; bound sqrt(5e-7 x 2.17828e-3).
|
||||
private const float OneWayDeviation = 3.3e-5f;
|
||||
// OneWayTetherLoad: shipped worst 0 (-> 5e-7), least claimed mutant Mtether 0.77 (pair branch; 0.93 particle branch), separation 1.5e6; bound sqrt(5e-7 x 0.77).
|
||||
// Mtether the ONE_WAY guard moved out of end_w/end_push into solve_attachments alone: only A_one_way_tether_books_nothing_* fails.
|
||||
// Mmask the unknown-bit clause deleted: only A_flag_bit_outside_the_known_mask_is_refused fails.
|
||||
private const float OneWayTetherLoad = 6e-4f;
|
||||
}
|
||||
797
tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingTests.cs
Normal file
797
tests/Ymir.Box3D.Soa.Tests/Box3DSoaCouplingTests.cs
Normal file
|
|
@ -0,0 +1,797 @@
|
|||
using System.Globalization;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>
|
||||
/// Particles and bodies coupled inside Box3D's substep (docs/soa-world.md, particle section): a held weight stays held,
|
||||
/// momentum and energy are kept through a throw and a snap, and a release takes effect in its step. The ropes are built
|
||||
/// by a test-local builder. Every reading the tests judge is also appended to the file named by YMIR_READINGS when set.
|
||||
/// </summary>
|
||||
public sealed partial class Box3DSoaCouplingTests
|
||||
{
|
||||
private const float Dt = Box3DSoaParticleTests.Dt;
|
||||
private const int Sub = Box3DSoaParticleTests.Sub;
|
||||
private const float G = 10f;
|
||||
private const float ParticleMass = Box3DSoaParticleTests.ParticleMass;
|
||||
private const float ParticleRadius = Box3DSoaParticleTests.ParticleRadius;
|
||||
private const float Spacing = Box3DSoaParticleTests.Spacing;
|
||||
|
||||
private static void Reading(string line)
|
||||
{
|
||||
var path = Environment.GetEnvironmentVariable("YMIR_READINGS");
|
||||
if (!string.IsNullOrEmpty(path)) File.AppendAllText(path, line + "\n");
|
||||
}
|
||||
|
||||
private static string F(double x) => x.ToString("G6", CultureInfo.InvariantCulture);
|
||||
private static Pos[] Line(Pos from, Pos step, int count) => Graph.Line(from, step, count);
|
||||
private static float Dens(float mass, float radius) => Graph.Dens(mass, radius);
|
||||
private static float Sq(float x) => x * x;
|
||||
private static Box3DSoaWorld World(float gravityX = 0f) => Box3DSoaParticleTests.World(gravityX: gravityX, gravityY: -G);
|
||||
private static void Run(Box3DSoaWorld world, int steps) => Box3DSoaParticleTests.Run(world, steps);
|
||||
|
||||
/// <summary>A rope of 48 particles hanging from a static point with a sphere of <paramref name="mass"/> tied under its end.</summary>
|
||||
internal static (int Sphere, Box3DSoaConstraintHandle Top, Box3DSoaConstraintHandle Bottom, Made Rope) Hung(
|
||||
Box3DSoaWorld world, float mass, float radius = 0.1f, Pos velocity = default)
|
||||
{
|
||||
var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48);
|
||||
var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius);
|
||||
var top = world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true);
|
||||
var end = positions[47];
|
||||
var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Dens(mass, radius), velocity: velocity);
|
||||
var bottom = world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true);
|
||||
return (sphere, top, bottom, rope);
|
||||
}
|
||||
|
||||
/// <summary>Kinetic and potential energy of the particles and of the listed spheres (translation and spin), gravity along -y.</summary>
|
||||
private static double Energy(Box3DSoaView v, params (int Lane, float Mass, float Radius)[] spheres)
|
||||
{
|
||||
double e = 0;
|
||||
for (var i = 0; i < v.ParticleCount; i++)
|
||||
{
|
||||
if (v.ParticleLive[i] == 0 || v.ParticleInvMass[i] <= 0f) continue;
|
||||
double m = 1.0 / v.ParticleInvMass[i];
|
||||
e += 0.5 * m * (Sq(v.ParticleVx[i]) + Sq(v.ParticleVy[i]) + Sq(v.ParticleVz[i])) + m * G * v.ParticleY[i];
|
||||
}
|
||||
foreach (var (lane, m, r) in spheres)
|
||||
{
|
||||
var inertia = 0.4 * m * r * r;
|
||||
e += 0.5 * m * (Sq(v.VelocityX[lane]) + Sq(v.VelocityY[lane]) + Sq(v.VelocityZ[lane]))
|
||||
+ 0.5 * inertia * (Sq(v.AngularVelocityX[lane]) + Sq(v.AngularVelocityY[lane]) + Sq(v.AngularVelocityZ[lane]))
|
||||
+ m * G * v.PositionY[lane];
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
private static double ParticleMomentumX(Box3DSoaView v)
|
||||
{
|
||||
double p = 0;
|
||||
for (var i = 0; i < v.ParticleCount; i++)
|
||||
if (v.ParticleLive[i] != 0 && v.ParticleInvMass[i] > 0f) p += v.ParticleVx[i] / v.ParticleInvMass[i];
|
||||
return p;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Attached_end_stays_on_its_point()
|
||||
{
|
||||
// The end particle is tied to the sphere's top and skips that sphere in contact. A contact that pushed it off its own body would read as a gap of its radius (12 mm).
|
||||
using var world = World();
|
||||
var (sphere, _, _, _) = Hung(world, 1f);
|
||||
var view = world.View;
|
||||
const float radius = 0.1f;
|
||||
var worst = 0f;
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
if (i < 10) continue;
|
||||
float qx = view.RotationX[sphere], qy = view.RotationY[sphere], qz = view.RotationZ[sphere], qw = view.RotationW[sphere];
|
||||
var tx = 2f * (qy * 0f - qz * radius); var ty = 2f * (qz * 0f - qx * 0f); var tz = 2f * (qx * radius - qy * 0f);
|
||||
var px = view.PositionX[sphere] + qw * tx + (qy * tz - qz * ty);
|
||||
var py = view.PositionY[sphere] + radius + qw * ty + (qz * tx - qx * tz);
|
||||
var pz = view.PositionZ[sphere] + qw * tz + (qx * ty - qy * tx);
|
||||
worst = MathF.Max(worst, MathF.Sqrt(Sq(view.ParticleX[47] - px) + Sq(view.ParticleY[47] - py) + Sq(view.ParticleZ[47] - pz)));
|
||||
}
|
||||
Reading($"ATTACHED_END worst gap {F(worst)} m");
|
||||
Assert.True(worst < 1e-4f, $"the end particle sat {worst} m from its body point");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tethers_hold_the_rest_path()
|
||||
{
|
||||
// A 70 kg particle at the end of a 48-particle rope from a static point: no particle may be farther from the
|
||||
// attachment than the rest path to it, however the load is routed.
|
||||
using var world = World();
|
||||
var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48);
|
||||
var masses = new float[48];
|
||||
Array.Fill(masses, ParticleMass);
|
||||
masses[47] = 70f;
|
||||
var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius, masses: masses);
|
||||
world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true);
|
||||
var view = world.View;
|
||||
var worst = 0f;
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
for (var k = 1; k < 48; k++)
|
||||
worst = MathF.Max(worst, MathF.Sqrt(Sq(view.ParticleX[k] - positions[0].X) + Sq(view.ParticleY[k] - positions[0].Y) + Sq(view.ParticleZ[k] - positions[0].Z)) - k * Spacing);
|
||||
}
|
||||
Reading($"TETHER_BOUND worst overshoot {F(worst)} m");
|
||||
Assert.True(worst < 1e-5f, $"a particle sits {worst} m past its rest path");
|
||||
}
|
||||
|
||||
// ---- momentum and energy ---------------------------------------------------------------------------------
|
||||
|
||||
[Theory]
|
||||
[InlineData(5f)]
|
||||
[InlineData(70f)]
|
||||
public void Free_throw_keeps_momentum(float mass)
|
||||
{
|
||||
// A sphere thrown at 5 m/s with a 48 x 20 g rope tied behind it, the rope at rest: x momentum is M x 5 for good.
|
||||
const float radius = 0.1f;
|
||||
using var world = World();
|
||||
var rope = Graph.Rope(world, Line((0f, 10f, 0f), (-Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius);
|
||||
var sphere = world.AddSphere(10, (radius, 10f, 0f), radius, Dens(mass, radius), velocity: (5f, 0f, 0f));
|
||||
world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, (-radius, 0f, 0f), tether: true);
|
||||
var view = world.View;
|
||||
var floor = 0.95 * mass * 5.0 / (mass + 48 * ParticleMass);
|
||||
double e0 = 0, worstMomentum = 0, worstEnergy = double.MinValue, firstVx = 0;
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
var momentum = mass * view.VelocityX[sphere] + ParticleMomentumX(view);
|
||||
var energy = Energy(view, (sphere, mass, radius));
|
||||
if (i == 0) { e0 = energy; firstVx = view.VelocityX[sphere]; }
|
||||
worstMomentum = Math.Max(worstMomentum, Math.Abs(momentum - mass * 5.0) / (mass * 5.0));
|
||||
worstEnergy = Math.Max(worstEnergy, energy - e0);
|
||||
}
|
||||
Reading($"FREE_THROW M={mass} vx after tick 0 {F(firstVx)} (floor {F(floor)}) worst momentum error {F(worstMomentum)} worst energy over tick 0 {F(worstEnergy)} J");
|
||||
Assert.True(firstVx >= floor, $"the body kept {firstVx} m/s after one tick, at least {floor} expected");
|
||||
Assert.True(worstMomentum < 1e-3, $"x momentum drifted by {worstMomentum:P3}");
|
||||
Assert.True(worstEnergy < 0.01, $"the system gained {worstEnergy} J");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(5f)]
|
||||
[InlineData(70f)]
|
||||
public void Throw_up_apex(float mass)
|
||||
{
|
||||
const float radius = 0.1f;
|
||||
using var world = World();
|
||||
var rope = Graph.Rope(world, Line((0f, 10f - radius, 0f), (0f, -Spacing, 0f), 48), ParticleMass, ParticleRadius); // hangs below the body
|
||||
var sphere = world.AddSphere(10, (0f, 10f, 0f), radius, Dens(mass, radius), velocity: (0f, 5f, 0f));
|
||||
world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, (0f, -radius, 0f), tether: true);
|
||||
var view = world.View;
|
||||
var apex = 10f;
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
apex = MathF.Max(apex, view.PositionY[sphere]);
|
||||
}
|
||||
// The body alone would rise 1.25 m; the rope it picks up from rest takes the momentum it needs.
|
||||
var ratio = mass / (mass + 48 * ParticleMass);
|
||||
var expected = 10f + 1.25f * ratio * ratio;
|
||||
Reading($"THROW_UP M={mass} apex {F(apex)} expected {F(expected)}");
|
||||
Assert.True(MathF.Abs(apex - expected) < 0.01f * (expected - 10f), $"apex {apex}, expected {expected}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Snap_taut_loses_energy()
|
||||
{
|
||||
const float radius = 0.05f;
|
||||
foreach (var mass in new[] { 5f, 70f })
|
||||
{
|
||||
using var world = World();
|
||||
var (sphere, _, _, _) = Hung(world, mass, radius, velocity: (0f, -6f, 0f));
|
||||
var view = world.View;
|
||||
var before = 0.5 * mass * 36.0;
|
||||
double first = 0, worst = 0, vyAfterOne = 0;
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
var ke = 0.5 * mass * (Sq(view.VelocityX[sphere]) + Sq(view.VelocityY[sphere]) + Sq(view.VelocityZ[sphere]));
|
||||
if (i == 0) { first = ke; vyAfterOne = view.VelocityY[sphere]; }
|
||||
worst = Math.Max(worst, ke);
|
||||
}
|
||||
Reading($"SNAP M={mass} body KE {F(first)} of {F(before)} J after one tick, vy {F(vyAfterOne)}, worst later {F(worst)} J");
|
||||
Assert.True(worst <= before, $"{mass} kg: the body's energy rose to {worst} J from {before} J");
|
||||
if (mass == 5f) Assert.True(first <= 0.05 * before, $"5 kg kept {first} J of {before} J after the snap");
|
||||
else Assert.True(Math.Abs(vyAfterOne) < 0.1, $"70 kg moves at {vyAfterOne} m/s after the snap");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pendulum_gains_no_energy()
|
||||
{
|
||||
// A 45 degree swing for 12 s, the weight as a tied body and as a heavy particle at the rope's end (the control the
|
||||
// solver is known to damp): the body must lose no less than nothing and no more than 1.25 times the control.
|
||||
const float radius = 0.05f;
|
||||
foreach (var mass in new[] { 5f, 70f })
|
||||
{
|
||||
var th = 45f * MathF.PI / 180f;
|
||||
var step = (MathF.Sin(th) * Spacing, -MathF.Cos(th) * Spacing, 0f);
|
||||
double Swing(bool asBody)
|
||||
{
|
||||
using var world = World();
|
||||
var positions = Line((0f, 5f, 0f), step, 48);
|
||||
var masses = new float[48];
|
||||
Array.Fill(masses, ParticleMass);
|
||||
if (!asBody) masses[47] = mass;
|
||||
var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius, masses: masses);
|
||||
world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true);
|
||||
(int, float, float)[] bodies = [];
|
||||
if (asBody)
|
||||
{
|
||||
var end = positions[47];
|
||||
var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Dens(mass, radius));
|
||||
world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true);
|
||||
bodies = [(sphere, mass, radius)];
|
||||
}
|
||||
var view = world.View;
|
||||
double e0 = 0, over = double.MinValue, last = 0;
|
||||
for (var i = 0; i < 12 * 120; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
var e = Energy(view, bodies);
|
||||
if (i == 0) e0 = e;
|
||||
over = Math.Max(over, e - e0);
|
||||
last = e - e0;
|
||||
}
|
||||
Assert.True(over < 0.01, $"{mass} kg {(asBody ? "body" : "control")}: the pendulum gained {over} J");
|
||||
return last;
|
||||
}
|
||||
var body = Swing(true);
|
||||
var control = Swing(false);
|
||||
Reading($"PENDULUM M={mass} body {F(body)} J control {F(control)} J after 12 s");
|
||||
Assert.True(-body <= 1.25 * -control, $"{mass} kg: the body lost {-body} J, the control {-control} J");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_hung_body_keeps_its_spin_about_the_vertical()
|
||||
{
|
||||
const float radius = 0.05f, mass = 5f;
|
||||
using var world = World();
|
||||
var positions = Line((0f, 5f, 0f), (0f, -Spacing, 0f), 48);
|
||||
var rope = Graph.Rope(world, positions, ParticleMass, ParticleRadius);
|
||||
world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: positions[0], tether: true);
|
||||
var end = positions[47];
|
||||
var sphere = world.AddSphere(10, (end.X, end.Y - radius, end.Z), radius, Dens(mass, radius));
|
||||
world.Attach(Box3DSoaAttachKind.Body, rope.Particles[47], sphere, (0f, radius, 0f), tether: true);
|
||||
var inertia = 0.4f * mass * radius * radius;
|
||||
Pos centre = (end.X, end.Y - radius, end.Z);
|
||||
world.ApplyImpulse(sphere, (0f, 0f, 30f * inertia / radius), (centre.X + radius, centre.Y, centre.Z)); // a couple about -y: omega_y = -30
|
||||
world.ApplyImpulse(sphere, (0f, 0f, -30f * inertia / radius), centre);
|
||||
var view = world.View;
|
||||
const float start = -30f;
|
||||
Run(world, 8 * 120);
|
||||
var spin = view.AngularVelocityY[sphere];
|
||||
Reading($"SPIN omega_y {F(start)} -> {F(spin)}");
|
||||
Assert.True(MathF.Abs(spin - start) < 0.01f * MathF.Abs(start), $"the spin went from {start} to {spin} rad/s");
|
||||
}
|
||||
|
||||
// ---- release ---------------------------------------------------------------------------------------------
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Release_takes_effect_in_step(bool destroyParticles)
|
||||
{
|
||||
using var world = World();
|
||||
var (sphere, _, bottom, rope) = Hung(world, 70f);
|
||||
var view = world.View;
|
||||
Run(world, 3 * 120);
|
||||
if (destroyParticles) world.DestroyParticles(rope.Particles); else world.Remove(bottom);
|
||||
var worst = 0f;
|
||||
var impulse = float.MinValue;
|
||||
for (var k = 1; k <= 4; k++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
worst = MathF.Max(worst, MathF.Abs(view.VelocityY[sphere] - (-G * Dt * k)));
|
||||
impulse = MathF.Max(impulse, view.ParticleImpulseY[sphere]);
|
||||
}
|
||||
Reading($"RELEASE destroyParticles={destroyParticles} worst vy error {F(worst)} m/s, greatest impulse Y {F(impulse)}");
|
||||
Assert.True(worst < 0.005f, $"the body is {worst} m/s off free fall in the step after the command");
|
||||
Assert.True(impulse <= 0f, $"the released rope still pushed the body up by {impulse} N s");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Particle_impulse_is_what_Box3D_applied()
|
||||
{
|
||||
// M (v_after - v_before) - M g dt is, per axis, the impulse the particles gave the body this tick: the lane reads exactly that.
|
||||
const float radius = 0.1f;
|
||||
foreach (var thrown in new[] { false, true })
|
||||
{
|
||||
const float mass = 70f;
|
||||
using var world = World();
|
||||
int sphere;
|
||||
if (!thrown) sphere = Hung(world, mass).Sphere;
|
||||
else
|
||||
{
|
||||
var rope = Graph.Rope(world, Line((0f, 10f, 0f), (-Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius);
|
||||
sphere = world.AddSphere(10, (radius, 10f, 0f), radius, Dens(mass, radius), velocity: (5f, 0f, 0f));
|
||||
world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, (-radius, 0f, 0f), tether: true);
|
||||
}
|
||||
var view = world.View;
|
||||
var (vx, vy, vz) = (view.VelocityX[sphere], view.VelocityY[sphere], view.VelocityZ[sphere]);
|
||||
var worst = 0f;
|
||||
for (var i = 0; i < 360; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
var dx = mass * (view.VelocityX[sphere] - vx) - view.ParticleImpulseX[sphere];
|
||||
var dy = mass * (view.VelocityY[sphere] - vy) - mass * -G * Dt - view.ParticleImpulseY[sphere];
|
||||
var dz = mass * (view.VelocityZ[sphere] - vz) - view.ParticleImpulseZ[sphere];
|
||||
worst = MathF.Max(worst, MathF.Max(MathF.Abs(dx), MathF.Max(MathF.Abs(dy), MathF.Abs(dz))));
|
||||
(vx, vy, vz) = (view.VelocityX[sphere], view.VelocityY[sphere], view.VelocityZ[sphere]);
|
||||
}
|
||||
Reading($"IMPULSE_LANE thrown={thrown} worst |M dv - M g dt - lane| {F(worst)} N s (M g dt = {F(mass * G * Dt)})");
|
||||
Assert.True(worst < 1e-3f, $"thrown={thrown}: the lane differs from the body's change by {worst} N s");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- bodies and particles without the pull -------------------------------------------------------------------
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.6f, true)]
|
||||
[InlineData(0f, false)]
|
||||
public void Material_friction_holds_on_a_slope(float friction, bool holds)
|
||||
{
|
||||
// Gravity tilted 20 degrees on a rope lying on a static box: friction 0.6 (above tan 20) holds it, friction 0 lets it go.
|
||||
var tilt = 20f * MathF.PI / 180f;
|
||||
using var world = World(gravityX: G * MathF.Sin(tilt));
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.6f);
|
||||
world.SetMaterial(0, friction);
|
||||
var rope = Graph.Rope(world, Line((0f, ParticleRadius, 0f), (0f, 0f, Spacing), 12), ParticleMass, ParticleRadius);
|
||||
var view = world.View;
|
||||
Run(world, 2 * 120);
|
||||
var slid = MathF.Abs(view.ParticleX[rope.Particles[6]]);
|
||||
Reading($"SLOPE mu={friction} slid {F(slid)} m in 2 s");
|
||||
if (holds) Assert.True(slid < 0.01f, $"friction {friction} let the rope slide {slid} m");
|
||||
else Assert.True(slid > 1f, $"friction 0 slid only {slid} m");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Particles_step_with_no_awake_body()
|
||||
{
|
||||
// Box3D returns early from a world with nothing awake; the particle substeps run all the same.
|
||||
using var world = World();
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f));
|
||||
var rope = Graph.Rope(world, Line((0f, 1f, 0f), (0f, 0f, Spacing), 8), ParticleMass, ParticleRadius);
|
||||
var view = world.View;
|
||||
Run(world, 24); // 0.2 s
|
||||
var fell = 1f - view.ParticleY[rope.Particles[3]];
|
||||
Reading($"NO_AWAKE fell {F(fell)} m in 0.2 s (g t^2 / 2 = 0.2)");
|
||||
Assert.True(MathF.Abs(fell - 0.2f) < 0.02f * 0.2f, $"the rope fell {fell} m, expected 0.2 m");
|
||||
Run(world, 4 * 120);
|
||||
Assert.Equal(ParticleRadius, view.ParticleY[rope.Particles[3]], 1e-3f);
|
||||
Assert.True(MathF.Abs(view.ParticleVy[rope.Particles[3]]) < 1e-3f, "the rope rests on the box");
|
||||
}
|
||||
|
||||
// ---- cost ---------------------------------------------------------------------------------------------------
|
||||
|
||||
[Theory]
|
||||
[InlineData(1, false)]
|
||||
[InlineData(40, false)]
|
||||
[InlineData(1, true)]
|
||||
[InlineData(40, true)]
|
||||
public void Particle_cost_line(int bodies, bool sheet)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(64, gravityY: -G, particles: new Box3DSoaParticleCapacities(16 * 48 + 256, 16 * 47 + 480, 16 * 46 + 448, 16, 600, 1));
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f));
|
||||
for (var b = 1; b < bodies; b++)
|
||||
world.AddSphere((ulong)(100 + b), (0.2f * (b % 8), 0.3f + 0.25f * (b / 8), 0.5f), 0.08f, 800f);
|
||||
for (var c = 0; c < 16; c++) // a pile: ropes zig-zag so particles meet their neighbours' links
|
||||
Graph.Rope(world, Line((0f, 0.5f + 0.03f * c, 0.02f * (c % 4)), (Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius, Box3DSoaPhase.Of((uint)(c + 1), true, true));
|
||||
if (sheet) Graph.Sheet(world, (0.2f, 1.2f, 0f), (0.03f, 0f, 0f), (0f, 0f, 0.03f), 16, 16, ParticleMass, ParticleRadius, Box3DSoaPhase.Of(99, true, true));
|
||||
Run(world, 60);
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
Run(world, 240);
|
||||
var line = $"PARTICLE_COST 16 ropes x 48{(sheet ? " and one 16 x 16 sheet" : "")}, 4 substeps, {bodies} bod{(bodies == 1 ? "y" : "ies")}: {watch.Elapsed.TotalMilliseconds / 240:F3} ms per tick";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
Assert.True(watch.Elapsed.TotalMilliseconds > 0);
|
||||
}
|
||||
|
||||
/// <summary>The 16 x 16 sheet cost scene with one body, plus <paramref name="fluid"/> fluid particles (r 1.25 cm) of XSPH viscosity <paramref name="viscosity"/> poured on the sheet; ms per tick at 4 substeps.</summary>
|
||||
private static double PourCost(int fluid, float viscosity = 0f, int sensors = 0)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(64, gravityY: -G, particles: new Box3DSoaParticleCapacities(16 * 48 + 256 + fluid, 16 * 47 + 480, 16 * 46 + 448, 16, 600, 2, fluid, 0, sensors));
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f));
|
||||
for (var s = 0; s < sensors; s++) world.CreateSensors([(0, (0.35f + 0.1f * s, 1.8f, 0.15f), 0.15f)]); // body-frame y 1.8 is world 1.3: over the block
|
||||
world.SetMaterial(0, 0f, 0, viscosity);
|
||||
for (var c = 0; c < 16; c++)
|
||||
Graph.Rope(world, Line((0f, 0.5f + 0.03f * c, 0.02f * (c % 4)), (Spacing, 0f, 0f), 48), ParticleMass, ParticleRadius, Box3DSoaPhase.Of((uint)(c + 1), true, true));
|
||||
Graph.Sheet(world, (0.2f, 1.2f, 0f), (0.03f, 0f, 0f), (0f, 0f, 0.03f), 16, 16, ParticleMass, ParticleRadius, Box3DSoaPhase.Of(99, true, true));
|
||||
if (fluid > 0)
|
||||
{
|
||||
var nx = 10;
|
||||
var ny = fluid / (nx * nx);
|
||||
if (fluid == 512) { nx = 8; ny = 8; }
|
||||
Graph.Block(world, (0.3f, 1.3f, 0.05f), nx, ny, fluid / (nx * ny), ParticleRadius, 0.015625f, Box3DSoaPhase.Of(200, fluid: true));
|
||||
}
|
||||
Run(world, 60);
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
Run(world, 240);
|
||||
return watch.Elapsed.TotalMilliseconds / 240;
|
||||
}
|
||||
|
||||
/// <summary>Private bytes the world takes for <paramref name="particles"/> particle lanes and a fluid capacity, as the process counts them (the native block is one calloc).</summary>
|
||||
private static long WorldBytes(int particles, int fluid)
|
||||
{
|
||||
GC.Collect();
|
||||
var before = System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64;
|
||||
using var world = new Box3DSoaWorld(4, particles: new Box3DSoaParticleCapacities(particles, 0, 0, 0, 0, 1, fluid));
|
||||
GC.Collect();
|
||||
return System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 - before;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(512)]
|
||||
[InlineData(2000)]
|
||||
public void Fluid_cost_line(int fluid)
|
||||
{
|
||||
// Target at 512: an increment of at most 1.0 ms per tick over the same scene without fluid, at XSPH viscosity 0 and 0.01.
|
||||
const int lanes = 200000;
|
||||
var perLane = (double)WorldBytes(lanes, 0) / lanes;
|
||||
var perFluid = (double)(WorldBytes(lanes, lanes) - WorldBytes(lanes, 0)) / lanes;
|
||||
var memory = $"PARTICLE_COST bytes: {perLane:F0} per particle lane at fluid capacity 0 (the whole block; the fluid copies, nbr_start and nbr_count are 7 x 4 = 28 of it, where h1 carved 388 in every world), {perFluid:F0} more per fluid capacity (the neighbour arena, 96 entries)";
|
||||
Console.Error.WriteLine(memory);
|
||||
Reading(memory);
|
||||
// The one-run difference moves 0.3 ms from run to run, so the line is paired: the scene without fluid and the scene with it
|
||||
// run back to back (the order alternating, so a drifting machine favours neither), and the increment is the median of the pairs'
|
||||
// differences with its interquartile range. Printed, not asserted.
|
||||
const int pairs = 9;
|
||||
foreach (var viscosity in new[] { 0f, 0.01f })
|
||||
{
|
||||
var increments = new double[pairs];
|
||||
var withs = new double[pairs];
|
||||
var withouts = new double[pairs];
|
||||
for (var k = 0; k < pairs; k++)
|
||||
{
|
||||
if (k % 2 == 0) { withouts[k] = PourCost(0); withs[k] = PourCost(fluid, viscosity); }
|
||||
else { withs[k] = PourCost(fluid, viscosity); withouts[k] = PourCost(0); }
|
||||
increments[k] = withs[k] - withouts[k];
|
||||
}
|
||||
Array.Sort(increments);
|
||||
Array.Sort(withs);
|
||||
Array.Sort(withouts);
|
||||
var line = $"PARTICLE_COST {fluid} fluid particles r 1.25 cm viscosity {viscosity} poured on the 16 x 16 sheet scene, 4 substeps, 1 body, {pairs} interleaved pairs: median {withs[pairs / 2]:F3} ms per tick with, {withouts[pairs / 2]:F3} without; fluid increment median {increments[pairs / 2]:F3} ms per tick, IQR {increments[1] / 2 + increments[2] / 2:F3} to {increments[6] / 2 + increments[7] / 2:F3} (min {increments[0]:F3}, max {increments[pairs - 1]:F3})";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
Assert.True(withs[pairs / 2] > 0);
|
||||
}
|
||||
// Four liquid sensors over the pour, paired the same way against the same scene without them (same binary, the order alternating): the sensors' increment.
|
||||
{
|
||||
var increments = new double[pairs];
|
||||
var withs = new double[pairs];
|
||||
var withouts = new double[pairs];
|
||||
for (var k = 0; k < pairs; k++)
|
||||
{
|
||||
if (k % 2 == 0) { withouts[k] = PourCost(fluid); withs[k] = PourCost(fluid, 0f, 4); }
|
||||
else { withs[k] = PourCost(fluid, 0f, 4); withouts[k] = PourCost(fluid); }
|
||||
increments[k] = withs[k] - withouts[k];
|
||||
}
|
||||
Array.Sort(increments);
|
||||
Array.Sort(withs);
|
||||
Array.Sort(withouts);
|
||||
var line = $"PARTICLE_COST {fluid} fluid particles, 4 liquid sensors r 15 cm over the pour, 4 substeps, {pairs} interleaved pairs: median {withs[pairs / 2]:F3} ms per tick with, {withouts[pairs / 2]:F3} without; sensor increment median {increments[pairs / 2]:F3} ms per tick (min {increments[0]:F3}, max {increments[pairs - 1]:F3})";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
Assert.True(withs[pairs / 2] > 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- flesh of a limb tree (YMIR_ATTACH_FLAG_LIMB) --------------------------------------------------------
|
||||
|
||||
private static Pos BodyPoint(Box3DSoaView v, int lane, Pos local)
|
||||
{
|
||||
float qx = v.RotationX[lane], qy = v.RotationY[lane], qz = v.RotationZ[lane], qw = v.RotationW[lane];
|
||||
var tx = 2f * (qy * local.Z - qz * local.Y); var ty = 2f * (qz * local.X - qx * local.Z); var tz = 2f * (qx * local.Y - qy * local.X);
|
||||
return (v.PositionX[lane] + local.X + qw * tx + (qy * tz - qz * ty),
|
||||
v.PositionY[lane] + local.Y + qw * ty + (qz * tx - qx * tz),
|
||||
v.PositionZ[lane] + local.Z + qw * tz + (qx * ty - qy * tx));
|
||||
}
|
||||
|
||||
private static float Gap(Box3DSoaView v, int particle, Pos point) =>
|
||||
MathF.Sqrt(Sq(v.ParticleX[particle] - point.X) + Sq(v.ParticleY[particle] - point.Y) + Sq(v.ParticleZ[particle] - point.Z));
|
||||
|
||||
// Two capsules of one limb tree, side by side with a gap between them (no overlap, no gravity): the upper arm's top cap centre
|
||||
// U = (0, 0.4, 0) and the forearm's bottom cap centre (0.2, 0.5, 0), both of radius 0.1. One particle sits 0.106 m from U toward
|
||||
// the forearm, inside the upper arm's contact reach (0.1 + 0.0125 = 0.1125) and attached to the forearm at its own place.
|
||||
private const float ArmRadius = 0.1f;
|
||||
private static readonly Pos ArmTop = (0f, 0.4f, 0f);
|
||||
private static readonly Pos FlankPoint = (0.0948f, 0.4474f, 0f);
|
||||
|
||||
private static (Box3DSoaWorld World, int Upper, int Fore, Box3DSoaParticleHandle Flesh, Box3DSoaConstraintHandle Attachment, Pos Local) Arm(bool limb)
|
||||
{
|
||||
var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
var upper = world.AddCapsule(1, (0f, 0f, 0f), ArmRadius, 0.4f, 1000f);
|
||||
var fore = world.AddCapsule(2, (0.2f, 0.9f, 0f), ArmRadius, 0.4f, 1000f, parent: upper);
|
||||
var flesh = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc(FlankPoint, ParticleMass, ParticleRadius)], flesh);
|
||||
Pos local = (FlankPoint.X - 0.2f, FlankPoint.Y - 0.9f, FlankPoint.Z);
|
||||
var attachment = world.Attach(Box3DSoaAttachKind.Body, flesh[0], fore, local, limb: limb);
|
||||
return (world, upper, fore, flesh[0], attachment, local);
|
||||
}
|
||||
|
||||
private static float ArmDeviation(bool limb)
|
||||
{
|
||||
var (world, _, fore, flesh, _, local) = Arm(limb);
|
||||
using (world)
|
||||
{
|
||||
var worst = 0f;
|
||||
for (var i = 0; i < 120; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
worst = MathF.Max(worst, Gap(world.View, flesh.Lane, BodyPoint(world.View, fore, local)));
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Limb_flesh_ignores_the_bones_of_its_own_limb()
|
||||
{
|
||||
// The flesh particle is attached to the forearm and lies inside the upper arm's reach. With LIMB the contact skips the whole tree
|
||||
// (the upper arm is the forearm's parent: one root) and the particle stays on its attachment point; without it the upper arm
|
||||
// shoves the particle. Readings are the worst distance of the particle from its attachment point over 120 ticks.
|
||||
var withLimb = ArmDeviation(true);
|
||||
var without = ArmDeviation(false);
|
||||
Reading($"LIMB_FLESH worst deviation from the attachment point with LIMB {F(withLimb)} m, without {F(without)} m");
|
||||
Assert.True(withLimb < LimbBound, $"LIMB flesh sat {withLimb} m off its point");
|
||||
Assert.True(without > PushedFloor, $"the same particle without LIMB sat only {without} m off its point");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Plain_attachment_skips_only_its_own_body_and_a_neighbour_still_collides()
|
||||
{
|
||||
// A two-particle rope at a sphere: the end A is tied inside the sphere without LIMB and stays on its point; B, one link out and
|
||||
// not attached, starts inside the sphere's reach and is pushed out of it. The held list names A's own body and nothing else.
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
const float radius = 0.3f;
|
||||
var sphere = world.AddSphere(1, (0f, 0f, 0f), radius, 1000f);
|
||||
Pos a = (0f, 0.29f, 0f), b = (Spacing, 0.29f, 0f);
|
||||
var rope = Graph.Rope(world, [a, b], ParticleMass, ParticleRadius, bend: -1f);
|
||||
world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], sphere, a);
|
||||
var view = world.View;
|
||||
var worstA = 0f;
|
||||
for (var i = 0; i < 120; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
worstA = MathF.Max(worstA, Gap(view, rope.Particles[0].Lane, BodyPoint(view, sphere, a)));
|
||||
}
|
||||
var lb = rope.Particles[1].Lane;
|
||||
var bFromCentre = MathF.Sqrt(Sq(view.ParticleX[lb] - view.PositionX[sphere]) + Sq(view.ParticleY[lb] - view.PositionY[sphere]) + Sq(view.ParticleZ[lb] - view.PositionZ[sphere]));
|
||||
Reading($"HELD_PLAIN attached end worst gap {F(worstA)} m; neighbour at {F(bFromCentre)} m from the sphere centre (surface plus radius {F(radius + ParticleRadius)})");
|
||||
Assert.True(worstA < HeldGap, $"the attached end sat {worstA} m off its point");
|
||||
var penetration = MathF.Max(0f, radius + ParticleRadius - bFromCentre);
|
||||
Assert.True(penetration < NeighbourDepth, $"the neighbour stayed {penetration} m inside the body's reach");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removing_the_limb_attachment_restores_contact_with_the_tree()
|
||||
{
|
||||
// The held list and limb body are derived at every attachment command: after Remove the particle meets the upper arm again.
|
||||
var (world, upper, _, flesh, attachment, _) = Arm(true);
|
||||
using (world)
|
||||
{
|
||||
Run(world, 30);
|
||||
var view = world.View;
|
||||
var cap = BodyPoint(view, upper, ArmTop);
|
||||
var before = Gap(view, flesh.Lane, cap);
|
||||
world.Remove([attachment]);
|
||||
Run(world, 30);
|
||||
cap = BodyPoint(view, upper, ArmTop);
|
||||
var after = Gap(view, flesh.Lane, cap);
|
||||
Reading($"LIMB_REMOVED distance from the upper arm's cap centre while attached {F(before)} m, 30 ticks after Remove {F(after)} m (surface plus radius {F(ArmRadius + ParticleRadius)})");
|
||||
Assert.True(before < ArmRadius + ParticleRadius, "the LIMB particle was not inside the upper arm's reach to begin with");
|
||||
var depth = MathF.Max(0f, ArmRadius + ParticleRadius - after);
|
||||
Assert.True(depth < RemovedDepth, $"after Remove the particle sat {depth} m inside the upper arm's reach");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Limb_attachment_to_a_world_point_is_refused()
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
var flesh = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, 1f, 0f), ParticleMass, ParticleRadius)], flesh);
|
||||
Assert.ThrowsAny<Exception>(() => world.Attach(Box3DSoaAttachKind.Static, flesh[0], point: (0f, 1f, 0f), limb: true));
|
||||
}
|
||||
|
||||
private static float WorstGap(Box3DSoaWorld world, int body, Pos local, Box3DSoaParticleHandle particle, int steps = 120)
|
||||
{
|
||||
var worst = 0f;
|
||||
for (var i = 0; i < steps; i++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
worst = MathF.Max(worst, Gap(world.View, particle.Lane, BodyPoint(world.View, body, local)));
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Limb_flesh_still_meets_a_body_of_another_tree()
|
||||
{
|
||||
// The arm's flesh particle (LIMB, attached to the forearm) has a sphere of no limb tree beside it, inside its contact reach: the
|
||||
// sphere is not skipped and pushes the particle off its point. Readings are the worst distance from the point over 120 ticks.
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
var upper = world.AddCapsule(1, (0f, 0f, 0f), ArmRadius, 0.4f, 1000f);
|
||||
var fore = world.AddCapsule(2, (0.2f, 0.9f, 0f), ArmRadius, 0.4f, 1000f, parent: upper);
|
||||
world.AddSphere(3, (0.35f, 0.9f, 0f), 0.04f, 1000f);
|
||||
Pos at = (0.306f, 0.9f, 0f);
|
||||
var flesh = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc(at, ParticleMass, ParticleRadius)], flesh);
|
||||
Pos local = (at.X - 0.2f, at.Y - 0.9f, at.Z);
|
||||
world.Attach(Box3DSoaAttachKind.Body, flesh[0], fore, local, limb: true);
|
||||
var worst = WorstGap(world, fore, local, flesh[0]);
|
||||
Reading($"LIMB_FOREIGN worst deviation from the attachment point beside a foreign sphere {F(worst)} m");
|
||||
Assert.True(worst > ForeignFloor, $"the LIMB particle sat only {worst} m off its point beside a foreign body");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Limb_flesh_ignores_every_bone_up_its_chain_not_only_the_parent()
|
||||
{
|
||||
// Three capsules chained grandparent -> parent -> child, spaced 0.5 m. The particle is attached to the child and lies inside the
|
||||
// grandparent's reach: the limb-tree root is two hops from the child, and a walk that stopped at the parent would not skip it.
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
var grand = world.AddCapsule(1, (0f, 0f, 0f), 0.1f, 0.4f, 1000f);
|
||||
var parent = world.AddCapsule(2, (0.5f, 0f, 0f), 0.1f, 0.4f, 1000f, parent: grand);
|
||||
var child = world.AddCapsule(3, (1.0f, 0f, 0f), 0.1f, 0.4f, 1000f, parent: parent);
|
||||
Pos at = (0.106f, 0f, 0f);
|
||||
var flesh = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc(at, ParticleMass, ParticleRadius)], flesh);
|
||||
Pos local = (at.X - 1.0f, at.Y, at.Z);
|
||||
world.Attach(Box3DSoaAttachKind.Body, flesh[0], child, local, limb: true);
|
||||
var worst = WorstGap(world, child, local, flesh[0]);
|
||||
Reading($"LIMB_CHAIN worst deviation from the attachment point, grandparent in reach {F(worst)} m");
|
||||
Assert.True(worst < ChainBound, $"the LIMB particle sat {worst} m off its point beside its grandparent");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_particle_created_after_an_attachment_does_not_skip_the_first_body()
|
||||
{
|
||||
// Creating particles rederives the held lists of the lanes that carry no attachment; a lane left at the zeroed arena's limb_body 0
|
||||
// would skip body 0's whole tree. The late particle sits inside sphere 0's reach and is pushed out of it.
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
const float radius = 0.3f;
|
||||
var sphere = world.AddSphere(1, (0f, 0f, 0f), radius, 1000f);
|
||||
var first = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, 2f, 0f), ParticleMass, ParticleRadius)], first);
|
||||
world.Attach(Box3DSoaAttachKind.Body, first[0], sphere, (0f, 2f, 0f));
|
||||
var late = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0.29f, 0f, 0f), ParticleMass, ParticleRadius)], late);
|
||||
Run(world, 60);
|
||||
var view = world.View;
|
||||
var fromCentre = MathF.Sqrt(Sq(view.ParticleX[late[0].Lane] - view.PositionX[sphere]) + Sq(view.ParticleY[late[0].Lane] - view.PositionY[sphere]) + Sq(view.ParticleZ[late[0].Lane] - view.PositionZ[sphere]));
|
||||
var depth = MathF.Max(0f, radius + ParticleRadius - fromCentre);
|
||||
Reading($"LIMB_LATE depth of the late particle inside the sphere's reach after 60 ticks {F(depth)} m");
|
||||
Assert.True(depth < LateDepth, $"the late particle stayed {depth} m inside body 0's reach");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_refused_attachment_leaves_the_held_lanes_as_they_were()
|
||||
{
|
||||
// A rope end beside the upper arm; the attach to the forearm asks for a tether, which the world has no capacity for, and is
|
||||
// refused. The refused command must leave the particle's held list and limb body untouched: the end then drifts exactly as in the
|
||||
// run that never tried. Readings are the end's distance from its start after 120 ticks, control and after the refusal.
|
||||
float Displacement(bool tryRefused)
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f, tethers: 1, particles: 16, distances: 16, bends: 16);
|
||||
var upper = world.AddCapsule(1, (0f, 0f, 0f), ArmRadius, 0.4f, 1000f);
|
||||
var fore = world.AddCapsule(2, (0.2f, 0.9f, 0f), ArmRadius, 0.4f, 1000f, parent: upper);
|
||||
var f = FlankPoint;
|
||||
var rope = Graph.Rope(world, [f, (f.X, f.Y, f.Z + 0.03f), (f.X, f.Y, f.Z + 0.06f), (f.X, f.Y, f.Z + 0.09f)], ParticleMass, ParticleRadius, bend: -1f);
|
||||
if (tryRefused)
|
||||
Assert.ThrowsAny<Exception>(() => world.Attach(Box3DSoaAttachKind.Body, rope.Particles[0], fore, (f.X - 0.2f, f.Y - 0.9f, f.Z), limb: true, tether: true));
|
||||
Run(world, 120);
|
||||
var v = world.View;
|
||||
var l = rope.Particles[0].Lane;
|
||||
return MathF.Sqrt(Sq(v.ParticleX[l] - f.X) + Sq(v.ParticleY[l] - f.Y) + Sq(v.ParticleZ[l] - f.Z));
|
||||
}
|
||||
var control = Displacement(false);
|
||||
var refused = Displacement(true);
|
||||
Reading($"LIMB_REFUSED rope end displacement control {F(control)} m, after a refused LIMB+TETHER attach {F(refused)} m");
|
||||
Assert.True(MathF.Abs(refused - control) < RefusedBound, $"a refused attach moved the end {MathF.Abs(refused - control)} m from the control run");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Limb_attachments_across_two_trees_skip_only_the_lowest_attachments_tree()
|
||||
{
|
||||
// The documented limit: a particle's LIMB attachments to bodies of two trees skip only the tree of its lowest live LIMB attachment
|
||||
// (the first made); the other tree's bones collide, except the bodies the particle is attached to. Two limbs, A (a1 -> x) and
|
||||
// B (a2 -> y); one particle per world is attached to x first and then y, and sits at its own place beside a1 or beside a2.
|
||||
static float Worst(bool besideSecondTree)
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(gravityY: 0f);
|
||||
world.AddCapsule(1, (0f, 0f, 0f), 0.1f, 0.4f, 1000f);
|
||||
var x = world.AddCapsule(2, (0f, 2f, 0f), 0.1f, 0.4f, 1000f, parent: 0);
|
||||
world.AddCapsule(3, (1f, 0f, 0f), 0.1f, 0.4f, 1000f);
|
||||
var y = world.AddCapsule(4, (1f, 2f, 0f), 0.1f, 0.4f, 1000f, parent: 2);
|
||||
Pos at = besideSecondTree ? (1.106f, 0f, 0f) : (0.106f, 0f, 0f);
|
||||
var flesh = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc(at, ParticleMass, ParticleRadius)], flesh);
|
||||
Pos onX = (at.X, at.Y - 2f, at.Z);
|
||||
world.Attach(Box3DSoaAttachKind.Body, flesh[0], x, onX, limb: true);
|
||||
world.Attach(Box3DSoaAttachKind.Body, flesh[0], y, (at.X - 1f, at.Y - 2f, at.Z), limb: true);
|
||||
return WorstGap(world, x, onX, flesh[0]);
|
||||
}
|
||||
var skipped = Worst(false);
|
||||
var other = Worst(true);
|
||||
Reading($"LIMB_TWO_TREES worst deviation beside the skipped tree's bone {F(skipped)} m, beside the other tree's bone {F(other)} m");
|
||||
Assert.True(skipped < TwoTreesBound, $"the skipped tree's bone moved the particle {skipped} m");
|
||||
Assert.True(other > TwoTreesFloor, $"the other tree's bone moved the particle only {other} m");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Held_body_contact_cost_reading()
|
||||
{
|
||||
// 600 particles, each attached (plain) to one of 19 capsules in a row and so skipping that body, every particle in reach of its
|
||||
// neighbours' bodies: the tick's cost, median of repeated runs of one scene. Printed, no bound.
|
||||
const int bodies = 19, count = 600, reps = 7;
|
||||
static double OneRun()
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(bodies: bodies + 1, particles: count, distances: 1, bends: 1, attachments: count, tethers: 1, gravityY: 0f);
|
||||
var lanes = new int[bodies];
|
||||
for (var k = 0; k < bodies; k++) lanes[k] = world.AddCapsule((ulong)(k + 1), (0.12f * k, 0f, 0f), 0.05f, 0.15f, 1000f);
|
||||
var desc = new Box3DSoaParticleDesc[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var k = i % bodies;
|
||||
var ang = 6.2831853f * (i / bodies) / (count / bodies + 1);
|
||||
desc[i] = new Box3DSoaParticleDesc((0.12f * k + 0.04f * MathF.Cos(ang), 0.2f * MathF.Sin(ang), 0.04f * MathF.Sin(ang)), ParticleMass, ParticleRadius);
|
||||
}
|
||||
var handles = new Box3DSoaParticleHandle[count];
|
||||
world.CreateParticles(desc, handles);
|
||||
for (var i = 0; i < count; i++)
|
||||
world.Attach(Box3DSoaAttachKind.Body, handles[i], lanes[i % bodies], (desc[i].X - 0.12f * (i % bodies), desc[i].Y, desc[i].Z));
|
||||
Run(world, 10);
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
Run(world, 60);
|
||||
return sw.Elapsed.TotalMilliseconds / 60.0;
|
||||
}
|
||||
var runs = new double[reps];
|
||||
for (var k = 0; k < reps; k++) runs[k] = OneRun();
|
||||
Array.Sort(runs);
|
||||
var line = $"HELD_COST {count} particles attached to {bodies} capsules, 4 substeps: median {F(runs[reps / 2])} ms per tick (min {F(runs[0])}, max {F(runs[reps - 1])})";
|
||||
Console.Error.WriteLine(line);
|
||||
Reading(line);
|
||||
Assert.True(runs[reps / 2] > 0);
|
||||
}
|
||||
|
||||
// Bounds, by lodur:ruling:deterministic-bound-margin and deterministic-bound-zero-reading: the geometric mean of the shipped worst and the
|
||||
// least claimed mutant (a shipped zero counts as half a unit, a mutant zero as one unit; the unit is 1 um). The mutants, each a one-line
|
||||
// change to ymir_particles.c, and their readings (metres):
|
||||
// Ml the LIMB root compare deleted Mr the compare against the attached body's lane instead of its root
|
||||
// Mx the root skip applied to every particle Mb held_by true for any particle with a list
|
||||
// Mh the held list read as empty Mp limb_body not reset when the list is rederived
|
||||
// LimbBound: shipped worst 0 (-> 5e-7), least claimed mutant Ml = Mr 6.2855e-3, separation 12571; bound sqrt(5e-7 x 6.2855e-3).
|
||||
private const float LimbBound = 5.6e-5f;
|
||||
// PushedFloor: shipped (no LIMB) 6.2855e-3, least claimed mutant Mx = Mb 0 (-> 1e-6), separation 6285; floor sqrt(6.2855e-3 x 1e-6).
|
||||
private const float PushedFloor = 7.9e-5f;
|
||||
// The attached end's worst gap while its neighbour is pushed: shipped 4.66652e-3 (the rope link pulls it), least claimed mutant Mh 2.26468e-2,
|
||||
// separation 4.85; bound sqrt(4.66652e-3 x 2.26468e-2) = 1.028e-2. Held tests (b) sit in Plain_attachment_skips_only_its_own_body_*.
|
||||
private const float HeldGap = 1.028e-2f;
|
||||
// The neighbour's depth inside the sphere's reach at the end: shipped 0 (-> 5e-7), least claimed mutant Mx 2.0952e-2; bound sqrt(5e-7 x 2.0952e-2).
|
||||
private const float NeighbourDepth = 1.02e-4f;
|
||||
// The particle's depth inside the upper arm's reach 30 ticks after Remove: shipped 0 (-> 5e-7), least claimed mutant Mp 6.51e-3; bound sqrt(5e-7 x 6.51e-3).
|
||||
private const float RemovedDepth = 5.7e-5f;
|
||||
// Bounds of the s1 fix batch, by the same rules (the unit is 1 um; a shipped or mutant zero is half a unit or one unit). The mutants:
|
||||
// Mg3 every body's limb-tree root set to 0 ML1 the root compare dropped, every body skipped once the particle has a limb body
|
||||
// Mg2 the root walk stopped after one hop Mi the ISOLATED reset of limb_body deleted
|
||||
// Mx the held lists written before the tether-capacity check Ml3 the highest LIMB attachment decides the skipped tree
|
||||
// ForeignFloor: shipped 3.52192e-3, least claimed mutant Mg3 = ML1 0 (-> 1e-6), separation 3522; floor sqrt(3.52192e-3 x 1e-6).
|
||||
private const float ForeignFloor = 5.9e-5f;
|
||||
// ChainBound: shipped 0 (-> 5e-7), Mg2 6.41614e-3, separation 12832; bound sqrt(5e-7 x 6.41614e-3).
|
||||
private const float ChainBound = 5.7e-5f;
|
||||
// LateDepth: shipped 0 (-> 5e-7), Mi 0.0225, separation 45000; bound sqrt(5e-7 x 0.0225).
|
||||
private const float LateDepth = 1.06e-4f;
|
||||
// RefusedBound, on the gap between the run after a refusal and the control run: shipped 0 (-> 5e-7), Mx 0.118058 (0.343645 - 0.225587),
|
||||
// separation 236116; bound sqrt(5e-7 x 0.118058).
|
||||
private const float RefusedBound = 2.43e-4f;
|
||||
// TwoTreesBound: shipped 7.5e-9 (-> 5e-7), least claimed mutant Ml3 6.76838e-3, separation 13537; bound sqrt(5e-7 x 6.76838e-3).
|
||||
private const float TwoTreesBound = 5.8e-5f;
|
||||
// TwoTreesFloor: shipped 5.90668e-3, least claimed mutant Ml3 = Mg3 = ML1 0 (-> 1e-6), separation 5907; floor sqrt(5.90668e-3 x 1e-6).
|
||||
private const float TwoTreesFloor = 7.7e-5f;
|
||||
}
|
||||
875
tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs
Normal file
875
tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs
Normal file
|
|
@ -0,0 +1,875 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Fluid as a phase bit of the one particle solver: docs/soa-world.md, particles section, Fluid.</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
private const float Dt = Box3DSoaParticleTests.Dt;
|
||||
private const int Sub = Box3DSoaParticleTests.Sub;
|
||||
private static readonly uint FluidPhase = Box3DSoaPhase.Of(0, fluid: true);
|
||||
|
||||
private static Box3DSoaParticleDesc Fluid(Pos at, float mass = 0.02f, float radius = 0.0125f, Pos velocity = default, uint material = 0) =>
|
||||
new(at, mass, radius, FluidPhase, material, null, velocity);
|
||||
|
||||
private sealed record Graphs(int Count, int[] Att, int[] Particle, int[] Parent, int[] Edge, int[] Other, float[] Bound, int[] Component);
|
||||
|
||||
private static Graphs Snapshot(Box3DSoaView v) =>
|
||||
new(v.TetherCount, v.TetherAttachment.ToArray(), v.TetherParticle.ToArray(), v.TetherParent.ToArray(), v.TetherEdge.ToArray(),
|
||||
v.TetherOther.ToArray(), v.TetherBound.ToArray(), v.ParticleComponent.ToArray());
|
||||
|
||||
private static void SameTethers(Graphs a, Graphs b)
|
||||
{
|
||||
Assert.Equal(a.Count, b.Count);
|
||||
Assert.Equal(a.Att, b.Att);
|
||||
Assert.Equal(a.Particle, b.Particle);
|
||||
Assert.Equal(a.Parent, b.Parent);
|
||||
Assert.Equal(a.Edge, b.Edge);
|
||||
Assert.Equal(a.Other, b.Other);
|
||||
Assert.True(a.Bound.AsSpan().SequenceEqual(b.Bound), "tether bounds differ");
|
||||
}
|
||||
|
||||
private const float R = 0.0125f;
|
||||
private const float FluidMass = 0.015625f; // (2 r)^3 of water: 15.6 mL
|
||||
|
||||
private static Box3DSoaWorld FluidWorld(int particles, int bodies = 8, float gravityY = -10f, int materials = 2, int wets = 0, int sensors = 0) =>
|
||||
new(bodies, gravityY: gravityY, particles: new Box3DSoaParticleCapacities(particles, 16, 16, 16, 64, materials, particles, wets, sensors));
|
||||
|
||||
/// <summary>A floor and four walls: an open well of interior half-width <paramref name="half"/> centred on the y axis.</summary>
|
||||
private static void Well(Box3DSoaWorld world, float half)
|
||||
{
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (half + 0.25f, 1f, 0f), (0.25f, 1f, 1f), friction: 0.3f);
|
||||
world.AddStaticBox(3, (-half - 0.25f, 1f, 0f), (0.25f, 1f, 1f), friction: 0.3f);
|
||||
world.AddStaticBox(4, (0f, 1f, half + 0.25f), (1f, 1f, 0.25f), friction: 0.3f);
|
||||
world.AddStaticBox(5, (0f, 1f, -half - 0.25f), (1f, 1f, 0.25f), friction: 0.3f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_capacity_refuses_a_batch_whole()
|
||||
{
|
||||
// The fluid capacity sizes the neighbour arena: fluid past it is refused before any lane is taken, solids still go in, and a
|
||||
// destroyed fluid particle frees its place at once.
|
||||
using var world = Box3DSoaParticleTests.World(particles: 16, distances: 16, bends: 16, attachments: 4, tethers: 64, fluid: 3);
|
||||
var ps = new Box3DSoaParticleHandle[2];
|
||||
world.CreateParticles([Fluid((0f, 0f, 0f)), Fluid((0.05f, 0f, 0f))], ps);
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateParticles([Fluid((0.1f, 0f, 0f)), Fluid((0.15f, 0f, 0f))]));
|
||||
Assert.Equal(2, world.View.ParticleCount);
|
||||
Assert.Equal(14, world.FreeParticleSlots);
|
||||
world.CreateParticles([new((0f, 0.1f, 0f), 0.02f, 0.0125f), Fluid((0.1f, 0f, 0f))]);
|
||||
Assert.Equal(4, world.View.ParticleCount);
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateParticles([Fluid((0.15f, 0f, 0f))]));
|
||||
world.DestroyParticles([ps[0]]);
|
||||
world.CreateParticles([Fluid((0.15f, 0f, 0f))]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_refusals()
|
||||
{
|
||||
using var world = Box3DSoaParticleTests.World(particles: 16, distances: 16, bends: 16, attachments: 4, tethers: 64, fluid: 16);
|
||||
var ps = new Box3DSoaParticleHandle[3];
|
||||
world.CreateParticles([new((0f, 0f, 0f), 0.02f, 0.0125f), Fluid((0.05f, 0f, 0f)), Fluid((0.1f, 0f, 0f))], ps);
|
||||
var view = world.View;
|
||||
Assert.Equal(FluidPhase, view.ParticlePhase[1]);
|
||||
// a fluid particle holds no distance, bend or attachment; every refusal happens before anything changes
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateDistances([new Box3DSoaDistanceDesc(ps[0], ps[1])]));
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateDistances([new Box3DSoaDistanceDesc(ps[1], ps[2])]));
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(Box3DSoaAttachKind.Static, ps[1], point: (0.05f, 0f, 0f), tether: true));
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(Box3DSoaAttachKind.Static, ps[2], point: (0.1f, 0f, 0f)));
|
||||
Assert.Equal(0, view.DistanceCount);
|
||||
Assert.Equal(0, view.AttachmentCount);
|
||||
Assert.Equal(0, view.TetherCount);
|
||||
Assert.Equal(16, world.FreeDistanceSlots);
|
||||
// the solids still take both
|
||||
var other = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new((0f, 0.05f, 0f), 0.02f, 0.0125f)], other);
|
||||
world.CreateDistances([new Box3DSoaDistanceDesc(ps[0], other[0])]);
|
||||
world.Attach(Box3DSoaAttachKind.Static, ps[0], point: (0f, 0f, 0f), tether: true);
|
||||
Assert.Equal(1, world.View.DistanceCount); // the view is a snapshot of the counts
|
||||
// a viscosity below 0 or not finite is refused, the material as it was
|
||||
world.SetMaterial(1, 0.3f, 7, 0.25f);
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetMaterial(1, 0.3f, 8, -0.01f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetMaterial(1, 0.3f, 8, float.NaN));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetMaterial(1, 0.3f, 8, float.PositiveInfinity));
|
||||
Assert.Equal(0.25f, world.View.MaterialViscosity[1]);
|
||||
Assert.Equal(7ul, world.View.MaterialTableId[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_emission_keeps_the_graph()
|
||||
{
|
||||
// A 32 x 32 sheet at 20 pins, then 64 fluid particles created every tick for 60 ticks and destroyed the tick after: creating a
|
||||
// particle changes no constraint and destroying fluid touches none, so the tether lanes never change and the full derivation
|
||||
// (3.6 to 4.0 ms on the 20th pin) is never run for them.
|
||||
using var world = Box3DSoaParticleTests.World(particles: 1024 + 256, distances: 2048, bends: 2048, attachments: 32, tethers: 4096, fluid: 1024);
|
||||
const float sp = 0.04f;
|
||||
var sheet = Graph.Sheet(world, (0f, 2f, 0f), (sp, 0f, 0f), (0f, -sp, 0f), 32, 32, 0.02f, 0.02f);
|
||||
var held = new HashSet<int>();
|
||||
for (var a = 0; a < 20; a++)
|
||||
{
|
||||
var i = a == 0 ? 0 : a == 1 ? 31 : a * 37 % 1024;
|
||||
if (held.Add(i)) world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[i], point: (i % 32 * sp, 2f - i / 32 * sp, 0f), tether: true);
|
||||
}
|
||||
var before = Snapshot(world.View);
|
||||
Assert.True(before.Count > 1900, $"{before.Count} tethers");
|
||||
Box3DSoaParticleHandle[]? previous = null;
|
||||
var emit = new TimeSpan();
|
||||
for (var tick = 0; tick < 60; tick++)
|
||||
{
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
if (previous is not null) world.DestroyParticles(previous);
|
||||
var batch = new Box3DSoaParticleDesc[64];
|
||||
for (var k = 0; k < 64; k++) batch[k] = Fluid((5f + 0.05f * (k % 8), 3f + 0.05f * (k / 8), 0.05f * (tick % 4)));
|
||||
var made = new Box3DSoaParticleHandle[64];
|
||||
world.CreateParticles(batch, made);
|
||||
emit += watch.Elapsed;
|
||||
var view = world.View;
|
||||
var now = Snapshot(view);
|
||||
SameTethers(before, now);
|
||||
for (var k = 0; k < 1024; k++) Assert.Equal(before.Component[k], now.Component[k]); // the sheet's components
|
||||
foreach (var h in made) Assert.Equal(h.Lane, view.ParticleComponent[h.Lane]);
|
||||
if (previous is not null) foreach (var h in previous) Assert.Equal(0, view.ParticleComponent[h.Lane]);
|
||||
world.Step(Dt, Sub);
|
||||
previous = made;
|
||||
}
|
||||
world.DestroyParticles(previous!);
|
||||
var last = world.View;
|
||||
SameTethers(before, Snapshot(last));
|
||||
for (var t = 0; t < last.TetherCount; t++) // every tether's parent is present
|
||||
Assert.True(last.TetherParent[t] < t);
|
||||
var line = $"FLUID_EMIT 64 fluid particles created and 64 destroyed per tick on the 20-pin 32 x 32 sheet: {emit.TotalMilliseconds / 60:F3} ms per tick of commands";
|
||||
Console.Error.WriteLine(line);
|
||||
Readings.Add(line);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Destroying_a_lone_attached_particle_leaves_the_tether_lanes_as_before_the_attach()
|
||||
{
|
||||
// A particle with a tether attachment and no distance: does it make a tether lane, and does destroying it leave one behind?
|
||||
using var world = Box3DSoaParticleTests.World(particles: 16, distances: 16, bends: 16, attachments: 4, tethers: 64, fluid: 16);
|
||||
var ps = new Box3DSoaParticleHandle[2];
|
||||
world.CreateParticles([new((0f, 0f, 0f), 0.02f, 0.0125f), new((1f, 0f, 0f), 0.02f, 0.0125f)], ps);
|
||||
var before = Snapshot(world.View);
|
||||
world.Attach(Box3DSoaAttachKind.Static, ps[0], point: (0f, 0f, 0f), tether: true);
|
||||
var held = world.View.TetherCount;
|
||||
world.DestroyParticles([ps[0]]);
|
||||
var line = $"HELD_ATTACHMENT tether lanes {before.Count} before the attach, {held} with a lone tethered particle, {world.View.TetherCount} after destroying it";
|
||||
Readings.Add(line);
|
||||
Console.Error.WriteLine(line);
|
||||
SameTethers(before, Snapshot(world.View));
|
||||
}
|
||||
|
||||
// ---- scenes ---------------------------------------------------------------------------------------------
|
||||
|
||||
private static float Sq(float x) => x * x;
|
||||
|
||||
/// <summary>
|
||||
/// A fluid block thrown at a free 16 x 16 sheet and a 48-rope in zero gravity, nothing pinned: every particle is free, so
|
||||
/// momentum is the whole of it. Masses are per particle.
|
||||
/// </summary>
|
||||
private static Box3DSoaWorld Collision(float fluidMass, float solidMass)
|
||||
{
|
||||
var world = new Box3DSoaWorld(4, gravityY: 0f, particles: new Box3DSoaParticleCapacities(1024, 1024, 1024, 8, 64, 2, 1024));
|
||||
world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f));
|
||||
Graph.Sheet(world, (0f, 0f, 0f), (0.04f, 0f, 0f), (0f, 0.04f, 0f), 16, 16, solidMass, 0.02f, Box3DSoaPhase.Of(7, true, true));
|
||||
Graph.Rope(world, Graph.Line((-0.3f, 0.25f, 0.3f), (0.03f, 0f, 0f), 48), solidMass, 0.0125f, Box3DSoaPhase.Of(8, true, true), bend: 1e-5f);
|
||||
Graph.Block(world, (0.2f, 0.17f, 0.45f), 5, 5, 5, 0.02f, fluidMass, Box3DSoaPhase.Of(9, fluid: true), velocity: (0f, 0f, -4f));
|
||||
return world;
|
||||
}
|
||||
|
||||
/// <summary>Drift of the total momentum over the run as a fraction of its initial size, and the highest kinetic energy over the initial.</summary>
|
||||
private static (double Drift, double EnergyRatio) Momentum(Box3DSoaWorld world, int ticks)
|
||||
{
|
||||
(double X, double Y, double Z, double E) Total()
|
||||
{
|
||||
var v = world.View;
|
||||
double x = 0, y = 0, z = 0, e = 0;
|
||||
for (var i = 0; i < v.ParticleCount; i++)
|
||||
{
|
||||
if (v.ParticleLive[i] == 0 || v.ParticleInvMass[i] == 0f) continue;
|
||||
double m = 1.0 / v.ParticleInvMass[i];
|
||||
x += m * v.ParticleVx[i]; y += m * v.ParticleVy[i]; z += m * v.ParticleVz[i];
|
||||
e += 0.5 * m * (Sq(v.ParticleVx[i]) + Sq(v.ParticleVy[i]) + Sq(v.ParticleVz[i]));
|
||||
}
|
||||
return (x, y, z, e);
|
||||
}
|
||||
var p0 = Total();
|
||||
var emax = p0.E;
|
||||
var worst = 0.0;
|
||||
var mag = Math.Sqrt(p0.X * p0.X + p0.Y * p0.Y + p0.Z * p0.Z);
|
||||
for (var t = 0; t < ticks; t++)
|
||||
{
|
||||
world.Step(1f / 60f, 4);
|
||||
var p = Total();
|
||||
emax = Math.Max(emax, p.E);
|
||||
worst = Math.Max(worst, Math.Sqrt(Sq((float)(p.X - p0.X)) + Sq((float)(p.Y - p0.Y)) + Sq((float)(p.Z - p0.Z))) / mag);
|
||||
}
|
||||
return (worst, emax / p0.E);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Probe scene 3: a 7 x 7 x 7 block above a 16 x 16 sheet tilted down toward +x (pinned at its corners) and a sloped 24-rope. The block is fluid, or
|
||||
/// with <paramref name="solid"/> the same particles flagged solid (group 6, self-collide) as the control.
|
||||
/// </summary>
|
||||
private static (Box3DSoaWorld World, Made Sheet, Made Rope, Box3DSoaParticleHandle[] Fluid) Pour(bool nudge = false, bool solid = false)
|
||||
{
|
||||
var world = new Box3DSoaWorld(4, gravityY: -9.81f, particles: new Box3DSoaParticleCapacities(640, 560, 520, 8, 1024, 2, 640)); // the probe's g
|
||||
world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f));
|
||||
world.SetMaterial(1, 0.3f, 0, 0.01f); // the probe's XSPH coefficient
|
||||
const float sp = 0.04f, r = 0.02f;
|
||||
var sheet = Graph.Sheet(world, (0f, 0.6f, 0f), (sp, -0.012f, 0f), (0f, 0f, sp), 16, 16, 0.02f, r, Box3DSoaPhase.Of(4, true, true), bend: 1e-3f);
|
||||
foreach (var i in new[] { 0, 15, 240, 255 })
|
||||
{
|
||||
var v = world.View;
|
||||
world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[i], point: (v.ParticleX[i], v.ParticleY[i], v.ParticleZ[i])); // plain pins, as the probe's
|
||||
}
|
||||
var line = Graph.Line((0.55f, 0.25f, 0.30f), ((1.40f - 0.55f) / 23f, -0.40f / 23f, 0f), 24);
|
||||
var rope = Graph.Rope(world, line, 0.02f, r, Box3DSoaPhase.Of(5), bend: 1e-5f);
|
||||
world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: line[0], tether: true);
|
||||
world.Attach(Box3DSoaAttachKind.Static, rope.Particles[23], point: line[23], tether: true);
|
||||
var desc = new Box3DSoaParticleDesc[343];
|
||||
for (var a = 0; a < 7; a++) for (var b = 0; b < 7; b++) for (var c = 0; c < 7; c++)
|
||||
desc[(a * 7 + b) * 7 + c] = new Box3DSoaParticleDesc((0.10f + a * sp, 0.75f + b * sp, 0.18f + c * sp), 1000f * sp * sp * sp, r, solid ? Box3DSoaPhase.Of(6, true, false) : Box3DSoaPhase.Of(6, fluid: true), 1);
|
||||
if (nudge) desc[100].X = BitConverter.UInt32BitsToSingle(BitConverter.SingleToUInt32Bits(desc[100].X) + 1);
|
||||
var fluid = new Box3DSoaParticleHandle[desc.Length];
|
||||
world.CreateParticles(desc, fluid);
|
||||
return (world, sheet, rope, fluid);
|
||||
}
|
||||
|
||||
// ---- behaviour ------------------------------------------------------------------------------------------
|
||||
|
||||
// Bounds follow lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped worst and the least claimed mutant, separation >= 1.2.
|
||||
// |mean - 1| at 3 s, by lodur:ruling:ymir-column-mean-bound-order-noise: summation order is not behaviour, so the shipped worst is taken over twelve orders
|
||||
// of the fluid pass's bucket offsets (the six axis permutations, each ascending and descending): 0.0178 worst (0.0027 to 0.0178). Md (fluid-fluid pairs done
|
||||
// from both rows) reads 0.4625 to 0.4865: bound sqrt(0.0178 x 0.4625) = 0.0907, separation 5.1 each side (it was 0.0137 against one order's reading, and one order broke it).
|
||||
// The mean no longer separates the others: Mk (fluid cell 2 rmax, 1 ring) 0.0142 to 0.0182, Mx (fluid pairs also contact; the column sets SELF_COLLIDE) 0.0038 to 0.0154,
|
||||
// Mu (bucket dedupe deleted) 0.0013 to 0.0058, Mf (fluid-solid contact deleted; the column holds no solid particle) unchanged: Mk is claimed by KERNEL_REACH, Mf by the floor
|
||||
// penetration and the through count, Mu and Mx are unclaimed (Mu only moves the FluidHashes pin). The max density reads 1.2992 to 1.3795 shipped over the twelve orders and
|
||||
// 1.7133 to 1.7550 under Md: Md is 1.14 away, the midpoint 1.537 would rise, so the sanity ceiling 1.5 stays and also claims Md (the
|
||||
// column compressing under its weight is the one-pass solver, not a defect: probe pours peaked at 1.07). Mo (capacity 8) overflows the lists
|
||||
// 377700 times in the column against 0 shipped (half a unit by lodur:ruling:deterministic-bound-zero-reading): the overflow assert is exact
|
||||
// zero, below the rule's midpoint, because the count is exact and any overflow means pairs were lost.
|
||||
// Unclaimed since the fix cut, readings of its build, a follow-up: Mc1 (lambda halved) max 1.2116, Mc2 (pass A without the self term) max 1.3340.
|
||||
private const float ColumnMax = 1.5f;
|
||||
private const float ColumnMean = 0.0907f;
|
||||
private const float FloorPenetration = 0.233f;
|
||||
private const int FloorThrough = 18;
|
||||
|
||||
[Fact]
|
||||
public void Fluid_column_rests_at_rest_density()
|
||||
{
|
||||
// A 8 x 8 x 16 block (r 1.25 cm, water mass) resting in a static box well, 3 s at 60 Hz x 4 substeps. The density constraint is
|
||||
// one pass a substep, so the column compresses under its own weight and its walls read low (a rigid box adds no density
|
||||
// to the estimate, docs/soa-world.md Not done); what is judged is that the max stays under the bound and the mean near 1.
|
||||
using var world = FluidWorld(1024);
|
||||
const float half = 0.105f;
|
||||
Well(world, half);
|
||||
// Alternate groups and set both self flags: two fluid particles share one density field whatever their group (Flex sec. 7), so
|
||||
// neither a group boundary nor SELF_COLLIDE makes a contact between them.
|
||||
var desc = new Box3DSoaParticleDesc[8 * 16 * 8];
|
||||
for (var k = 0; k < 8; k++) for (var j = 0; j < 16; j++) for (var i = 0; i < 8; i++)
|
||||
desc[(k * 16 + j) * 8 + i] = new Box3DSoaParticleDesc((-0.0875f + 2 * R * i, R + 2 * R * j, -0.0875f + 2 * R * k), FluidMass, R,
|
||||
Box3DSoaPhase.Of((uint)((i + j + k) % 2 + 1), true, true, true));
|
||||
var block = new Box3DSoaParticleHandle[desc.Length];
|
||||
world.CreateParticles(desc, block);
|
||||
var worst = 0f;
|
||||
var overflow = 0;
|
||||
for (var tick = 0; tick < 180; tick++)
|
||||
{
|
||||
world.Step(1f / 60f, 4);
|
||||
overflow = Math.Max(overflow, world.View.FluidNeighbourOverflow);
|
||||
if (tick < 120) continue;
|
||||
var d = world.View.ParticleDensity;
|
||||
foreach (var h in block) worst = MathF.Max(worst, d[h.Lane]);
|
||||
}
|
||||
var v = world.View;
|
||||
double mean = 0;
|
||||
var outside = 0;
|
||||
foreach (var h in block)
|
||||
{
|
||||
mean += v.ParticleDensity[h.Lane];
|
||||
if (MathF.Abs(v.ParticleX[h.Lane]) > half || MathF.Abs(v.ParticleZ[h.Lane]) > half || v.ParticleY[h.Lane] < -0.01f) outside++;
|
||||
}
|
||||
mean /= block.Length;
|
||||
var line = $"COLUMN max density over the last second {worst:F4}, mean at 3 s {mean:F4}, outside the well {outside}, neighbour overflow {overflow}";
|
||||
Readings.Add(line);
|
||||
Assert.Equal(0, outside);
|
||||
Assert.Equal(0, overflow);
|
||||
Assert.True(worst <= ColumnMax, $"{line}: max over {ColumnMax}");
|
||||
Assert.True(Math.Abs(mean - 1.0) <= ColumnMean, $"{line}: mean off 1 by over {ColumnMean}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_density_counts_a_larger_solid_beyond_two_contact_radii()
|
||||
{
|
||||
// The kernel reach of a pair is 2 (ri + rj), so a fluid particle sees a solid of radius 5 cm 12.5 cm away while contact reaches
|
||||
// 6.25 cm: the fluid grid cell is 4 r_fluid (5 cm) and the fluid pass walks 3 rings of them. Placed three cells apart (10.15 cm), the solid is in
|
||||
// the fluid particle's estimate only if the rings are derived from the kernel reach (Mk forces the cell to 2 r_max and 1 ring: the solid is then two cells away).
|
||||
double Density(bool solid)
|
||||
{
|
||||
using var world = FluidWorld(256, gravityY: 0f); // a table of 512 buckets: a bucket two cells share could hide the miss
|
||||
world.CreateParticles([Fluid((0.099f, 0f, 0f))]);
|
||||
if (solid) world.CreateParticles([new Box3DSoaParticleDesc((0.2005f, 0f, 0f), 1f, 0.05f, Box3DSoaPhase.Of(1))]);
|
||||
world.Step(1f / 60f, 4);
|
||||
return world.View.ParticleDensity[0];
|
||||
}
|
||||
var alone = Density(false);
|
||||
var near = Density(true);
|
||||
var rise = near / alone - 1.0;
|
||||
var line = $"KERNEL_REACH fluid density {alone:F6} alone, {near:F6} with a 5 cm solid 10.15 cm away: rise {rise:E3}";
|
||||
Readings.Add(line);
|
||||
Assert.True(rise >= KernelReachBound, line);
|
||||
}
|
||||
|
||||
// Relative rise of the fluid particle's density: shipped 2.530e-3, Mk (cell 2 r_max, 1 ring) 0 (a table of 512 buckets, as 16 would hide the miss; Mu, dedupe deleted, 5.06e-2), which counts one unit (1e-6) by
|
||||
// lodur:ruling:deterministic-bound-zero-reading: bound sqrt(2.530e-3 x 1e-6) = 5.0e-5, separation 50.
|
||||
private const double KernelReachBound = 5.0e-5;
|
||||
|
||||
// Drift as a fraction of the initial momentum, worst of the four mass ratios: shipped 7.71e-4 (fluid : solid 1 : 30; 6e-6 to 1e-5, the float32
|
||||
// floor as Contact_conserves_momentum's, at the other three). Mutants, worst row / least row: M1 (solid end of pass B not moved) 0.20 / 2.5e-2;
|
||||
// M3 (each end takes the whole correction) 0.148 / 2.06e-3. The midpoint sqrt(5.72e-4 x 2.5e-2) = 3.8e-3 would rise, so the bound keeps
|
||||
// its 2.0e-3 (never loosened); shipped is 3.5 under it and M1 and M3 fail it on every row but M3's 100 : 1.
|
||||
// Kinetic energy rise (max / initial - 1) on every row: shipped reads 1.000000, no rise at the print's 1e-6 (half a unit, 5e-7, by
|
||||
// lodur:ruling:deterministic-bound-zero-reading); M9 (the pair split 2 w / (wi + wj) over a unit-mass lambda) rises 0.108 at 30 : 1 and 0.130 at
|
||||
// 100 : 1. The midpoint sqrt(5e-7 x 0.108) = 2.3e-4 would loosen the standing 1e-5, which stays: separation 1.1e4.
|
||||
private const double MomentumBound = 2.0e-3;
|
||||
private const double EnergyBound = 1e-5;
|
||||
|
||||
[Theory]
|
||||
[InlineData(0.064f, 0.02f)] // fluid water, solids as the pour
|
||||
[InlineData(0.002f, 0.06f)] // fluid : solid 1 : 30
|
||||
[InlineData(0.06f, 0.002f)] // fluid : solid 30 : 1
|
||||
[InlineData(0.1f, 0.001f)] // fluid : solid 100 : 1
|
||||
public void Fluid_solid_momentum_zero_g(float fluidMass, float solidMass)
|
||||
{
|
||||
// A fluid block thrown into a free sheet and a free rope in zero gravity for 2 s: every pair (fluid and fluid, fluid and solid, solid
|
||||
// and solid) moves its two ends by equal and opposite momentum, so the total may not drift and the kinetic energy may not rise,
|
||||
// at any mass ratio. The bound is the float32 floor of the scene, as Contact_conserves_momentum's.
|
||||
using var world = Collision(fluidMass, solidMass);
|
||||
var (drift, energy) = Momentum(world, 120);
|
||||
var line = $"MOMENTUM_FLUID m_f {fluidMass} m_s {solidMass}: drift {drift:E3} of the initial momentum, kinetic energy max/initial {energy:F6}";
|
||||
Readings.Add(line);
|
||||
Assert.True(drift <= MomentumBound, line);
|
||||
Assert.True(energy <= 1 + EnergyBound, line);
|
||||
}
|
||||
|
||||
// The pour is read, not judged: at the scene's own 4 substeps its sheet stretches under the block's weight until a particle the sheet's own size
|
||||
// passes between the pins (the sieve, a limit of loose cloth pinned at few points: lodur:ruling:ymir-sheet-sieve-at-budget-substeps; a skin attached along a
|
||||
// bone holds, Skin_on_a_bone_holds_under_pour_and_drop), and the same block flagged solid tunnels worse, so no count of it
|
||||
// claims a mutant of the fluid. What fluid owns is pinned by Fluid_holds_on_a_solid_floor; this test runs the scene and prints both readings.
|
||||
private static (string Line, int Overflow) PourReading(bool solid)
|
||||
{
|
||||
var (world, sheet, rope, fluid) = Pour(solid: solid);
|
||||
using (world)
|
||||
{
|
||||
var touchedSheet = new bool[fluid.Length];
|
||||
var touchedRope = new bool[fluid.Length];
|
||||
var deep = 0; var minRatio = 9f; var maxStretch = 0f; var overflow = 0;
|
||||
var solids = sheet.Particles.Select(h => (h.Lane, Sheet: true)).Concat(rope.Particles.Select(h => (h.Lane, Sheet: false))).ToArray();
|
||||
for (var tick = 0; tick < 240; tick++)
|
||||
{
|
||||
world.Step(1f / 60f, Sub);
|
||||
var v = world.View;
|
||||
overflow = Math.Max(overflow, v.FluidNeighbourOverflow);
|
||||
foreach (var e in sheet.Edges)
|
||||
maxStretch = MathF.Max(maxStretch, Graph.Dist(v, v.DistanceA[e.Lane], v.DistanceB[e.Lane]) / v.DistanceRest[e.Lane] - 1f);
|
||||
for (var k = 0; k < fluid.Length; k++)
|
||||
{
|
||||
var f = fluid[k].Lane;
|
||||
foreach (var (s, onSheet) in solids)
|
||||
{
|
||||
var reach = v.ParticleRadius[f] + v.ParticleRadius[s];
|
||||
var d = Graph.Dist(v, f, s);
|
||||
if (d < 1.25f * reach) { if (onSheet) touchedSheet[k] = true; else touchedRope[k] = true; }
|
||||
if (d < 0.5f * reach) deep++;
|
||||
minRatio = MathF.Min(minRatio, d / reach);
|
||||
}
|
||||
}
|
||||
}
|
||||
var view = world.View;
|
||||
var below = fluid.Count(h => view.ParticleY[h.Lane] < -0.2f);
|
||||
return ($"POUR_{(solid ? "SOLID" : "FLUID")} at {Sub} substeps: touched the sheet {touchedSheet.Count(b => b)} of {fluid.Length}, the rope {touchedRope.Count(b => b)}, below y = -0.2 m at 4 s {below}, " +
|
||||
$"within half a contact distance of a solid (tick x particle pairs) {deep} (closest {minRatio:F3} of a contact distance), worst sheet edge stretch {maxStretch:F3}, neighbour overflow {overflow}", overflow);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_pours_on_a_sheet_and_off_a_rope()
|
||||
{
|
||||
foreach (var solid in new[] { false, true })
|
||||
{
|
||||
var (line, overflow) = PourReading(solid);
|
||||
Console.Error.WriteLine(line);
|
||||
Readings.Add(line);
|
||||
Assert.Equal(0, overflow);
|
||||
}
|
||||
}
|
||||
|
||||
// Probe sieve.c (lodur flesh-bones-map.probe-skin-sieve) as a test: a skin sheet attached along its length to a bone, under a pour and a drop.
|
||||
private const float SkinBone = 0.07f, SkinHalf = 0.18f, SkinY = 0.5f;
|
||||
|
||||
/// <summary>
|
||||
/// A capsule (r 7 cm, half 18 cm, local Y laid along world X) welded to an anchor over a static floor, wrapped by 5 rings of 6 skin particles
|
||||
/// (staggered, centres on the capsule surface, no self-collision) with ring and diagonal distances, ring bends and a body attachment on every
|
||||
/// particle, and a load block 25 cm above the capsule: 7 x 7 x 7 fluid at 2.5 cm, or 4 x 4 x 4 solids at 4 cm.
|
||||
/// </summary>
|
||||
private static (Box3DSoaWorld World, int Bone, Box3DSoaParticleHandle[] Skin, Box3DSoaConstraintHandle[] Edges, Box3DSoaParticleHandle[] Load) SkinScene(bool solid, float attach)
|
||||
{
|
||||
var world = new Box3DSoaWorld(4, gravityY: -9.81f, jointCapacity: 2, particles: new Box3DSoaParticleCapacities(512, 128, 64, 64, 64, 2, 512));
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (5f, 0.5f, 5f));
|
||||
world.SetMaterial(1, 0.3f, 0, 0.01f); // the pour's XSPH coefficient
|
||||
var q = (0f, 0f, MathF.Sin(-MathF.PI / 4f), MathF.Cos(-MathF.PI / 4f)); // local Y onto world X
|
||||
var bone = world.AddCapsule(2, (0f, SkinY, 0f), SkinBone, SkinHalf, 1000f, q);
|
||||
var anchor = world.AddAnchor(3, (0f, SkinY, 0f));
|
||||
world.AddJoint(Box3DSoaJointKind.Weld, anchor, bone, (0f, SkinY, 0f), (0f, 0f, 1f));
|
||||
const int rings = 5, per = 6;
|
||||
const float spacing = 2 * SkinHalf / (rings - 1);
|
||||
var rest = new (float X, float Y, float Z)[rings * per];
|
||||
var desc = new Box3DSoaParticleDesc[rings * per];
|
||||
for (var i = 0; i < rings; i++)
|
||||
for (var j = 0; j < per; j++)
|
||||
{
|
||||
var a = 2f * MathF.PI * (j + 0.5f * (i & 1)) / per;
|
||||
var at = (-SkinHalf + spacing * i, SkinY + SkinBone * MathF.Cos(a), SkinBone * MathF.Sin(a));
|
||||
rest[i * per + j] = at;
|
||||
desc[i * per + j] = new Box3DSoaParticleDesc(at, 0.012f, 0.036f, Box3DSoaPhase.Of(4));
|
||||
}
|
||||
var skin = new Box3DSoaParticleHandle[desc.Length];
|
||||
world.CreateParticles(desc, skin);
|
||||
var d = new List<Box3DSoaDistanceDesc>();
|
||||
var ringAt = new int[rings, per];
|
||||
for (var i = 0; i < rings; i++)
|
||||
for (var j = 0; j < per; j++)
|
||||
{
|
||||
ringAt[i, j] = d.Count;
|
||||
d.Add(new(skin[i * per + j], skin[i * per + (j + 1) % per], 2e-4f));
|
||||
if (i + 1 == rings) continue;
|
||||
var odd = (i & 1) == 1;
|
||||
d.Add(new(skin[i * per + j], skin[(i + 1) * per + (odd ? (j + 1) % per : j)], 2e-4f));
|
||||
d.Add(new(skin[i * per + j], skin[(i + 1) * per + (odd ? j : (j + per - 1) % per)], 2e-4f));
|
||||
}
|
||||
var edges = new Box3DSoaConstraintHandle[d.Count];
|
||||
world.CreateDistances(d.ToArray(), edges);
|
||||
var b = new List<Box3DSoaBendDesc>();
|
||||
for (var i = 0; i < rings; i++)
|
||||
for (var j = 0; j < per; j++) b.Add(new(edges[ringAt[i, (j + per - 1) % per]], edges[ringAt[i, j]], 1e-3f));
|
||||
world.CreateBends(b.ToArray(), new Box3DSoaConstraintHandle[b.Count]);
|
||||
for (var k = 0; k < skin.Length; k++) // the body frame of the rotation above: local = (-dy, dx, dz)
|
||||
world.Attach(Box3DSoaAttachKind.Body, skin[k], bone, (-(rest[k].Y - SkinY), rest[k].X, rest[k].Z), attach);
|
||||
var side = solid ? 4 : 7;
|
||||
var pitch = solid ? 0.04f : 0.025f;
|
||||
var r = pitch / 2f;
|
||||
var load = new Box3DSoaParticleHandle[side * side * side];
|
||||
var l = new Box3DSoaParticleDesc[load.Length];
|
||||
for (var x = 0; x < side; x++) for (var y = 0; y < side; y++) for (var z = 0; z < side; z++)
|
||||
l[(x * side + y) * side + z] = new Box3DSoaParticleDesc(
|
||||
((x - 0.5f * (side - 1)) * pitch, SkinY + SkinBone + 0.25f + y * pitch, (z - 0.5f * (side - 1)) * pitch),
|
||||
solid ? 0.06f : 0.015625f, r, solid ? Box3DSoaPhase.Of(6, true) : Box3DSoaPhase.Of(6, fluid: true), 1);
|
||||
world.CreateParticles(l, load);
|
||||
return (world, bone, skin, edges, load);
|
||||
}
|
||||
|
||||
private static string SkinReading(bool solid, int hz, float attach, out float stretch, out int inside, out float place, out int reachedCount)
|
||||
{
|
||||
var (world, bone, skin, edges, load) = SkinScene(solid, attach);
|
||||
using (world)
|
||||
{
|
||||
stretch = 0f; inside = 0;
|
||||
var reached = new bool[load.Length];
|
||||
for (var tick = 0; tick < 3 * hz; tick++)
|
||||
{
|
||||
world.Step(1f / hz, 4);
|
||||
var v = world.View;
|
||||
foreach (var e in edges)
|
||||
stretch = MathF.Max(stretch, Graph.Dist(v, v.DistanceA[e.Lane], v.DistanceB[e.Lane]) / v.DistanceRest[e.Lane] - 1f);
|
||||
for (var k = 0; k < load.Length; k++)
|
||||
{
|
||||
var f = load[k].Lane;
|
||||
if (MathF.Abs(v.ParticleX[f] - v.PositionX[bone]) >= SkinHalf) continue; // over the shaft only: the open ends are not the skin's to close
|
||||
var radial = MathF.Sqrt(Sq(v.ParticleY[f] - v.PositionY[bone]) + Sq(v.ParticleZ[f] - v.PositionZ[bone]));
|
||||
if (radial < SkinBone) inside++;
|
||||
if (radial < SkinBone + 1.5f * v.ParticleRadius[f]) reached[k] = true;
|
||||
}
|
||||
}
|
||||
var w = world.View;
|
||||
double sum = 0;
|
||||
foreach (var h in skin)
|
||||
{
|
||||
var dx = MathF.Max(0f, MathF.Abs(w.ParticleX[h.Lane] - w.PositionX[bone]) - SkinHalf);
|
||||
sum += MathF.Sqrt(dx * dx + Sq(w.ParticleY[h.Lane] - w.PositionY[bone]) + Sq(w.ParticleZ[h.Lane] - w.PositionZ[bone]));
|
||||
}
|
||||
var mean = (float)(sum / skin.Length);
|
||||
place = MathF.Abs(mean - SkinBone);
|
||||
reachedCount = reached.Count(x => x);
|
||||
return $"SKIN_SIEVE {(solid ? "solid" : "fluid")} {hz} Hz at attach compliance {attach:E0}: worst skin edge stretch {stretch:F4}, place off {place:E2}, load particles inside the bone {inside}, " +
|
||||
$"skin mean axis distance {mean:F5} (bone {SkinBone}), load reaching the bone surface {reachedCount} of {load.Length}";
|
||||
}
|
||||
}
|
||||
|
||||
// Bounds follow lodur:ruling:deterministic-bound-margin; the reached floor also lodur:ruling:deterministic-bound-zero-reading. Worst edge stretch over the four rows:
|
||||
// shipped 0.0214 (fluid 0.0156 / 0.0204, solid 0.0196 / 0.0214 at 60 / 120 Hz). Ma (solve_attachments returns at entry) 0.0560 (120 Hz) to 0.1475 (60 Hz), and Mc (the
|
||||
// skin's attachment compliance x 1e6 here, not in the solver) 0.0559 to 0.1465: the skin free-falls past the bone before the load arrives, so both read alike on every
|
||||
// row. Bound sqrt(0.0214 x 0.0559) = 0.0346, separation 2.6, both mutants claimed. The place bound is |skin mean axis distance - 0.07| at 3 s: shipped reads 6e-8 to
|
||||
// 2.7e-7 (float32 noise, not zero, so no zero-reading convention), worst 2.7e-7; the least claimed mutant is attachment compliance x 10 (1e-2 here) at 4.91e-6 to 4.94e-6 (it also trips stretch on 3 rows);
|
||||
// bound sqrt(2.7e-7 x 4.9e-6) = 1.15e-6, separation 18. Compliance x 100 reads 4.8e-4 to 5.1e-4 and fails the bound too; Ma and Mc
|
||||
// read 0.331 to 0.350. Not claimed: bend compliance x 1e6 and 1 to 3 substeps pass every row (4 is pinned by construction only). Inside the bone is exact zero in every
|
||||
// row for shipped, Ma and Mc: the capsule body itself stops a particle against those. It claims the body-contact mutant (body_contacts returns at entry): 119 to 2151
|
||||
// inside, fluid and solid, against 0. The load reaching the bone surface (a centre within the bone radius + 1.5 r) reads 33 to 174 shipped (fluid 174 / 103, solid 41 / 33 at
|
||||
// 60 / 120 Hz; of 343 fluid and 64 solid): the load rests between the skin's particles on the bone, as a skin of six particles a ring leaves it. It is asserted as the proof the
|
||||
// load arrives: with the load block 3 m off the bone it reads 0 on every row while stretch, inside and place all pass. Floor sqrt(33 x 1) = 5.74, the mutant's zero counting as
|
||||
// one unit by the zero-reading rule, separation 33.
|
||||
private const float SkinStretch = 0.0346f;
|
||||
private const float SkinPlace = 1.15e-6f;
|
||||
private const float SkinReached = 5.74f;
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, 60)]
|
||||
[InlineData(false, 120)]
|
||||
[InlineData(true, 60)]
|
||||
[InlineData(true, 120)]
|
||||
public void Skin_on_a_bone_holds_under_pour_and_drop(bool solid, int hz)
|
||||
{
|
||||
// The case the corner-pinned sheet above is not: skin attached along its length to a bone (lodur:ruling:ymir-sheet-sieve-at-budget-substeps,
|
||||
// lodur:ruling:bds-body-skeleton-particle-flesh-rough). 3 s at 4 substeps under a pour or a drop of solids from 25 cm; the load must reach the bone, nothing may enter it.
|
||||
var line = SkinReading(solid, hz, 1e-3f, out var stretch, out var inside, out var place, out var reached);
|
||||
Readings.Add(line);
|
||||
Assert.Equal(0, inside);
|
||||
Assert.True(reached >= SkinReached, $"{line}: load reaching the bone surface under {SkinReached}");
|
||||
Assert.True(stretch <= SkinStretch, $"{line}: stretch over {SkinStretch}");
|
||||
Assert.True(place <= SkinPlace, $"{line}: place off the bone by over {SkinPlace}");
|
||||
}
|
||||
|
||||
// A fluid block dropped 15 cm onto a floor of immovable solid particles (mass 0). Two readings, both over the 4 s at 4 substeps:
|
||||
// penetration = 1 - closest fluid-floor distance / contact distance (sampled at tick ends), and the fluid particles that went below the floor plane
|
||||
// while over the floor's interior (a pitch in from every edge: a flat floor has no walls, so the rest spill off its edge, 210 of 343 by 4 s).
|
||||
// Penetration: shipped 0.186, Mt1 (collides returns 0 for any fluid-solid pair) 0.292, Mt2 (density_pair counts fluid-fluid only) 0.291: bound
|
||||
// sqrt(0.187 x 0.291) = 0.233, separation 1.56 (set at the fix cut's 0.187; the midpoint with 0.186 is 0.233 too). Mr (rings forced to 1) reads 0.258 and
|
||||
// Md (fluid-fluid pairs done from both rows) 0.401 with 22 through: both fail the bounds. Mo (capacity 8) reads 0.629 and 25823 overflows. Through: shipped 1, Mt1 343, Mt2 1: bound sqrt(1 x 343) = 18, separation 343. The shipped 1 is the
|
||||
// block's centre column, exactly over a hole of the floor lattice: by the lattice symmetry the contacts push it sideways at the hole's plane and the
|
||||
// column's weight takes it through. Nowhere near half a contact distance deep, so not the fluid defect the spec stops on; reported.
|
||||
// At the kernel-cell cut (lodur:cut_spec:cut-ymir-fluid-cost.r2): shipped 0.134 and 0 through; Mk (fluid cell 2 r_max, 1 ring) 0.171 and 0 (unclaimed here, KERNEL_REACH claims it); Md 0.435 and 10 through; Mf (fluid-solid contact deleted) 0.945 and 259 through, claimed by both; Mo (arena 8 a fluid lane) 0.843 and 13650 overflows.
|
||||
private static (float Penetration, int Below, int Overflow) Floor(out string line)
|
||||
{
|
||||
using var world = FluidWorld(640, gravityY: -9.81f);
|
||||
world.SetMaterial(1, 0.3f, 0, 0.01f);
|
||||
const float pitch = 0.04f, r = 0.02f;
|
||||
var floor = Graph.Block(world, (0f, 0f, 0f), 16, 1, 16, r, 0f, Box3DSoaPhase.Of(4), pitch: pitch);
|
||||
var fluid = Graph.Block(world, (0.18f, 0.15f, 0.18f), 7, 7, 7, r, 1000f * pitch * pitch * pitch, Box3DSoaPhase.Of(6, fluid: true), material: 1, pitch: pitch);
|
||||
var closest = 9f;
|
||||
var overflow = 0;
|
||||
var through = new bool[fluid.Length];
|
||||
for (var tick = 0; tick < 240; tick++)
|
||||
{
|
||||
world.Step(1f / 60f, Sub);
|
||||
var v = world.View;
|
||||
overflow = Math.Max(overflow, v.FluidNeighbourOverflow);
|
||||
for (var k = 0; k < fluid.Length; k++) // a particle that spills off the floor's edge is not below it: only one over the floor's interior (a pitch in from every edge) counts
|
||||
{
|
||||
var l = fluid[k].Lane;
|
||||
if (v.ParticleY[l] < 0f && v.ParticleX[l] >= pitch && v.ParticleX[l] <= 14f * pitch && v.ParticleZ[l] >= pitch && v.ParticleZ[l] <= 14f * pitch) through[k] = true;
|
||||
}
|
||||
foreach (var f in fluid)
|
||||
foreach (var s in floor)
|
||||
closest = MathF.Min(closest, Graph.Dist(v, f.Lane, s.Lane) / (v.ParticleRadius[f.Lane] + v.ParticleRadius[s.Lane]));
|
||||
}
|
||||
var view = world.View;
|
||||
var below = through.Count(b => b);
|
||||
var spilled = fluid.Count(h => view.ParticleY[h.Lane] < 0f);
|
||||
var penetration = MathF.Max(0f, 1f - closest);
|
||||
line = $"FLOOR a 7 x 7 x 7 fluid block dropped 15 cm onto a 16 x 16 immovable floor at {Sub} substeps: penetration {penetration:F3} of a contact distance, fluid that went below the floor plane over its interior {below} of {fluid.Length} ({spilled} below it at 4 s, the rest of them over the edge), neighbour overflow {overflow}";
|
||||
Readings.Add(line);
|
||||
return (penetration, below, overflow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_holds_on_a_solid_floor()
|
||||
{
|
||||
var (penetration, below, overflow) = Floor(out var line);
|
||||
Assert.Equal(0, overflow);
|
||||
Assert.True(penetration <= FloorPenetration, line + $": penetration over {FloorPenetration}");
|
||||
Assert.True(below <= FloorThrough, line + $": more than {FloorThrough} through");
|
||||
}
|
||||
|
||||
// The support lanes name contact in the last substep, not rest: the step writes them and nothing reads them, so these tests read them.
|
||||
private static void ReadSupport(string scene, Box3DSoaView v, Box3DSoaParticleHandle[] fluid)
|
||||
{
|
||||
var body = fluid.Count(h => v.SupportBody[h.Lane] >= 0);
|
||||
var particle = fluid.Count(h => v.SupportParticle[h.Lane] >= 0);
|
||||
Readings.Add($"SUPPORT {scene}: {fluid.Length} fluid particles, {body} read a body, {particle} read a solid particle");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Support_lanes_name_what_fluid_rests_on()
|
||||
{
|
||||
// Static floor and walls: a 4 x 4 x 4 pool in a well. Whoever touches the floor or a wall (the highest lane wins) reads that body; a particle
|
||||
// resting only on other fluid reads -1 on both lanes, as does a drop in flight. A drop pinched between the floor (lane 0) and a slab 1.9 r above
|
||||
// it (lane 5) touches both: the slab, the higher lane.
|
||||
{
|
||||
using var world = FluidWorld(256, gravityY: -9.81f);
|
||||
const float half = 0.1f;
|
||||
Well(world, half);
|
||||
var slab = world.AddStaticBox(6, (1f, 1.9f * R + 0.05f, 0f), (0.1f, 0.05f, 0.1f));
|
||||
var pool = Graph.Block(world, (-0.0625f, R + 0.005f, -0.0625f), 5, 8, 5, R, FluidMass, FluidPhase);
|
||||
var pinched = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((1f, R, 0f))], pinched);
|
||||
var flight = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((-1f, 40f, 0f))], flight);
|
||||
var thrown = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((-1f, 0.5f * R, 1f), velocity: (0f, 1f, 0f))], thrown); // inside the floor, moving up
|
||||
Assert.Equal(5, slab);
|
||||
var view = world.View;
|
||||
Assert.Equal(-1, view.SupportBody[pool[0].Lane]);
|
||||
world.Step(1f / 240f, 1); // one substep: the thrown drop touches the floor in it
|
||||
Assert.Equal(0, world.View.SupportBody[thrown[0].Lane]);
|
||||
world.Step(1f / 60f, Sub); // four more: it is in flight in each, so a lane the step did not clear would still read the floor
|
||||
Assert.Equal(-1, world.View.SupportBody[thrown[0].Lane]);
|
||||
for (var tick = 0; tick < 119; tick++) world.Step(1f / 60f, Sub);
|
||||
view = world.View;
|
||||
// Every pool particle falls in one class by its distance to the nearest face. Gravity presses the floor layer every substep, so it must read;
|
||||
// a particle clear of every face by 5% must read -1 (resting on fluid); one in between may read either, but only a face it is within 5% of
|
||||
// (a contact pushes a particle out to distance r exactly, where it may or may not touch again).
|
||||
int floor = 0, resting = 0, band = 0;
|
||||
foreach (var h in pool)
|
||||
{
|
||||
var (x, y, z) = (view.ParticleX[h.Lane], view.ParticleY[h.Lane], view.ParticleZ[h.Lane]);
|
||||
var near = new List<int>();
|
||||
if (y <= 1.05f * R) near.Add(0);
|
||||
if (half - x <= 1.05f * R) near.Add(1);
|
||||
if (half + x <= 1.05f * R) near.Add(2);
|
||||
if (half - z <= 1.05f * R) near.Add(3);
|
||||
if (half + z <= 1.05f * R) near.Add(4);
|
||||
var body = view.SupportBody[h.Lane];
|
||||
var where = $"x {x:F5} y {y:F5} z {z:F5} body {body}";
|
||||
if (y <= 1.001f * R) { floor++; Assert.True(body >= 0 && body <= 4, where); }
|
||||
else if (near.Count == 0) { resting++; Assert.Equal(-1, body); }
|
||||
else { band++; Assert.True(body == -1 || near.Contains(body), where); }
|
||||
Assert.Equal(-1, view.SupportParticle[h.Lane]);
|
||||
}
|
||||
Assert.Equal(pool.Length, floor + resting + band);
|
||||
Assert.True(floor >= 100 && resting >= 10, $"{floor} on the floor, {resting} resting on fluid, {band} in the band");
|
||||
Assert.Equal(5, view.SupportBody[pinched[0].Lane]);
|
||||
Assert.Equal(-1, view.SupportParticle[pinched[0].Lane]);
|
||||
Assert.Equal(-1, view.SupportBody[flight[0].Lane]);
|
||||
Assert.Equal(-1, view.SupportParticle[flight[0].Lane]);
|
||||
// Destroy clears both lanes at once: a destroyed floor particle reads -1 before any step, not its last support.
|
||||
var floorPick = pool.First(h => view.ParticleY[h.Lane] <= 1.001f * R);
|
||||
Assert.True(view.SupportBody[floorPick.Lane] >= 0);
|
||||
world.DestroyParticles([floorPick]);
|
||||
Assert.Equal(-1, world.View.SupportBody[floorPick.Lane]);
|
||||
Assert.Equal(-1, world.View.SupportParticle[floorPick.Lane]);
|
||||
Readings.Add($"SUPPORT well classes: {floor} floor, {resting} resting on fluid, {band} band of {pool.Length}");
|
||||
ReadSupport("well", view, pool);
|
||||
}
|
||||
// A free box on the floor, a pool on the box: the box's lane for the layer that touches it, -1 above, never the floor's.
|
||||
{
|
||||
using var world = FluidWorld(128, gravityY: -9.81f);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
var box = world.AddBox(2, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), 5000f, friction: 0.3f);
|
||||
var pool = Graph.Block(world, (-0.025f, 0.2f + R + 0.005f, -0.025f), 3, 7, 3, R, FluidMass, FluidPhase);
|
||||
for (var tick = 0; tick < 12; tick++) world.Step(1f / 60f, Sub);
|
||||
var view = world.View;
|
||||
var top = view.PositionY[box] + 0.1f;
|
||||
var touching = 0; var resting = 0;
|
||||
foreach (var h in pool)
|
||||
{
|
||||
var y = view.ParticleY[h.Lane];
|
||||
if (MathF.Abs(view.ParticleX[h.Lane] - view.PositionX[box]) > 0.1f - R || MathF.Abs(view.ParticleZ[h.Lane] - view.PositionZ[box]) > 0.1f - R) continue; // spilled over the edge
|
||||
if (y <= top + 1.001f * R) { touching++; Assert.Equal(box, view.SupportBody[h.Lane]); }
|
||||
else if (y > top + 1.5f * R) { resting++; Assert.Equal(-1, view.SupportBody[h.Lane]); }
|
||||
Assert.Equal(-1, view.SupportParticle[h.Lane]);
|
||||
}
|
||||
Assert.True(touching >= 4 && resting >= 4, $"{touching} touch the box, {resting} above them");
|
||||
ReadSupport("free box", view, pool);
|
||||
}
|
||||
// A sheet pinned along two opposite edges (one edge alone swings down like a curtain; a corner-pinned tarp sieves, lodur:ruling:ymir-sheet-sieve-at-budget-substeps) under a few drops: each reads a
|
||||
// sheet particle that touches it; a drop high above reads -1 on both.
|
||||
{
|
||||
using var world = new Box3DSoaWorld(4, gravityY: -9.81f, particles: new Box3DSoaParticleCapacities(256, 160, 140, 16, 1024, 2, 16));
|
||||
world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f));
|
||||
var sheet = Graph.Sheet(world, (0f, 0.6f, 0f), (0.04f, 0f, 0f), (0f, 0f, 0.04f), 8, 8, 0.02f, 0.02f, Box3DSoaPhase.Of(4, true, true));
|
||||
for (var j = 0; j < 8; j++)
|
||||
for (var i = 0; i < 8; i += 7)
|
||||
world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[j * 8 + i], point: (0.04f * i, 0.6f, 0.04f * j));
|
||||
var drops = new Box3DSoaParticleHandle[4];
|
||||
world.CreateParticles([Fluid((0.12f, 0.64f, 0.12f)), Fluid((0.16f, 0.64f, 0.16f)), Fluid((0.2f, 0.64f, 0.08f)), Fluid((0.15f, 60f, 0.14f))], drops);
|
||||
world.Step(1f / 60f, Sub);
|
||||
// a drop 4 cm above a sheet particle sits inside the kernel reach and so in its row's list, and does not touch (4 cm against 3.25): no support
|
||||
Assert.Equal(-1, world.View.SupportParticle[drops[0].Lane]);
|
||||
Assert.Equal(-1, world.View.SupportParticle[drops[1].Lane]);
|
||||
for (var tick = 1; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
var view = world.View;
|
||||
var onSheet = new HashSet<int>(sheet.Particles.Select(h => h.Lane));
|
||||
var read = 0;
|
||||
foreach (var h in drops.Take(3))
|
||||
{
|
||||
var s = view.SupportParticle[h.Lane];
|
||||
Assert.Equal(-1, view.SupportBody[h.Lane]);
|
||||
Assert.True(s >= 0, $"drop at lane {h.Lane} reads no sheet particle");
|
||||
read++;
|
||||
Assert.Contains(s, onSheet);
|
||||
Assert.True(Graph.Dist(view, h.Lane, s) <= 1.05f * (view.ParticleRadius[h.Lane] + view.ParticleRadius[s]), "the named particle does not touch");
|
||||
}
|
||||
Assert.Equal(3, read);
|
||||
Assert.Equal(-1, view.SupportParticle[drops[3].Lane]);
|
||||
Assert.Equal(-1, view.SupportBody[drops[3].Lane]);
|
||||
ReadSupport("sheet", view, drops);
|
||||
// A solid destroyed under a drop leaves no name behind: the drop is alive and reads -1 before any step.
|
||||
var under = view.SupportParticle[drops[0].Lane];
|
||||
world.DestroyParticles([sheet.Particles.Single(h => h.Lane == under)]);
|
||||
Assert.Equal(-1, world.View.SupportParticle[drops[0].Lane]);
|
||||
Assert.Equal(1, Math.Sign(world.View.ParticleRadius[drops[0].Lane]));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_pushes_a_body()
|
||||
{
|
||||
// A fluid block thrown down on a free 1 kg box in zero gravity: the contact and gravity terms are 0, so the box's M dv in a tick is
|
||||
// the impulse the particles gave it, which the lane reads. Fluid is booked on a body as any particle is.
|
||||
using var world = FluidWorld(256, gravityY: 0f);
|
||||
const float mass = 1f;
|
||||
var box = world.AddBox(2, (0f, 0f, 0f), (0.1f, 0.1f, 0.1f), mass / (8f * 0.1f * 0.1f * 0.1f), friction: 0.3f);
|
||||
Graph.Block(world, (-0.0375f, 0.13f, -0.0375f), 4, 4, 4, R, FluidMass, FluidPhase, velocity: (0f, -3f, 0f));
|
||||
var view = world.View;
|
||||
var (vx, vy, vz) = (view.VelocityX[box], view.VelocityY[box], view.VelocityZ[box]);
|
||||
float worst = 0f, peak = 0f;
|
||||
for (var tick = 0; tick < 120; tick++)
|
||||
{
|
||||
world.Step(1f / 60f, 4);
|
||||
var dx = mass * (view.VelocityX[box] - vx) - view.ParticleImpulseX[box];
|
||||
var dy = mass * (view.VelocityY[box] - vy) - view.ParticleImpulseY[box];
|
||||
var dz = mass * (view.VelocityZ[box] - vz) - view.ParticleImpulseZ[box];
|
||||
worst = MathF.Max(worst, MathF.Max(MathF.Abs(dx), MathF.Max(MathF.Abs(dy), MathF.Abs(dz))));
|
||||
peak = MathF.Max(peak, MathF.Abs(view.ParticleImpulseY[box]));
|
||||
(vx, vy, vz) = (view.VelocityX[box], view.VelocityY[box], view.VelocityZ[box]);
|
||||
}
|
||||
var line = $"PUSH peak impulse {peak:F5} N s a tick, worst |M dv - lane| {worst:E3} N s ({worst / peak:P3} of the peak)";
|
||||
Readings.Add(line);
|
||||
Assert.True(peak > 0.01f, line);
|
||||
Assert.True(worst <= 0.005f * peak, line);
|
||||
}
|
||||
|
||||
// Drift of the mean nearest-neighbour distance in micrometres: shipped 0 (reads 0.000 at 1e-3, so half a unit, 5e-4), M4 (bilateral C) 1.529e7:
|
||||
// bound sqrt(5e-4 x 1.529e7) = 87 micrometres by lodur:ruling:deterministic-bound-zero-reading, separation 1.8e5.
|
||||
private const double ClumpBound = 87.0;
|
||||
|
||||
[Fact]
|
||||
public void Fluid_does_not_clump()
|
||||
{
|
||||
// Particles on a lattice at 3 r spacing are under-dense: a unilateral constraint (C = max(n / n0 - 1, 0)) leaves them where they
|
||||
// are. A bilateral one pulls them together to rest density.
|
||||
using var world = FluidWorld(512, gravityY: 0f);
|
||||
world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f));
|
||||
var block = Graph.Block(world, (0f, 0f, 0f), 6, 6, 6, R, FluidMass, FluidPhase, pitch: 3f * R);
|
||||
double Mean()
|
||||
{
|
||||
var v = world.View;
|
||||
double sum = 0;
|
||||
foreach (var a in block)
|
||||
{
|
||||
var nearest = float.MaxValue;
|
||||
foreach (var b in block) if (a.Lane != b.Lane) nearest = MathF.Min(nearest, Graph.Dist(v, a.Lane, b.Lane));
|
||||
sum += nearest;
|
||||
}
|
||||
return sum / block.Length;
|
||||
}
|
||||
var before = Mean();
|
||||
for (var tick = 0; tick < 60; tick++) world.Step(1f / 60f, 4);
|
||||
var after = Mean();
|
||||
var line = $"CLUMP mean nearest-neighbour distance {before * 1e3:F6} mm before, {after * 1e3:F6} mm after 1 s (pitch {3f * R * 1e3:F4} mm), drift {Math.Abs(after - before) * 1e6:F3} micrometres";
|
||||
Readings.Add(line);
|
||||
Assert.True(Math.Abs(after - before) * 1e6 <= ClumpBound, line);
|
||||
}
|
||||
|
||||
// Variance ratio, viscosity 0.1 over 0: shipped 0.7799, M5 (XSPH skipped) and Mv (the viscous-material scan finds none, so the skip flag ignores the materials) 1.0000: bound sqrt(0.7799 x 1.0000) = 0.883, separation 1.28.
|
||||
private const double ShearBound = 0.883;
|
||||
|
||||
[Fact]
|
||||
public void Fluid_viscosity_damps_shear()
|
||||
{
|
||||
// The same block with a shear velocity field (vx by layer) for 0.5 s in zero gravity: XSPH at 0.1 takes the velocity variance
|
||||
// under the bound, at 0 it stays.
|
||||
static double Variance(float viscosity)
|
||||
{
|
||||
using var world = FluidWorld(512, gravityY: 0f);
|
||||
world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f));
|
||||
world.SetMaterial(0, 0.3f, 0, viscosity);
|
||||
var desc = new Box3DSoaParticleDesc[216];
|
||||
for (var k = 0; k < 6; k++) for (var j = 0; j < 6; j++) for (var i = 0; i < 6; i++)
|
||||
desc[(k * 6 + j) * 6 + i] = new Box3DSoaParticleDesc((2 * R * i, 2 * R * j, 2 * R * k), FluidMass, R, FluidPhase, 0, null, (0.5f * (j - 2.5f), 0f, 0f));
|
||||
var made = new Box3DSoaParticleHandle[216];
|
||||
world.CreateParticles(desc, made);
|
||||
for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, 4);
|
||||
var v = world.View;
|
||||
double mean = 0, sq = 0;
|
||||
foreach (var h in made) { mean += v.ParticleVx[h.Lane]; sq += Sq(v.ParticleVx[h.Lane]); }
|
||||
mean /= made.Length;
|
||||
return sq / made.Length - mean * mean;
|
||||
}
|
||||
var free = Variance(0f);
|
||||
var damped = Variance(0.1f);
|
||||
var line = $"SHEAR velocity variance after 0.5 s: viscosity 0 {free:F5}, viscosity 0.1 {damped:F5} (ratio {damped / free:F4})";
|
||||
Readings.Add(line);
|
||||
Assert.True(damped <= ShearBound * free, line);
|
||||
}
|
||||
|
||||
// ---- determinism ----------------------------------------------------------------------------------------
|
||||
|
||||
private static ulong Fnv(ulong h, ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
foreach (var b in bytes) { h ^= b; h *= 1099511628211ul; }
|
||||
return h;
|
||||
}
|
||||
|
||||
private static ulong HashFluid(Box3DSoaView v)
|
||||
{
|
||||
var h = 1469598103934665603ul;
|
||||
void F(ReadOnlySpan<float> lane) => h = Fnv(h, MemoryMarshal.AsBytes(lane));
|
||||
F(v.ParticleX); F(v.ParticleY); F(v.ParticleZ); F(v.ParticleVx); F(v.ParticleVy); F(v.ParticleVz); F(v.ParticleDensity);
|
||||
F(v.DistanceTension); F(v.AttachmentForceX); F(v.AttachmentForceY); F(v.AttachmentForceZ);
|
||||
F(v.PositionX); F(v.PositionY); F(v.PositionZ); F(v.VelocityX); F(v.VelocityY); F(v.VelocityZ);
|
||||
F(v.ParticleImpulseX); F(v.ParticleImpulseY); F(v.ParticleImpulseZ);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static ulong[] Checkpoints(bool nudge = false)
|
||||
{
|
||||
var (world, _, _, _) = Pour(nudge);
|
||||
using (world)
|
||||
{
|
||||
var hashes = new ulong[6];
|
||||
for (var c = 0; c < 6; c++)
|
||||
{
|
||||
for (var t = 0; t < 40; t++) world.Step(1f / 60f, Sub);
|
||||
hashes[c] = HashFluid(world.View);
|
||||
}
|
||||
return hashes;
|
||||
}
|
||||
}
|
||||
|
||||
// Re-pinned once at the kernel-cell cut (fluid rows in sorted order over 4 rfmax cells, fluid-solid contact in the fluid pass: every pair sum has a new order). Recorded on this commit's build (gcc 13.2, -ffp-contract=off): the pour scene's (4 substeps, fluid block) particle, density and body lanes at ticks 40, 80, ... 240.
|
||||
private static readonly ulong[] FluidHashes = [5735058435646750614ul, 17157245750823511088ul, 9310017083272243290ul, 13504503053832530307ul, 15203508087677495529ul, 12413386253327045810ul];
|
||||
|
||||
[Fact]
|
||||
public void Fluid_world_is_byte_deterministic()
|
||||
{
|
||||
var a = Checkpoints();
|
||||
var b = Checkpoints();
|
||||
Assert.True(a.AsSpan().SequenceEqual(b), "two runs diverged: " + string.Join(",", a) + " vs " + string.Join(",", b));
|
||||
Assert.True(a.Distinct().Count() == 6, "the scene moves");
|
||||
Assert.False(a.AsSpan().SequenceEqual(Checkpoints(nudge: true)), "a one-ulp input difference must diverge");
|
||||
Assert.True(FluidHashes.AsSpan().SequenceEqual(a), string.Join(",", a.Select(g => g + "ul")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fluid_world_is_the_same_bytes_on_any_thread_under_load()
|
||||
{
|
||||
var serial = Checkpoints();
|
||||
var results = Enumerable.Range(0, 8).Select(_ => Task.Factory.StartNew(() => Checkpoints(), TaskCreationOptions.LongRunning)).ToArray();
|
||||
await Task.WhenAll(results);
|
||||
foreach (var r in results) Assert.True(Enumerable.SequenceEqual(serial, await r), "a concurrent run diverged from the serial one");
|
||||
}
|
||||
}
|
||||
426
tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs
Normal file
426
tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
/// <summary>Kinematic anchors, the motor joint, point impulses and the closest-hit ray: the input plumbing for grab and poke.</summary>
|
||||
public sealed class Box3DSoaGrabTests
|
||||
{
|
||||
private const float Dt = 1f / 60f;
|
||||
private const float Gravity = 10f;
|
||||
private const float Radius = 0.2f;
|
||||
private const float Density = 500f;
|
||||
private static readonly float Mass = Density * 4f / 3f * MathF.PI * Radius * Radius * Radius;
|
||||
|
||||
private static float Distance(Box3DSoaView v, int lane, (float X, float Y, float Z) p)
|
||||
{
|
||||
var dx = v.PositionX[lane] - p.X; var dy = v.PositionY[lane] - p.Y; var dz = v.PositionZ[lane] - p.Z;
|
||||
return MathF.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||
}
|
||||
|
||||
/// <summary>A sphere hung from an anchor at the same point by a motor joint with the given linear spring.</summary>
|
||||
private static (Box3DSoaWorld World, int Anchor, int Sphere, int Joint) Grab(float maxForce, float hertz = 5f)
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: 4, gravityY: -Gravity, jointCapacity: 2);
|
||||
var sphere = world.AddSphere(1, (0f, 5f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(2, (0f, 5f, 0f));
|
||||
var joint = world.AddMotorJoint(anchor, sphere, (0f, 5f, 0f), (hertz, 0.7f, maxForce), (0f, 0f, 0f));
|
||||
return (world, anchor, sphere, joint);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_strong_grab_follows_its_target_and_the_anchor_shows_its_pose()
|
||||
{
|
||||
var (world, anchor, sphere, joint) = Grab(maxForce: 20f * Mass * Gravity);
|
||||
using var _ = world;
|
||||
var view = world.View;
|
||||
Assert.Equal((uint)Box3DSoaKind.Anchor, view.Kind[anchor]);
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Motor, view.JointKind[joint]);
|
||||
var target = (1f, 5f, 0f);
|
||||
for (var i = 0; i < 60; i++)
|
||||
{
|
||||
world.SetAnchorTarget(anchor, target, default, Dt);
|
||||
world.Step(Dt);
|
||||
}
|
||||
Assert.True(Distance(view, sphere, target) < 0.02f, $"sphere {Distance(view, sphere, target)} m from the target");
|
||||
Assert.Equal(target.Item1, view.PositionX[anchor], 1e-3f); // the anchor reaches the pose at the end of the step
|
||||
Assert.Equal(0f, view.JointAngle[joint]);
|
||||
Assert.Equal(0f, view.Size0[anchor]); // no shape, so no size
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_anchor_reaches_its_target_at_the_end_of_the_very_next_step()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 1, gravityY: 0f);
|
||||
var anchor = world.AddAnchor(1, (0f, 0f, 0f));
|
||||
var view = world.View;
|
||||
world.SetAnchorTarget(anchor, (1f, 2f, 0f), default, Dt);
|
||||
world.Step(Dt);
|
||||
Assert.Equal(1f, view.PositionX[anchor], 1e-3f);
|
||||
Assert.Equal(2f, view.PositionY[anchor], 1e-3f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_anchor_holds_still_once_it_arrives_and_a_skipped_frame_flings_nothing()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 3, gravityY: 0f, jointCapacity: 1);
|
||||
var sphere = world.AddSphere(1, (0f, 0f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(2, (0f, 0f, 0f));
|
||||
world.AddMotorJoint(anchor, sphere, (0f, 0f, 0f), (5f, 0.7f, 1e6f), (0f, 0f, 0f));
|
||||
var view = world.View;
|
||||
world.SetAnchorTarget(anchor, (1f, 0f, 0f), default, Dt); // one target, 1 m away, then the caller sets no more
|
||||
for (var i = 0; i < 150; i++) world.Step(Dt);
|
||||
Assert.Equal(1f, view.PositionX[anchor], 1e-4f);
|
||||
Assert.Equal(0f, view.VelocityX[anchor]);
|
||||
Assert.Equal(1f, view.PositionX[sphere], 0.02f);
|
||||
Assert.True(MathF.Abs(view.VelocityX[sphere]) < 0.05f, "the grabbed body is not flung");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_grab_can_be_released_and_repeated_without_the_slots_growing()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, gravityY: -Gravity, jointCapacity: 1);
|
||||
var a = world.AddSphere(1, (0f, 5f, 0f), Radius, Density);
|
||||
var b = world.AddSphere(2, (3f, 5f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(3, (0f, 5f, 0f));
|
||||
var view = world.View;
|
||||
var strong = 20f * Mass * Gravity;
|
||||
for (var cycle = 0; cycle < 1000; cycle++)
|
||||
{
|
||||
var grabbed = cycle % 2 == 0 ? a : b;
|
||||
var at = (view.PositionX[grabbed], view.PositionY[grabbed], view.PositionZ[grabbed]);
|
||||
world.SetAnchorTarget(anchor, at, default, Dt);
|
||||
world.Step(Dt); // the anchor is on the body before the joint is made
|
||||
Assert.Equal(1, world.FreeJointSlots);
|
||||
var joint = world.AddMotorJoint(anchor, grabbed, at, (5f, 0.7f, strong), (0f, 0f, 0f));
|
||||
Assert.Equal(0, joint);
|
||||
world.Step(Dt);
|
||||
Assert.Equal(at.Item2, world.View.JointOriginY[joint], 0.05f); // live, the origin is the grab point
|
||||
world.DestroyJoint(joint);
|
||||
var jv = world.View; // joint count is as of when the view was taken
|
||||
// A destroyed lane is a tombstone this step and is not reused within it.
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Removed, jv.JointKind[joint]);
|
||||
Assert.Equal((-1, -1), (jv.JointBodyA[joint], jv.JointBodyB[joint]));
|
||||
Assert.Equal(0f, jv.JointFrameW[joint]);
|
||||
Assert.Equal((0f, 0f, 0f), (jv.JointOriginX[joint], jv.JointOriginY[joint], jv.JointOriginZ[joint]));
|
||||
Assert.Equal(0, world.FreeJointSlots);
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, grabbed, at, (5f, 0.7f, strong), (0f, 0f, 0f)));
|
||||
world.Step(Dt);
|
||||
}
|
||||
Assert.Equal(3, world.View.Count);
|
||||
Assert.Equal(1, world.View.JointCount);
|
||||
// Released, the sphere is free: it fell.
|
||||
Assert.True(view.PositionY[b] < 5f - 0.01f, "a released body falls");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_regrab_after_release_follows_the_anchor()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 3, gravityY: 0f, jointCapacity: 1);
|
||||
var sphere = world.AddSphere(1, (0f, 5f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(2, (0f, 5f, 0f));
|
||||
var view = world.View;
|
||||
var strong = 20f * Mass * Gravity;
|
||||
for (var round = 0; round < 3; round++)
|
||||
{
|
||||
var at = (view.PositionX[sphere], view.PositionY[sphere], view.PositionZ[sphere]);
|
||||
world.SetAnchorTarget(anchor, at, default, Dt);
|
||||
world.Step(Dt);
|
||||
var joint = world.AddMotorJoint(anchor, sphere, at, (5f, 0.7f, strong), (0f, 0f, 0f));
|
||||
var target = (1f + round, at.Item2, 0f);
|
||||
for (var i = 0; i < 90; i++) { world.SetAnchorTarget(anchor, target, default, Dt); world.Step(Dt); }
|
||||
Assert.True(Distance(view, sphere, target) < 0.02f, $"round {round}: {Distance(view, sphere, target)} m from the target");
|
||||
world.DestroyJoint(joint);
|
||||
world.Step(Dt);
|
||||
// Released: the anchor can go elsewhere and the sphere stays where it was left.
|
||||
var away = (target.Item1 + 5f, target.Item2, 0f);
|
||||
for (var i = 0; i < 30; i++) { world.SetAnchorTarget(anchor, away, default, Dt); world.Step(Dt); }
|
||||
Assert.True(MathF.Abs(view.PositionX[sphere] - target.Item1) < 0.1f, "the released sphere did not follow the anchor");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_stale_release_cannot_destroy_a_later_grab_in_a_reused_slot()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 3, gravityY: 0f, jointCapacity: 1);
|
||||
var sphere = world.AddSphere(1, (0f, 0f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(2, (0f, 0f, 0f));
|
||||
var first = world.AddMotorJoint(anchor, sphere, (0f, 0f, 0f), (5f, 0.7f, 1e6f), (0f, 0f, 0f));
|
||||
world.Step(Dt);
|
||||
world.DestroyJoint(first);
|
||||
world.Step(Dt); // the slot may now be reused
|
||||
var second = world.AddMotorJoint(anchor, sphere, (0f, 0f, 0f), (5f, 0.7f, 1e6f), (0f, 0f, 0f));
|
||||
Assert.Equal(first.Lane, second.Lane);
|
||||
Assert.NotEqual(first.Generation, second.Generation);
|
||||
Assert.Equal(second.Generation, world.View.JointGeneration[second.Lane]);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(first)); // the UI's second release click
|
||||
var view = world.View;
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Motor, view.JointKind[second.Lane]);
|
||||
for (var i = 0; i < 90; i++) { world.SetAnchorTarget(anchor, (1f, 0f, 0f), default, Dt); world.Step(Dt); }
|
||||
Assert.Equal(1f, view.PositionX[sphere], 0.02f); // the second grab still holds
|
||||
|
||||
world.DestroyJoint(second);
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(second));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_managed_side_refuses_a_native_library_of_another_abi_in_either_direction()
|
||||
{
|
||||
Assert.Equal(21u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
|
||||
Box3DSoaWorld.RequireNativeAbi(21);
|
||||
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(20)); // an older native under this managed build
|
||||
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(22)); // a newer one
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_joint_kind_destroys_through_one_path()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, gravityY: 0f, jointCapacity: 3);
|
||||
var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f));
|
||||
var sphere = world.AddSphere(2, (1f, 5f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(3, (1f, 5f, 0f));
|
||||
var hinge = world.AddJoint(Box3DSoaJointKind.Revolute, pin, sphere, (0f, 5f, 0f), (0f, 0f, 1f));
|
||||
var weld = world.AddJoint(Box3DSoaJointKind.Weld, anchor, sphere, (1f, 5f, 0f), (0f, 0f, 1f));
|
||||
var motor = world.AddMotorJoint(anchor, sphere, (1f, 5f, 0f), (5f, 0.7f, 100f), (0f, 0f, 0f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(new Box3DSoaJointHandle(-1, 0)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(new Box3DSoaJointHandle(3, 0)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(new Box3DSoaJointHandle(hinge.Lane, hinge.Generation + 1))); // stale
|
||||
var view = world.View;
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Revolute, view.JointKind[hinge]);
|
||||
foreach (var joint in new[] { hinge, weld, motor })
|
||||
{
|
||||
world.DestroyJoint(joint);
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Removed, view.JointKind[joint]);
|
||||
Assert.Equal(-1, view.JointBodyA[joint]);
|
||||
Assert.Equal(-1, view.JointBodyB[joint]);
|
||||
Assert.Equal(joint.Generation + 1, view.JointGeneration[joint]);
|
||||
Assert.Equal(0f, view.JointAngle[joint]);
|
||||
Assert.Equal(0f, view.JointOriginX[joint]);
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(joint)); // already gone
|
||||
}
|
||||
world.Step(Dt);
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Removed, view.JointKind[weld]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_world_with_no_joint_slot_is_seen_before_an_anchor_is_added()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, jointCapacity: 0);
|
||||
var sphere = world.AddSphere(1, (0f, 5f, 0f), Radius, Density);
|
||||
Assert.Equal(0, world.FreeJointSlots);
|
||||
Assert.Equal(3, world.FreeBodySlots);
|
||||
var anchorLane = -1;
|
||||
if (world.FreeJointSlots > 0) anchorLane = world.AddAnchor(2, (0f, 5f, 0f)); // the caller's check: no grab, no anchor
|
||||
Assert.Equal(-1, anchorLane);
|
||||
Assert.Equal(3, world.FreeBodySlots);
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(sphere, sphere, (0f, 5f, 0f), (5f, 0.7f, 1f), (0f, 0f, 0f)));
|
||||
Assert.Equal(1, world.View.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_angular_spring_turns_the_grabbed_body_to_the_anchors_rotation_and_off_leaves_it_free()
|
||||
{
|
||||
static float Turned(float angularHertz)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 3, gravityY: 0f, jointCapacity: 1);
|
||||
var box = world.AddBox(1, (0f, 5f, 0f), (0.2f, 0.2f, 0.2f), Density);
|
||||
var anchor = world.AddAnchor(2, (0f, 5f, 0f));
|
||||
world.AddMotorJoint(anchor, box, (0f, 5f, 0f), (5f, 0.7f, 1e5f), (angularHertz, 0.7f, 1e5f));
|
||||
var view = world.View;
|
||||
var quarterTurnZ = (0f, 0f, MathF.Sin(MathF.PI / 4), MathF.Cos(MathF.PI / 4));
|
||||
for (var i = 0; i < 90; i++)
|
||||
{
|
||||
world.SetAnchorTarget(anchor, (0f, 5f, 0f), quarterTurnZ, Dt);
|
||||
world.Step(Dt);
|
||||
}
|
||||
return 2f * MathF.Atan2(view.RotationZ[box], view.RotationW[box]);
|
||||
}
|
||||
|
||||
Assert.Equal(MathF.PI / 2, Turned(angularHertz: 5f), 0.05f);
|
||||
Assert.Equal(0f, Turned(angularHertz: 0f), 1e-3f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_weak_grab_is_bounded_by_its_max_force()
|
||||
{
|
||||
var maxForce = 0.5f * Mass * Gravity;
|
||||
var (world, anchor, sphere, _) = Grab(maxForce);
|
||||
using var _ = world;
|
||||
var view = world.View;
|
||||
var target = (0f, 6f, 0f);
|
||||
for (var i = 0; i < 60; i++)
|
||||
{
|
||||
world.SetAnchorTarget(anchor, target, default, Dt);
|
||||
world.Step(Dt);
|
||||
}
|
||||
// Whatever the spring does, it adds at most maxForce / m upward: the fall is at least that of a body
|
||||
// under g - F/m = 5 m/s^2, 2.5 m in a second. A spring that exceeded its bound would hold it higher.
|
||||
Assert.True(5f - view.PositionY[sphere] >= 2.4f, $"fell only {5f - view.PositionY[sphere]} m");
|
||||
Assert.True(view.PositionY[sphere] < target.Item2 - 1f, "the sphere hangs below the target and never reaches it");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Anchors_do_not_collide_and_are_never_hit_by_a_ray()
|
||||
{
|
||||
static float DropY(bool withAnchor)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 3, gravityY: -Gravity);
|
||||
var sphere = world.AddSphere(1, (0f, 3f, 0f), Radius, Density);
|
||||
if (withAnchor) world.AddAnchor(2, (0f, 1.5f, 0f));
|
||||
var view = world.View;
|
||||
for (var i = 0; i < 60; i++) world.Step(Dt);
|
||||
return view.PositionY[sphere];
|
||||
}
|
||||
|
||||
Assert.True(DropY(false) < 1f, "the sphere fell past y = 1.5");
|
||||
Assert.Equal(BitConverter.SingleToInt32Bits(DropY(false)), BitConverter.SingleToInt32Bits(DropY(true)));
|
||||
|
||||
using var w = new Box3DSoaWorld(capacity: 2);
|
||||
w.AddAnchor(2, (0f, 1.5f, 0f));
|
||||
Assert.False(w.CastRayClosest((0f, 3f, 0f), (0f, -3f, 0f)).Hit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_force_lanes_never_move_an_anchor()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 2, gravityY: -Gravity);
|
||||
var anchor = world.AddAnchor(1, (1f, 2f, 3f));
|
||||
var view = world.View;
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
view.ForceY[anchor] = 1e6f;
|
||||
view.TorqueZ[anchor] = 1e6f;
|
||||
world.Step(Dt);
|
||||
}
|
||||
Assert.Equal((1f, 2f, 3f), (view.PositionX[anchor], view.PositionY[anchor], view.PositionZ[anchor]));
|
||||
Assert.Equal(1f, view.RotationW[anchor]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_off_centre_impulse_turns_the_body()
|
||||
{
|
||||
const float r = 0.25f, density = 100f;
|
||||
var mass = density * 4f / 3f * MathF.PI * r * r * r;
|
||||
using var world = new Box3DSoaWorld(capacity: 2, gravityY: 0f);
|
||||
var sphere = world.AddSphere(1, (0f, 0f, 0f), r, density);
|
||||
var centred = world.AddSphere(2, (5f, 0f, 0f), r, density);
|
||||
var view = world.View;
|
||||
const float j = 2f;
|
||||
world.ApplyImpulse(sphere, (j, 0f, 0f), (0f, 0.1f, 0f));
|
||||
world.ApplyImpulse(centred, (j, 0f, 0f), (5f, 0f, 0f));
|
||||
world.Step(Dt);
|
||||
Assert.Equal(j / mass, view.VelocityX[sphere], 1e-4f);
|
||||
Assert.Equal(0f, view.VelocityY[sphere], 1e-4f);
|
||||
// r x J = (0, 0.1, 0) x (j, 0, 0) = (0, 0, -0.1 j): the spin is about -z, I = 2/5 m r^2.
|
||||
Assert.True(view.AngularVelocityZ[sphere] < 0f);
|
||||
Assert.Equal(-0.1f * j / (0.4f * mass * r * r), view.AngularVelocityZ[sphere], 0.02f);
|
||||
Assert.Equal(0f, view.AngularVelocityX[sphere], 1e-4f);
|
||||
// The same impulse through the centre of mass gives no spin.
|
||||
Assert.Equal(j / mass, view.VelocityX[centred], 1e-4f);
|
||||
Assert.Equal(0f, view.AngularVelocityZ[centred], 1e-4f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_ray_finds_the_nearest_body_with_its_lane_and_stable_id()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, gravityY: 0f);
|
||||
var far = world.AddSphere(12, (6f, 0f, 0f), 0.5f, 1f);
|
||||
var near = world.AddSphere(11, (3f, 0f, 0f), 0.5f, 1f);
|
||||
var hit = world.CastRayClosest((0f, 0f, 0f), (10f, 0f, 0f));
|
||||
Assert.True(hit.Hit);
|
||||
Assert.Equal(near, hit.Lane);
|
||||
Assert.NotEqual(far, hit.Lane);
|
||||
Assert.Equal(11ul, hit.StableId);
|
||||
Assert.Equal(2.5f, hit.Point.X, 1e-3f);
|
||||
Assert.Equal(0.25f, hit.Fraction, 1e-4f);
|
||||
Assert.Equal(-1f, hit.Normal.X, 1e-3f);
|
||||
Assert.False(world.CastRayClosest((0f, 0f, 0f), (0f, 10f, 0f)).Hit);
|
||||
Assert.Equal(default, world.CastRayClosest((0f, 0f, 0f), (0f, 10f, 0f)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Refused_calls_throw_and_change_nothing()
|
||||
{
|
||||
static Box3DSoaWorld Build(out int anchor, out int sphere, out int box)
|
||||
{
|
||||
var w = new Box3DSoaWorld(capacity: 5, gravityY: -Gravity, jointCapacity: 2);
|
||||
sphere = w.AddSphere(1, (0f, 2f, 0f), Radius, Density);
|
||||
box = w.AddStaticBox(2, (0f, -1f, 0f), (5f, 1f, 5f));
|
||||
anchor = w.AddAnchor(3, (0f, 2f, 0f));
|
||||
return w;
|
||||
}
|
||||
|
||||
using var world = Build(out var anchor, out var sphere, out var box);
|
||||
using var control = Build(out _, out _, out _);
|
||||
var nan = float.NaN;
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(sphere, (1f, 1f, 1f), default, Dt));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(box, (1f, 1f, 1f), default, Dt));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(9, (1f, 1f, 1f), default, Dt));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(anchor, (nan, 1f, 1f), default, Dt));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(anchor, (1f, 1f, 1f), (0f, 0f, nan, 1f), Dt));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(anchor, (1f, 1f, 1f), (0f, 0f, 0f, 2f), Dt));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetAnchorTarget(anchor, (1f, 1f, 1f), default, 0f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.ApplyImpulse(box, (1f, 0f, 0f), (0f, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.ApplyImpulse(anchor, (1f, 0f, 0f), (0f, 2f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.ApplyImpulse(sphere, (nan, 0f, 0f), (0f, 2f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.ApplyImpulse(sphere, (1f, 0f, 0f), (0f, float.PositiveInfinity, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.CastRayClosest((nan, 0f, 0f), (1f, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.CastRayClosest((0f, 0f, 0f), (0f, 0f, 0f)));
|
||||
foreach (var bad in new[] { -1f, nan, float.PositiveInfinity })
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, sphere, (0f, 2f, 0f), (bad, 0.7f, 100f), (0f, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, sphere, (0f, 2f, 0f), (5f, bad, 100f), (0f, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, sphere, (0f, 2f, 0f), (5f, 0.7f, bad), (0f, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, sphere, (0f, 2f, 0f), (5f, 0.7f, 100f), (bad, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, sphere, (0f, 2f, 0f), (5f, 0.7f, 100f), (1f, bad, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddMotorJoint(anchor, sphere, (0f, 2f, 0f), (5f, 0.7f, 100f), (1f, 0f, bad)));
|
||||
}
|
||||
Assert.Equal(0, world.View.JointCount);
|
||||
|
||||
for (var i = 0; i < 30; i++) { world.Step(Dt); control.Step(Dt); }
|
||||
Assert.Equal(Snapshot(control), Snapshot(world));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Two_identical_worlds_with_the_same_grab_and_impulses_match_bit_for_bit()
|
||||
{
|
||||
var a = Snapshot(RunGrab(0f));
|
||||
Assert.Equal(a, Snapshot(RunGrab(0f)));
|
||||
Assert.NotEqual(a, Snapshot(RunGrab(MathF.BitIncrement(1f) - 1f))); // one ulp of impulse is seen
|
||||
}
|
||||
|
||||
private static Box3DSoaWorld RunGrab(float impulseNudge)
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: 5, gravityY: -Gravity, jointCapacity: 2);
|
||||
var slab = world.AddStaticBox(1, (0f, -1f, 0f), (10f, 1f, 10f));
|
||||
var ball = world.AddSphere(2, (0f, 1f, 0f), Radius, Density);
|
||||
var other = world.AddSphere(3, (1.5f, 0.2f, 0f), Radius, Density);
|
||||
var anchor = world.AddAnchor(4, (0f, 1f, 0f));
|
||||
world.AddMotorJoint(anchor, ball, (0f, 1f, 0f), (4f, 0.5f, 8f * Mass * Gravity), (2f, 0.5f, 5f));
|
||||
for (var i = 0; i < 300; i++)
|
||||
{
|
||||
var t = i * Dt;
|
||||
world.SetAnchorTarget(anchor, (MathF.Sin(t) * 1.5f, 1f + 0.5f * MathF.Cos(2f * t), 0.3f * t), default, Dt);
|
||||
if (i == 100) world.ApplyImpulse(other, (0.5f + impulseNudge, 0.2f, 0f), (1.5f, 0.3f, 0f));
|
||||
world.Step(Dt);
|
||||
}
|
||||
_ = slab;
|
||||
return world;
|
||||
}
|
||||
|
||||
/// <summary>Every state lane of the world as bytes, disposing the world.</summary>
|
||||
private static byte[] Snapshot(Box3DSoaWorld world)
|
||||
{
|
||||
using var _ = world;
|
||||
var v = world.View;
|
||||
var bytes = new List<byte>();
|
||||
void Add(ReadOnlySpan<float> lane) => bytes.AddRange(MemoryMarshal.AsBytes(lane).ToArray());
|
||||
Add(v.PositionX); Add(v.PositionY); Add(v.PositionZ);
|
||||
Add(v.RotationX); Add(v.RotationY); Add(v.RotationZ); Add(v.RotationW);
|
||||
Add(v.VelocityX); Add(v.VelocityY); Add(v.VelocityZ);
|
||||
Add(v.AngularVelocityX); Add(v.AngularVelocityY); Add(v.AngularVelocityZ);
|
||||
for (var j = 0; j < v.JointCount; j++) bytes.AddRange(BitConverter.GetBytes(v.JointRotationW[j]));
|
||||
return [.. bytes];
|
||||
}
|
||||
}
|
||||
122
tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs
Normal file
122
tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>What a builder made: the particles, the distances between them and the bends over pairs of distances.</summary>
|
||||
internal sealed record Made(Box3DSoaParticleHandle[] Particles, Box3DSoaConstraintHandle[] Edges, Box3DSoaConstraintHandle[] Bends);
|
||||
|
||||
/// <summary>
|
||||
/// Test-local builders. Ymir has no rope or sheet: both are only the constraints these functions emit through the
|
||||
/// public commands, so the tests exercise exactly the surface a game would.
|
||||
/// </summary>
|
||||
internal static class Graph
|
||||
{
|
||||
public static Pos[] Line(Pos from, Pos step, int count)
|
||||
{
|
||||
var p = new Pos[count];
|
||||
for (var i = 0; i < count; i++) p[i] = (from.X + step.X * i, from.Y + step.Y * i, from.Z + step.Z * i);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>Particles at <paramref name="positions"/> (rest pose <paramref name="rest"/> or the same), a distance between neighbours and a bend over each pair of distances.</summary>
|
||||
public static Made Rope(
|
||||
Box3DSoaWorld world, Pos[] positions, float mass, float radius, uint phase = 0, float stretch = 0f, float bend = 1e-4f,
|
||||
float maxAngle = -1f, Pos[]? rest = null, float[]? masses = null, Pos velocity = default, uint material = 0)
|
||||
{
|
||||
var n = positions.Length;
|
||||
var desc = new Box3DSoaParticleDesc[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
desc[i] = new Box3DSoaParticleDesc(positions[i], masses?[i] ?? mass, radius, phase, material, rest?[i], velocity);
|
||||
var particles = new Box3DSoaParticleHandle[n];
|
||||
world.CreateParticles(desc, particles);
|
||||
var edges = new Box3DSoaConstraintHandle[n - 1];
|
||||
var d = new Box3DSoaDistanceDesc[n - 1];
|
||||
for (var i = 0; i + 1 < n; i++) d[i] = new Box3DSoaDistanceDesc(particles[i], particles[i + 1], stretch);
|
||||
world.CreateDistances(d, edges);
|
||||
var bends = Array.Empty<Box3DSoaConstraintHandle>();
|
||||
if (bend >= 0f || maxAngle >= 0f)
|
||||
{
|
||||
bends = new Box3DSoaConstraintHandle[Math.Max(0, n - 2)];
|
||||
var b = new Box3DSoaBendDesc[bends.Length];
|
||||
for (var i = 0; i + 2 < n; i++) b[i] = new Box3DSoaBendDesc(edges[i], edges[i + 1], bend, maxAngle);
|
||||
world.CreateBends(b, bends);
|
||||
}
|
||||
return new Made(particles, edges, bends);
|
||||
}
|
||||
|
||||
/// <summary>An <paramref name="nu"/> x <paramref name="nv"/> grid: distances along both axes, bends along both.</summary>
|
||||
public static Made Sheet(
|
||||
Box3DSoaWorld world, Pos origin, Pos du, Pos dv, int nu, int nv, float mass, float radius, uint phase = 0,
|
||||
float stretch = 0f, float bend = 1e-4f)
|
||||
{
|
||||
var desc = new Box3DSoaParticleDesc[nu * nv];
|
||||
for (var j = 0; j < nv; j++)
|
||||
for (var i = 0; i < nu; i++)
|
||||
desc[j * nu + i] = new Box3DSoaParticleDesc(
|
||||
(origin.X + du.X * i + dv.X * j, origin.Y + du.Y * i + dv.Y * j, origin.Z + du.Z * i + dv.Z * j), mass, radius, phase);
|
||||
var p = new Box3DSoaParticleHandle[nu * nv];
|
||||
world.CreateParticles(desc, p);
|
||||
var d = new List<Box3DSoaDistanceDesc>();
|
||||
for (var j = 0; j < nv; j++) for (var i = 0; i + 1 < nu; i++) d.Add(new(p[j * nu + i], p[j * nu + i + 1], stretch));
|
||||
var uCount = d.Count;
|
||||
for (var j = 0; j + 1 < nv; j++) for (var i = 0; i < nu; i++) d.Add(new(p[j * nu + i], p[(j + 1) * nu + i], stretch));
|
||||
var e = new Box3DSoaConstraintHandle[d.Count];
|
||||
world.CreateDistances(d.ToArray(), e);
|
||||
var b = new List<Box3DSoaBendDesc>();
|
||||
for (var j = 0; j < nv; j++) for (var i = 0; i + 2 < nu; i++) b.Add(new(e[j * (nu - 1) + i], e[j * (nu - 1) + i + 1], bend));
|
||||
for (var j = 0; j + 2 < nv; j++) for (var i = 0; i < nu; i++) b.Add(new(e[uCount + j * nu + i], e[uCount + (j + 1) * nu + i], bend));
|
||||
var bends = new Box3DSoaConstraintHandle[b.Count];
|
||||
world.CreateBends(b.ToArray(), bends);
|
||||
return new Made(p, e, bends);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An <paramref name="nx"/> x <paramref name="ny"/> x <paramref name="nz"/> block of particles on a simple-cubic lattice at spacing
|
||||
/// 2 <paramref name="radius"/> (or <paramref name="pitch"/>), the first particle's centre at <paramref name="origin"/>, x fastest. No constraint: pass the fluid phase for a liquid.
|
||||
/// </summary>
|
||||
public static Box3DSoaParticleHandle[] Block(
|
||||
Box3DSoaWorld world, Pos origin, int nx, int ny, int nz, float radius, float mass, uint phase, uint material = 0, Pos velocity = default, float pitch = 0f)
|
||||
{
|
||||
var desc = new Box3DSoaParticleDesc[nx * ny * nz];
|
||||
var s = pitch > 0f ? pitch : 2f * radius;
|
||||
for (var k = 0; k < nz; k++)
|
||||
for (var j = 0; j < ny; j++)
|
||||
for (var i = 0; i < nx; i++)
|
||||
desc[(k * ny + j) * nx + i] = new Box3DSoaParticleDesc(
|
||||
(origin.X + s * i, origin.Y + s * j, origin.Z + s * k), mass, radius, phase, material, null, velocity);
|
||||
var p = new Box3DSoaParticleHandle[desc.Length];
|
||||
world.CreateParticles(desc, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
public static float Dist(Box3DSoaView v, int a, int b) =>
|
||||
MathF.Sqrt(Sq(v.ParticleX[a] - v.ParticleX[b]) + Sq(v.ParticleY[a] - v.ParticleY[b]) + Sq(v.ParticleZ[a] - v.ParticleZ[b]));
|
||||
|
||||
public static float Sq(float x) => x * x;
|
||||
|
||||
/// <summary>The summed length of the given distances over their summed rest lengths, minus 1.</summary>
|
||||
public static float Stretch(Box3DSoaView v, Made m)
|
||||
{
|
||||
float length = 0f, rest = 0f;
|
||||
foreach (var e in m.Edges)
|
||||
{
|
||||
length += Dist(v, v.DistanceA[e.Lane], v.DistanceB[e.Lane]);
|
||||
rest += v.DistanceRest[e.Lane];
|
||||
}
|
||||
return length / rest - 1f;
|
||||
}
|
||||
|
||||
public static float Dens(float mass, float radius) => mass / (4f / 3f * MathF.PI * radius * radius * radius);
|
||||
}
|
||||
|
||||
internal static class Readings
|
||||
{
|
||||
/// <summary>Appends a line to the file named by YMIR_READINGS when that variable is set (the numbers the tests judge).</summary>
|
||||
public static void Add(string line)
|
||||
{
|
||||
var path = Environment.GetEnvironmentVariable("YMIR_READINGS");
|
||||
if (!string.IsNullOrEmpty(path)) File.AppendAllText(path, line + "\n");
|
||||
}
|
||||
}
|
||||
341
tests/Ymir.Box3D.Soa.Tests/Box3DSoaImpulseTests.cs
Normal file
341
tests/Ymir.Box3D.Soa.Tests/Box3DSoaImpulseTests.cs
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// ContactImpulse and the hit fact's Impulse are the normal impulse contacts delivered over the whole step. The
|
||||
/// oracle is momentum: only contacts and gravity act, so over one step the contact impulse along the contact normal
|
||||
/// is the change of the system's momentum along it plus the weight's impulse, whatever the joints and sub-steps did.
|
||||
/// </summary>
|
||||
public sealed class Box3DSoaImpulseTests
|
||||
{
|
||||
private const float G = 10f;
|
||||
private static readonly (float, float, float, float) QuarterTurnZ = (0f, 0f, MathF.Sin(MathF.PI / 4), MathF.Cos(MathF.PI / 4));
|
||||
|
||||
private static float SphereMass(float radius, float density) => 4f / 3f * MathF.PI * radius * radius * radius * density;
|
||||
private static float CapsuleMass(float radius, float halfLength, float density) =>
|
||||
MathF.PI * radius * radius * (2f * halfLength + 4f / 3f * radius) * density;
|
||||
|
||||
/// <summary>Momentum along Y of the given lanes with their masses.</summary>
|
||||
private static double MomentumY(Box3DSoaWorld world, (int Lane, float Mass)[] bodies)
|
||||
{
|
||||
double p = 0;
|
||||
foreach (var (lane, mass) in bodies) p += (double)mass * world.View.VelocityY[lane];
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Torso box 23.8 kg, upper-arm capsule on a spherical shoulder and forearm capsule on a revolute elbow, as in the
|
||||
/// probe that measured Box3D. Lanes 0, 1, 2; the arm lies along +X with the forearm's centre at x = 0.78.
|
||||
/// </summary>
|
||||
private static (Box3DSoaWorld World, (int Lane, float Mass)[] Arm) Arm(float gravityY)
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: 16, gravityY: gravityY, jointCapacity: 2);
|
||||
var torso = world.AddBox(1, (0f, 0f, 0f), (0.175f, 0.25f, 0.1f), 680f);
|
||||
var upper = world.AddCapsule(2, (0.40f, 0.2f, 0f), 0.045f, 0.15f, 1000f, rotation: QuarterTurnZ);
|
||||
var fore = world.AddCapsule(3, (0.78f, 0.2f, 0f), 0.04f, 0.14f, 1000f, rotation: QuarterTurnZ);
|
||||
world.AddJoint(Box3DSoaJointKind.Spherical, torso, upper, (0.2f, 0.2f, 0f), (0f, 0f, 1f));
|
||||
world.AddJoint(Box3DSoaJointKind.Revolute, upper, fore, (0.6f, 0.2f, 0f), (0f, 0f, 1f));
|
||||
var arm = new (int Lane, float Mass)[] { (torso, 0.35f * 0.5f * 0.2f * 680f), (upper, CapsuleMass(0.045f, 0.15f, 1000f)), (fore, CapsuleMass(0.04f, 0.14f, 1000f)) };
|
||||
return (world, arm);
|
||||
}
|
||||
|
||||
/// <summary>Fires a ball at the forearm from above; returns the sum over the run of the forearm's ContactImpulse and the ball's -m dv.</summary>
|
||||
private static (double Delivered, double Truth, double Peak, int Hits) Strike(float radius, float mass, float speed, float restitution, float gap, int hz, int subSteps, int steps)
|
||||
{
|
||||
var (world, _) = Arm(0f);
|
||||
using var _w = world;
|
||||
const int fore = 2;
|
||||
// Box3D opens a contact only once shapes overlap and a fast ball would be through the forearm by then (its
|
||||
// continuous collision is for static shapes and bullets, which the SoA world has none of). So the ball starts at
|
||||
// rest where the contact exists (a negative gap overlaps by that much) and an impulse launches it into the forearm.
|
||||
var ball = world.AddSphere(10, (0.78f, 0.2f + 0.04f + radius + gap, 0f), radius, mass / SphereMass(radius, 1f), restitution: restitution);
|
||||
var dt = 1f / hz;
|
||||
world.Step(dt, subSteps);
|
||||
world.Step(dt, subSteps);
|
||||
world.ApplyImpulse(ball, (0f, -mass * speed, 0f), (0.78f, 0.2f + 0.04f + radius + gap, 0f));
|
||||
var launched = -(double)mass * speed;
|
||||
var truths = new double[steps];
|
||||
var lanes = new float[steps];
|
||||
var hitImpulse = new float[steps];
|
||||
var hitSteps = new bool[steps];
|
||||
var hits = 0;
|
||||
var before = launched;
|
||||
for (var i = 0; i < steps; i++)
|
||||
{
|
||||
world.Step(dt, subSteps);
|
||||
var after = (double)mass * world.View.VelocityY[ball];
|
||||
truths[i] = after - before;
|
||||
before = after;
|
||||
lanes[i] = world.View.ContactImpulse[fore];
|
||||
foreach (var hit in world.Facts.Hit) { hitImpulse[i] += hit.Impulse; hitSteps[i] = true; hits++; }
|
||||
}
|
||||
var peak = truths.Max(Math.Abs);
|
||||
for (var i = 0; i < steps; i++)
|
||||
{
|
||||
Assert.True(Math.Abs(lanes[i] - truths[i]) <= 1e-4 * peak, $"step {i}: forearm ContactImpulse {lanes[i]} vs the ball's momentum change {truths[i]}");
|
||||
if (hitSteps[i]) Assert.Equal(lanes[i], hitImpulse[i], 1e-4 * peak);
|
||||
}
|
||||
var delivered = (double)lanes.Sum();
|
||||
var truth = truths.Sum();
|
||||
return (delivered, truth, peak, hits);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(0.5f)]
|
||||
public void A_jointed_forearm_hit_is_exact_per_step_and_the_hit_carries_the_same_impulse(float restitution)
|
||||
{
|
||||
var (delivered, truth, peak, hits) = Strike(0.1f, 5f, 10f, restitution, gap: 0.05f, hz: 60, subSteps: 4, steps: 9);
|
||||
Assert.InRange(peak, 14f, 25f); // a 5 kg ball at 10 m/s onto a forearm: tens of N s, not the tenth the ball's own approach speed implies
|
||||
Assert.Equal(truth, delivered, 1e-4 * peak);
|
||||
Assert.Equal(1, hits); // the hit fact carried the impulse checked above
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_BB_is_not_a_cannonball()
|
||||
{
|
||||
var (bb, bbTruth, _, _) = Strike(0.003f, 0.0003f, 100f, 0f, gap: -0.001f, hz: 60, subSteps: 4, steps: 9);
|
||||
Assert.True(bb >= 0.030f * 0.99f && bb <= 0.030f * 1.01f, $"BB delivered {bb} N s");
|
||||
Assert.Equal(bbTruth, bb, 1e-6);
|
||||
var (ball, _, _, _) = Strike(0.1f, 5f, 10f, 0f, gap: 0.05f, hz: 60, subSteps: 4, steps: 9);
|
||||
Assert.True(ball > 400f * bb, $"the ball's {ball} N s dwarfs the BB's {bb} N s");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_forearm_falling_onto_a_wall_delivers_the_whole_arms_momentum_change()
|
||||
{
|
||||
// The forearm lands on a slab while the shoulder and elbow keep the rest of the arm moving: the wall's impulse is
|
||||
// the change of the three bodies' momentum plus their weight, not the forearm's own.
|
||||
var (world, arm) = Arm(-G);
|
||||
using var _w = world;
|
||||
world.AddStaticBox(9, (1.0f, 0.2f - 0.04f - 0.8f - 0.1f, 0f), (0.3f, 0.1f, 0.5f)); // under the forearm only: the upper arm never reaches it
|
||||
var totalMass = arm.Sum(b => b.Mass);
|
||||
const int fore = 2;
|
||||
var dt = 1f / 60f;
|
||||
double peak = 0;
|
||||
var truths = new List<(double Truth, float Lane)>();
|
||||
for (var i = 0; i < 90; i++)
|
||||
{
|
||||
var before = MomentumY(world, arm);
|
||||
world.Step(dt, 4);
|
||||
var truth = MomentumY(world, arm) - before + totalMass * G * dt;
|
||||
truths.Add((truth, world.View.ContactImpulse[fore]));
|
||||
peak = Math.Max(peak, Math.Abs(truth));
|
||||
}
|
||||
Assert.True(peak > 10.0, $"the arm hit the slab (peak {peak} N s)");
|
||||
for (var i = 0; i < truths.Count; i++)
|
||||
{
|
||||
Assert.True(Math.Abs(truths[i].Lane - truths[i].Truth) <= 1e-4 * peak, $"step {i}: {truths[i].Lane} vs {truths[i].Truth}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_swung_arm_into_a_wall_delivers_the_whole_arms_momentum_change()
|
||||
{
|
||||
// The swing the probe measured: impulses launch the upper arm and the forearm off-centre (spin included) at 6 m/s,
|
||||
// no gravity, and the forearm meets a slab. The wall's impulse is the three bodies' momentum change.
|
||||
var (world, arm) = Arm(0f);
|
||||
using var _w = world;
|
||||
world.AddStaticBox(9, (1.0f, 0.2f - 0.04f - 0.5f - 0.1f, 0f), (0.3f, 0.1f, 0.5f), friction: 0f); // under the forearm only; frictionless, as the lane is the normal channel only
|
||||
const int fore = 2;
|
||||
world.ApplyImpulse(1, (0f, -arm[1].Mass * 6f, 0f), (0.55f, 0.2f, 0f));
|
||||
world.ApplyImpulse(fore, (0f, -arm[2].Mass * 6f, 0f), (0.95f, 0.2f, 0f));
|
||||
// The swung forearm meets the slab at a tilt, so the impulse is along the contact normal, not Y: the truth is the
|
||||
// length of the momentum change vector (every contact point of the one contact shares its normal).
|
||||
var before = (X: 0.0, Y: -(double)(arm[1].Mass + arm[2].Mass) * 6f, Z: 0.0);
|
||||
var dt = 1f / 60f;
|
||||
var truths = new List<double>();
|
||||
var lanes = new List<float>();
|
||||
for (var i = 0; i < 8; i++) // the impact is step 3; after it the forearm swings into its own torso, an internal contact whose impulses cancel in the sum
|
||||
{
|
||||
world.Step(dt, 4);
|
||||
var v = world.View;
|
||||
var after = (X: 0.0, Y: 0.0, Z: 0.0);
|
||||
foreach (var (lane, mass) in arm) after = (after.X + (double)mass * v.VelocityX[lane], after.Y + (double)mass * v.VelocityY[lane], after.Z + (double)mass * v.VelocityZ[lane]);
|
||||
var dx = after.X - before.X; var dy = after.Y - before.Y; var dz = after.Z - before.Z;
|
||||
truths.Add(Math.Sqrt(dx * dx + dy * dy + dz * dz));
|
||||
before = after;
|
||||
lanes.Add(v.ContactImpulse[fore]);
|
||||
}
|
||||
var peak = truths.Max(Math.Abs);
|
||||
Assert.True(peak > 5.0, $"the arm hit the slab (peak {peak} N s)");
|
||||
for (var i = 0; i < truths.Count; i++)
|
||||
{
|
||||
Assert.True(Math.Abs(lanes[i] - truths[i]) <= 1e-4 * peak, $"step {i}: {lanes[i]} vs {truths[i]}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(0.5f)]
|
||||
public void A_body_with_more_contacts_than_graph_colours_still_reads_every_one(float restitution)
|
||||
{
|
||||
// One big sphere with 60 small ones converging on it: more contacts on the big body than Box3D has graph colours,
|
||||
// so some are solved by its overflow path. Each small ball has one contact, so its lane is its own momentum
|
||||
// change; the big ball's lane is the sum of theirs.
|
||||
const int count = 60;
|
||||
const float bigRadius = 0.5f, smallRadius = 0.05f, speed = 4f;
|
||||
using var world = new Box3DSoaWorld(capacity: count + 2, gravityY: 0f);
|
||||
var big = world.AddSphere(1, (0f, 0f, 0f), bigRadius, 500f, restitution: restitution);
|
||||
var smallMass = SphereMass(smallRadius, 500f);
|
||||
var smalls = new int[count];
|
||||
var dirs = new (float X, float Y, float Z)[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var y = 1f - 2f * (i + 0.5f) / count;
|
||||
var r = MathF.Sqrt(1f - y * y);
|
||||
var a = i * MathF.PI * (3f - MathF.Sqrt(5f));
|
||||
dirs[i] = (r * MathF.Cos(a), y, r * MathF.Sin(a));
|
||||
var d = bigRadius + smallRadius - 0.001f;
|
||||
smalls[i] = world.AddSphere((ulong)(10 + i), (dirs[i].X * d, dirs[i].Y * d, dirs[i].Z * d), smallRadius, 500f, restitution: restitution);
|
||||
}
|
||||
var dt = 1f / 60f;
|
||||
world.Step(dt);
|
||||
world.Step(dt);
|
||||
Assert.True(world.View.ContactCount[big] > 24, $"the big ball has {world.View.ContactCount[big]} contacts, more than Box3D has graph colours");
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
world.ApplyImpulse(smalls[i], (-dirs[i].X * smallMass * speed, -dirs[i].Y * smallMass * speed, -dirs[i].Z * smallMass * speed),
|
||||
(dirs[i].X * bigRadius, dirs[i].Y * bigRadius, dirs[i].Z * bigRadius));
|
||||
}
|
||||
var launched = new (double X, double Y, double Z)[count];
|
||||
for (var i = 0; i < count; i++) launched[i] = (-dirs[i].X * smallMass * speed, -dirs[i].Y * smallMass * speed, -dirs[i].Z * smallMass * speed);
|
||||
var peak = 0.0;
|
||||
var steps = 12;
|
||||
var sumOfSmalls = new double[steps];
|
||||
var bigLane = new float[steps];
|
||||
var worst = new double[steps];
|
||||
for (var s = 0; s < steps; s++)
|
||||
{
|
||||
world.Step(dt);
|
||||
var v = world.View;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var l = smalls[i];
|
||||
var now = (X: (double)smallMass * v.VelocityX[l], Y: (double)smallMass * v.VelocityY[l], Z: (double)smallMass * v.VelocityZ[l]);
|
||||
var dp = Math.Sqrt((now.X - launched[i].X) * (now.X - launched[i].X) + (now.Y - launched[i].Y) * (now.Y - launched[i].Y) + (now.Z - launched[i].Z) * (now.Z - launched[i].Z));
|
||||
launched[i] = now;
|
||||
sumOfSmalls[s] += v.ContactImpulse[l];
|
||||
worst[s] = Math.Max(worst[s], Math.Abs(v.ContactImpulse[l] - dp));
|
||||
peak = Math.Max(peak, dp);
|
||||
}
|
||||
bigLane[s] = v.ContactImpulse[big];
|
||||
}
|
||||
Assert.True(peak > 0.5, $"the small balls hit (peak {peak} N s)");
|
||||
for (var s = 0; s < steps; s++)
|
||||
{
|
||||
Assert.True(Math.Abs(bigLane[s] - sumOfSmalls[s]) <= 1e-4 * sumOfSmalls.Max(), $"step {s}: big {bigLane[s]} vs the smalls' sum {sumOfSmalls[s]}");
|
||||
Assert.True(worst[s] <= 1e-3 * peak, $"step {s}: a small ball's lane is off its momentum change by {worst[s]}");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(60, 1, 0f)]
|
||||
[InlineData(60, 4, 0f)]
|
||||
[InlineData(60, 1, 0.5f)]
|
||||
[InlineData(60, 4, 0.5f)]
|
||||
[InlineData(240, 1, 0f)]
|
||||
[InlineData(240, 4, 0f)]
|
||||
[InlineData(240, 1, 0.5f)]
|
||||
[InlineData(240, 4, 0.5f)]
|
||||
public void Drop_impulse_is_exact_every_step(int hz, int subSteps, float restitution)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, gravityY: -G);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (50f, 0.5f, 50f));
|
||||
const float radius = 0.1f;
|
||||
const float density = 125f; // 0.52 kg
|
||||
var ball = world.AddSphere(2, (0f, 1.5f, 0f), radius, density, restitution: restitution);
|
||||
var mass = SphereMass(radius, density);
|
||||
var dt = 1f / hz;
|
||||
var truths = new double[hz];
|
||||
var lanes = new float[hz];
|
||||
var hits = 0;
|
||||
for (var i = 0; i < hz; i++)
|
||||
{
|
||||
var before = (double)mass * world.View.VelocityY[ball];
|
||||
world.Step(dt, subSteps);
|
||||
truths[i] = mass * (double)world.View.VelocityY[ball] - before + mass * G * dt;
|
||||
lanes[i] = world.View.ContactImpulse[ball];
|
||||
foreach (var hit in world.Facts.Hit)
|
||||
{
|
||||
hits++;
|
||||
Assert.Equal(lanes[i], hit.Impulse, 1e-4 * truths.Max(Math.Abs));
|
||||
}
|
||||
}
|
||||
var peak = truths.Max(Math.Abs);
|
||||
Assert.InRange(peak, 2.5, 6.0);
|
||||
Assert.True(hits >= 1);
|
||||
for (var i = 0; i < hz; i++)
|
||||
{
|
||||
Assert.True(Math.Abs(lanes[i] - truths[i]) <= 1e-4 * peak, $"step {i}: {lanes[i]} vs {truths[i]}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Each_hit_reads_its_own_pair_when_the_slab_has_several_contacts()
|
||||
{
|
||||
// Two balls of different mass land on the slab in the same step: the slab's contact list holds both, and each hit
|
||||
// fact is its own ball's impulse, whichever of the slab's contacts Box3D lists first.
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (50f, 0.5f, 50f));
|
||||
var light = world.AddSphere(2, (-1f, 1.5f, 0f), 0.1f, 125f);
|
||||
var heavy = world.AddSphere(3, (1f, 1.5f, 0f), 0.1f, 500f);
|
||||
var dt = 1f / 60f;
|
||||
var checkedHits = 0;
|
||||
for (var i = 0; i < 90; i++)
|
||||
{
|
||||
world.Step(dt);
|
||||
foreach (var hit in world.Facts.Hit)
|
||||
{
|
||||
var ball = hit.LaneA == light || hit.LaneB == light ? light : heavy;
|
||||
Assert.Equal(world.View.ContactImpulse[ball], hit.Impulse, 1e-3f);
|
||||
checkedHits++;
|
||||
}
|
||||
}
|
||||
Assert.Equal(2, checkedHits);
|
||||
Assert.Equal(world.View.ContactImpulse[heavy] / 4f, world.View.ContactImpulse[light], 1e-3f); // resting: weight scales with mass
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resting_impulse_is_the_weight_and_a_body_touching_nothing_reads_zero()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (50f, 0.5f, 50f));
|
||||
world.AddSphere(2, (0f, 0.6f, 0f), 0.5f, 1f);
|
||||
world.AddSphere(3, (10f, 1000f, 10f), 0.5f, 1f); // still falling after the whole run
|
||||
var dt = 1f / 60f;
|
||||
for (var i = 0; i < 300; i++) world.Step(dt);
|
||||
var weight = SphereMass(0.5f, 1f) * G;
|
||||
var view = world.View;
|
||||
Assert.InRange(view.ContactImpulse[1] / dt, weight * 0.999f, weight * 1.001f);
|
||||
Assert.InRange(view.ContactImpulse[0] / dt, weight * 0.999f, weight * 1.001f); // the slab carries the same load
|
||||
Assert.Equal(0f, view.ContactImpulse[2]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f)]
|
||||
[InlineData(0.5f)]
|
||||
public void Two_free_bodies_exchange_exactly_the_momentum_B_gains(float restitution)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, gravityY: 0f);
|
||||
world.AddSphere(10, (-0.5f, 0f, 0f), 0.1f, 1f / SphereMass(0.1f, 1f), velocity: (5f, 0f, 0f), restitution: restitution);
|
||||
var b = world.AddSphere(11, (0f, 0f, 0f), 0.1f, 3f / SphereMass(0.1f, 1f), restitution: restitution);
|
||||
const float massB = 3f;
|
||||
const float dt = 1f / 60f;
|
||||
double delivered = 0, truth = 0, peak = 0;
|
||||
for (var i = 0; i < 12; i++)
|
||||
{
|
||||
var before = (double)massB * world.View.VelocityX[b];
|
||||
world.Step(dt);
|
||||
var step = massB * (double)world.View.VelocityX[b] - before;
|
||||
peak = Math.Max(peak, Math.Abs(step));
|
||||
Assert.True(Math.Abs(world.View.ContactImpulse[b] - step) <= 1e-4 * Math.Max(peak, 1e-6), $"step {i}");
|
||||
foreach (var hit in world.Facts.Hit) Assert.Equal(world.View.ContactImpulse[b], hit.Impulse, 1e-4 * peak);
|
||||
delivered += world.View.ContactImpulse[b];
|
||||
truth += step;
|
||||
}
|
||||
Assert.InRange(peak, 3.5, 6.0);
|
||||
Assert.Equal(truth, delivered, 1e-4 * peak);
|
||||
}
|
||||
}
|
||||
|
|
@ -59,6 +59,55 @@ public sealed class Box3DSoaJointTests
|
|||
Assert.Equal(-1, view.Parent[anchor]);
|
||||
}
|
||||
|
||||
private static (float X, float Y, float Z) Rotate((float X, float Y, float Z, float W) q, (float X, float Y, float Z) o)
|
||||
{
|
||||
var (tx, ty, tz) = (2f * (q.Y * o.Z - q.Z * o.Y), 2f * (q.Z * o.X - q.X * o.Z), 2f * (q.X * o.Y - q.Y * o.X)); // 2 (q.v x o)
|
||||
return (o.X + q.W * tx + (q.Y * tz - q.Z * ty), o.Y + q.W * ty + (q.Z * tx - q.X * tz), o.Z + q.W * tz + (q.X * ty - q.Y * tx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Joint_origin_lane_equals_the_anchor_at_creation_and_follows_body_a()
|
||||
{
|
||||
// No gravity. Body A is translated AND rotated, so the world anchor and the local offset differ in every
|
||||
// component: a lane that stored the world anchor (or the local offset) instead of A's pose applied to it fails.
|
||||
using var world = new Box3DSoaWorld(capacity: 2, gravityY: 0f, jointCapacity: 1);
|
||||
var (ax, ay, az) = (0.5f, 1f, 0.2f);
|
||||
var n = MathF.Sqrt(ax * ax + ay * ay + az * az);
|
||||
var half = 0.4f;
|
||||
var rotA = (X: ax / n * MathF.Sin(half), Y: ay / n * MathF.Sin(half), Z: az / n * MathF.Sin(half), W: MathF.Cos(half));
|
||||
var posA = (X: 2f, Y: 3f, Z: -1f);
|
||||
var anchor = (X: 2.4f, Y: 3.3f, Z: -0.7f);
|
||||
var a = world.AddBox(1, posA, (0.2f, 0.2f, 0.2f), 1f, rotation: rotA);
|
||||
var b = world.AddBox(2, (3f, 3.3f, -1f), (0.2f, 0.2f, 0.2f), 1f, parent: a);
|
||||
var j = world.AddJoint(Box3DSoaJointKind.Spherical, a, b, anchor, (0f, 0f, 1f));
|
||||
var v = world.View;
|
||||
Assert.Equal(anchor.X, v.JointOriginX[j], 1e-4f);
|
||||
Assert.Equal(anchor.Y, v.JointOriginY[j], 1e-4f);
|
||||
Assert.Equal(anchor.Z, v.JointOriginZ[j], 1e-4f);
|
||||
|
||||
// The creation-time offsets, found by undoing A's and B's creation poses (conjugate = inverse of a unit quaternion).
|
||||
var conjA = (-rotA.X, -rotA.Y, -rotA.Z, rotA.W);
|
||||
var localA = Rotate(conjA, (anchor.X - posA.X, anchor.Y - posA.Y, anchor.Z - posA.Z));
|
||||
var localB = (X: anchor.X - 3f, Y: anchor.Y - 3.3f, Z: anchor.Z + 1f); // B was created unrotated
|
||||
|
||||
// Kick body A off-centre so it moves and turns for 240 steps; the lane is A's current pose applied to the offset.
|
||||
world.ApplyImpulse(a, (0f, 1f, 0.5f), (posA.X - 0.1f, posA.Y, posA.Z));
|
||||
for (var i = 0; i < 240; i++) world.Step(Dt);
|
||||
var qa = (v.RotationX[a], v.RotationY[a], v.RotationZ[a], v.RotationW[a]);
|
||||
var o = Rotate(qa, localA);
|
||||
var (ex, ey, ez) = (v.PositionX[a] + o.X, v.PositionY[a] + o.Y, v.PositionZ[a] + o.Z);
|
||||
Assert.True(MathF.Abs(v.PositionY[a] - posA.Y) > 0.5f && MathF.Abs(qa.Item3 - rotA.Z) > 0.05f, "body A moved and turned");
|
||||
Assert.Equal(ex, v.JointOriginX[j], 1e-4f);
|
||||
Assert.Equal(ey, v.JointOriginY[j], 1e-4f);
|
||||
Assert.Equal(ez, v.JointOriginZ[j], 1e-4f);
|
||||
|
||||
// The joint holds the two bodies together: B's own anchor point stays within 0.05 m (the soft constraint's slack) of the lane.
|
||||
var qb = (v.RotationX[b], v.RotationY[b], v.RotationZ[b], v.RotationW[b]);
|
||||
var ob = Rotate(qb, localB);
|
||||
var (dx, dy, dz) = (v.PositionX[b] + ob.X - v.JointOriginX[j], v.PositionY[b] + ob.Y - v.JointOriginY[j], v.PositionZ[b] + ob.Z - v.JointOriginZ[j]);
|
||||
Assert.True(MathF.Sqrt(dx * dx + dy * dy + dz * dz) < 0.05f, "the lane stays at B's own anchor point");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_off_axis_hinge_gets_a_frame_rotated_onto_its_axis()
|
||||
{
|
||||
|
|
@ -225,4 +274,108 @@ public sealed class Box3DSoaJointTests
|
|||
Assert.True(first.AsSpan().SequenceEqual(Run()));
|
||||
Assert.Contains(first, b => b != 0);
|
||||
}
|
||||
|
||||
private const float BobRadius = 0.1f, BobDensity = 1000f;
|
||||
private static float BobMass => 4f / 3f * MathF.PI * BobRadius * BobRadius * BobRadius * BobDensity;
|
||||
|
||||
/// <summary>A static box with a heavy sphere hung one metre below it by a joint of the given kind at the box's centre.</summary>
|
||||
private static (Box3DSoaWorld World, int Bob, Box3DSoaJointHandle Joint) Hanging(
|
||||
Box3DSoaJointKind kind, float forceThreshold = float.PositiveInfinity, float torqueThreshold = float.PositiveInfinity)
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: 4, jointCapacity: 2);
|
||||
var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f));
|
||||
var bob = world.AddSphere(2, (0f, 4f, 0f), BobRadius, BobDensity);
|
||||
var joint = world.AddJoint(kind, pin, bob, (0f, 5f, 0f), (0f, 0f, 1f), forceThreshold: forceThreshold, torqueThreshold: torqueThreshold);
|
||||
return (world, bob, joint);
|
||||
}
|
||||
|
||||
private static float Magnitude(Box3DSoaView v, int joint) =>
|
||||
MathF.Sqrt(v.JointConstraintForceX[joint] * v.JointConstraintForceX[joint] + v.JointConstraintForceY[joint] * v.JointConstraintForceY[joint] +
|
||||
v.JointConstraintForceZ[joint] * v.JointConstraintForceZ[joint]);
|
||||
|
||||
[Theory]
|
||||
[InlineData(Box3DSoaJointKind.Spherical)]
|
||||
[InlineData(Box3DSoaJointKind.Weld)]
|
||||
public void Constraint_lanes_read_the_load(Box3DSoaJointKind kind)
|
||||
{
|
||||
var (world, _, joint) = Hanging(kind);
|
||||
using var _ = world;
|
||||
var view = world.View;
|
||||
for (var i = 0; i < 120; i++) world.Step(Dt);
|
||||
Assert.Equal(BobMass * 10f, Magnitude(view, joint), BobMass * 10f * 0.02f); // m g within 2%
|
||||
world.DestroyJoint(joint);
|
||||
Assert.Equal(0f, Magnitude(view, joint)); // a removed lane keeps no load
|
||||
Assert.Equal(0f, view.JointConstraintTorqueZ[joint]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_overload_is_reported_not_acted_on()
|
||||
{
|
||||
var (world, bob, joint) = Hanging(Box3DSoaJointKind.Spherical, forceThreshold: 200f);
|
||||
using var _ = world;
|
||||
var view = world.View;
|
||||
var first = -1;
|
||||
for (var i = 0; i < 400 && first < 0; i++)
|
||||
{
|
||||
view.ForceY[bob] = -2f * i; // a slow ramp of downward pull
|
||||
world.Step(Dt);
|
||||
var reached = Magnitude(view, joint) >= 198f;
|
||||
var overloads = world.Facts.Overloads;
|
||||
if (!reached) Assert.Equal(0, overloads.Length); // never before the load comes within 1% of the threshold
|
||||
else if (overloads.Length > 0) first = i;
|
||||
else
|
||||
{
|
||||
view.ForceY[bob] = -2f * (i + 1);
|
||||
world.Step(Dt); // by the step after
|
||||
var next = world.Facts.Overloads;
|
||||
Assert.Equal(1, next.Length);
|
||||
Assert.Equal(joint.Lane, next[0].JointLane);
|
||||
Assert.Equal(joint.Generation, next[0].JointGeneration);
|
||||
Assert.True(next[0].ForceY > 190f); // the load rides on the fact
|
||||
first = i + 1;
|
||||
}
|
||||
}
|
||||
Assert.True(first >= 0, "the ramp must reach the threshold");
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
view.ForceY[bob] = -400f;
|
||||
world.Step(Dt);
|
||||
}
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Spherical, view.JointKind[joint]); // the joint still holds: no removal on a threshold
|
||||
Assert.Equal(joint.Generation, view.JointGeneration[joint]);
|
||||
Assert.Equal(4f, view.PositionY[bob], 0.2f);
|
||||
|
||||
world.DestroyJoint(joint);
|
||||
for (var i = 0; i < 30; i++) world.Step(Dt);
|
||||
Assert.True(view.PositionY[bob] < 3f, "DestroyJoint frees the child");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Thresholds_are_a_sensor_set_by_desc_or_command_and_refused_when_not_a_load()
|
||||
{
|
||||
var (world, bob, joint) = Hanging(Box3DSoaJointKind.Weld);
|
||||
using var _ = world;
|
||||
for (var i = 0; i < 5; i++) world.Step(Dt);
|
||||
Assert.Equal(0, world.Facts.Overloads.Length); // +inf is never
|
||||
|
||||
world.SetJointThresholds(joint, 10f, float.PositiveInfinity); // below the bob's weight
|
||||
world.Step(Dt);
|
||||
Assert.Equal(1, world.Facts.Overloads.Length);
|
||||
world.SetJointThresholds(joint, float.PositiveInfinity, float.PositiveInfinity);
|
||||
world.Step(Dt);
|
||||
Assert.Equal(0, world.Facts.Overloads.Length);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetJointThresholds(joint, float.NaN, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetJointThresholds(joint, 1f, -1f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetJointThresholds(new Box3DSoaJointHandle(joint.Lane, joint.Generation + 1), 1f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetJointThresholds(new Box3DSoaJointHandle(1, 0), 1f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddJoint(Box3DSoaJointKind.Spherical, 0, bob, (0f, 5f, 0f), (0f, 0f, 1f), forceThreshold: float.NaN));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddJoint(Box3DSoaJointKind.Spherical, 0, bob, (0f, 5f, 0f), (0f, 0f, 1f), torqueThreshold: -0.5f));
|
||||
Assert.Equal(1, world.View.JointCount); // the refusals added nothing
|
||||
world.Step(Dt);
|
||||
Assert.Equal(0, world.Facts.Overloads.Length); // and changed nothing
|
||||
|
||||
world.DestroyJoint(joint);
|
||||
Assert.Throws<InvalidOperationException>(() => world.SetJointThresholds(joint, 1f, 1f)); // a removed joint has none
|
||||
}
|
||||
}
|
||||
|
|
|
|||
1350
tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs
Normal file
1350
tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs
Normal file
File diff suppressed because it is too large
Load diff
115
tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinFluidTests.cs
Normal file
115
tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinFluidTests.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Pinned flesh and liquid (docs/soa-world.md, pinned, dormant, kinematic, anchor): settled liquid on dormant flesh rides the flesh's bone, and poured liquid stops at the bone under dormant skin.</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
/// <summary>
|
||||
/// A kinematic bone with a 5 x 5 plate of flesh on it (one-way, limb), one drop settled on the plate, a sensor on the bone around the drop. With <paramref name="pin"/> the plate is
|
||||
/// pinned after the settle. Returns the sensor's wet reading after the bone has moved <paramref name="travel"/> m along x, and the reading before.
|
||||
/// </summary>
|
||||
private static (float Before, float After) WetOnMovingBone(bool pin, float travel)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(8, gravityY: -10f, particles: new Box3DSoaParticleCapacities(64, 16, 16, 32, 64, 2, 64, 4, 2));
|
||||
var bone = world.AddAnchor(1, (0f, 0.3f, 0f));
|
||||
var plate = Graph.Block(world, (-0.05f, 0.3f, -0.05f), 5, 1, 5, R, 0.01f, Box3DSoaPhase.Of(4));
|
||||
var drop = Graph.Block(world, (0f, 0.3f + 2f * R + 0.001f, 0f), 1, 1, 1, R, FluidMass, FluidPhase);
|
||||
for (var i = 0; i < plate.Length; i++)
|
||||
{
|
||||
var q = world.View;
|
||||
world.Attach(Box3DSoaAttachKind.Body, plate[i], bone, (q.ParticleX[plate[i]], 0f, q.ParticleZ[plate[i]]), limb: true, oneWay: true);
|
||||
}
|
||||
var sensor = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(bone, (0f, 0f, 0f), 0.3f)], sensor);
|
||||
Run(world, 20);
|
||||
Assert.True(world.View.SupportParticle[drop[0].Lane] >= 0, "the drop rests on the plate");
|
||||
world.Settle(drop);
|
||||
if (pin) world.SetPinned(plate, true);
|
||||
world.Step(Dt, Sub);
|
||||
var before = world.View.SensorWetVolume[sensor[0]];
|
||||
var steps = 30;
|
||||
for (var s = 1; s <= steps; s++)
|
||||
{
|
||||
world.SetAnchorTarget(bone, (travel * s / steps, 0.3f, 0f), default, Dt);
|
||||
world.Step(Dt, Sub);
|
||||
}
|
||||
world.Step(Dt, Sub);
|
||||
return (before, world.View.SensorWetVolume[sensor[0]]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settled_liquid_on_pinned_flesh_rides_its_bone()
|
||||
{
|
||||
// The drop settled on flesh that is then pinned: the sensor on the bone reads it after the bone has moved 2 m, as it does for live flesh. A patch read at the
|
||||
// dormant particle's stale position would be left behind and read 0.
|
||||
var live = WetOnMovingBone(false, 2f);
|
||||
var pinned = WetOnMovingBone(true, 2f);
|
||||
Readings.Add($"PIN_WET sensor on the bone before and after it moved 2 m: live {live.Before:E4} {live.After:E4}, pinned {pinned.Before:E4} {pinned.After:E4}");
|
||||
Assert.Equal(DropVolume, live.Before);
|
||||
Assert.Equal(live.Before, live.After);
|
||||
Assert.Equal(DropVolume, pinned.Before);
|
||||
Assert.Equal(pinned.Before, pinned.After);
|
||||
}
|
||||
|
||||
private const float CapR = 0.07f, CapHalf = 0.18f, SkinR = 0.036f;
|
||||
|
||||
/// <summary>Per fluid particle, the closest its centre came to the capsule's axis over a 343-particle pour on a horizontal capsule under a 36-particle skin ring of flesh, live or pinned.</summary>
|
||||
private static (double[] Closest, int Inside) PourOnSkin(bool pinned)
|
||||
{
|
||||
const int Ring = 36;
|
||||
using var world = new Box3DSoaWorld(8, gravityY: -10f, jointCapacity: 4,
|
||||
particles: new Box3DSoaParticleCapacities(Ring + 343 + 8, 16, 16, Ring + 8, 16, 2, 343));
|
||||
var wall = world.AddStaticBox(1, (2f, 0.5f, 0f), (0.05f, 0.05f, 0.05f));
|
||||
var sq = MathF.Sqrt(0.5f);
|
||||
var bone = world.AddCapsule(2, (0f, 0.5f, 0f), CapR, CapHalf, 500f, rotation: (0f, 0f, sq, sq)); // local Y lies along world x
|
||||
world.AddJoint(Box3DSoaJointKind.Weld, wall, bone, (0f, 0.5f, 0f), (0f, 0f, 1f));
|
||||
var skin = new Box3DSoaParticleHandle[Ring];
|
||||
var local = new Pos[Ring];
|
||||
var desc = new Box3DSoaParticleDesc[Ring];
|
||||
for (var k = 0; k < Ring; k++)
|
||||
{
|
||||
var a = 2f * MathF.PI * k / Ring;
|
||||
local[k] = (CapR * MathF.Cos(a), 0f, CapR * MathF.Sin(a)); // a ring in the bone's xz plane, around its axis y
|
||||
}
|
||||
// rotation (0, 0, s, s) is +90 degrees about z: local (x, y, z) -> world (-y, x, z), plus the bone's centre (0, 0.5, 0)
|
||||
for (var k = 0; k < Ring; k++) desc[k] = new Box3DSoaParticleDesc((-local[k].Y, local[k].X + 0.5f, local[k].Z), 0.02f, SkinR, Box3DSoaPhase.Of(4));
|
||||
world.CreateParticles(desc, skin);
|
||||
for (var k = 0; k < Ring; k++) world.Attach(Box3DSoaAttachKind.Body, skin[k], bone, local[k], limb: true, oneWay: true);
|
||||
if (pinned) world.SetPinned(skin, true);
|
||||
var pour = Graph.Block(world, (-0.15f + 0.0125f, 0.5f + 0.45f, -0.15f + 0.0125f), 7, 7, 7, R, FluidMass, FluidPhase, pitch: 2f * R);
|
||||
var closest = Enumerable.Repeat(double.MaxValue, pour.Length).ToArray();
|
||||
var inside = 0;
|
||||
for (var s = 0; s < 240; s++)
|
||||
{
|
||||
world.Step(Dt, Sub);
|
||||
var v = world.View;
|
||||
for (var i = 0; i < pour.Length; i++)
|
||||
{
|
||||
var l = pour[i].Lane;
|
||||
double y = v.ParticleY[l] - 0.5, z = v.ParticleZ[l];
|
||||
var d = Math.Sqrt(y * y + z * z);
|
||||
if (Math.Abs(v.ParticleX[l]) < CapHalf) closest[i] = Math.Min(closest[i], d);
|
||||
if (Math.Abs(v.ParticleX[l]) < CapHalf && d < CapR) inside++;
|
||||
}
|
||||
}
|
||||
return (closest, inside);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Blood_poured_on_dormant_skin_stops_at_the_bone()
|
||||
{
|
||||
// Dormant flesh meets no fluid, so liquid on pinned skin stops at the bone's capsule (centre at R + r), not at the skin's surface (R + skin radius + r) where live flesh stops it.
|
||||
static double Median(double[] x) { var c = x.Where(d => d != double.MaxValue).OrderBy(d => d).ToArray(); return c[c.Length / 2]; }
|
||||
var live = PourOnSkin(false);
|
||||
var dormant = PourOnSkin(true);
|
||||
double stop = CapR + R;
|
||||
var (lm, dm) = (Median(live.Closest), Median(dormant.Closest));
|
||||
Readings.Add($"PIN_BLOOD median closest approach to the axis: live skin {lm:F4}, dormant skin {dm:F4}, capsule surface plus fluid radius {stop:F4}; centres inside the capsule live {live.Inside}, dormant {dormant.Inside}");
|
||||
Assert.Equal(0, dormant.Inside);
|
||||
Assert.True(dm >= stop - 0.002 && dm <= stop + 0.008, $"dormant blood lies {dm} from the axis, the capsule stops it at {stop}");
|
||||
Assert.True(lm > dm + 0.008, $"live skin holds the blood off at {lm}, dormant at {dm}");
|
||||
}
|
||||
}
|
||||
542
tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTests.cs
Normal file
542
tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTests.cs
Normal file
|
|
@ -0,0 +1,542 @@
|
|||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>
|
||||
/// Pinned particles are dormant (docs/soa-world.md, pinned, dormant, kinematic, anchor). The scene is four capsules on a hinge chain, each
|
||||
/// with a 6 x 6 sheet of flesh attached to it (NO_PARTICLE_CONTACT, edges, bends), and stitches between neighbouring sheets.
|
||||
/// </summary>
|
||||
public sealed class Box3DSoaPinTests
|
||||
{
|
||||
private const int Chain = 4, Side = 6, PerSheet = Side * Side;
|
||||
private const float Step = 0.05f, Offset = 0.08f, Pitch = 0.32f;
|
||||
|
||||
private static string F(double x) => x.ToString("G6", CultureInfo.InvariantCulture);
|
||||
|
||||
private static void Reading(string line)
|
||||
{
|
||||
Console.Error.WriteLine(line);
|
||||
var path = Environment.GetEnvironmentVariable("YMIR_READINGS");
|
||||
if (!string.IsNullOrEmpty(path)) File.AppendAllText(path, line + "\n");
|
||||
}
|
||||
|
||||
private sealed class Scene : IDisposable
|
||||
{
|
||||
public Box3DSoaWorld World = null!;
|
||||
public int[] Bones = null!;
|
||||
public Box3DSoaParticleHandle[][] P = null!;
|
||||
public Pos[][] Local = null!;
|
||||
public Box3DSoaConstraintHandle[][] Anchor = null!; // per sheet, per particle: its attachment
|
||||
public Box3DSoaConstraintHandle[][] Stitch = null!; // stitch k joins the bottom row of sheet k to the top row of sheet k + 1
|
||||
public Box3DSoaParticleHandle[] All = null!;
|
||||
public Box3DSoaView View = default!;
|
||||
public void Dispose() => World.Dispose();
|
||||
}
|
||||
|
||||
private static Scene Chained(int fluid = 0, int extra = 0)
|
||||
{
|
||||
var s = new Scene
|
||||
{
|
||||
World = Box3DSoaParticleTests.World(bodies: 8, particles: Chain * PerSheet + 8 + extra, distances: 320, bends: 320, attachments: Chain * PerSheet + 8 + extra,
|
||||
tethers: 8, joints: 8, gravityX: 4f, gravityY: -10f, fluid: fluid),
|
||||
Bones = new int[Chain], P = new Box3DSoaParticleHandle[Chain][], Local = new Pos[Chain][],
|
||||
Anchor = new Box3DSoaConstraintHandle[Chain][], Stitch = new Box3DSoaConstraintHandle[Chain - 1][],
|
||||
};
|
||||
var w = s.World;
|
||||
var top = w.AddStaticBox(1, (0f, 2.05f, 0f), (0.1f, 0.05f, 0.1f));
|
||||
var sheets = new Made[Chain];
|
||||
for (var k = 0; k < Chain; k++)
|
||||
{
|
||||
var cy = 1.85f - Pitch * k;
|
||||
s.Bones[k] = w.AddCapsule((ulong)(k + 2), (0f, cy, 0f), 0.05f, 0.1f, 500f, parent: k == 0 ? top : s.Bones[k - 1], limb: k);
|
||||
w.AddJoint(Box3DSoaJointKind.Revolute, k == 0 ? top : s.Bones[k - 1], s.Bones[k], (0f, k == 0 ? 2f : cy + Pitch / 2f, 0f), (0f, 0f, 1f));
|
||||
sheets[k] = Graph.Sheet(w, (-0.125f, cy - 0.125f, Offset), (Step, 0f, 0f), (0f, Step, 0f), Side, Side, 0.02f, 0.0125f,
|
||||
Box3DSoaPhase.Of((uint)(k + 1), noParticleContact: true));
|
||||
s.P[k] = sheets[k].Particles;
|
||||
s.Local[k] = new Pos[PerSheet];
|
||||
for (var q = 0; q < PerSheet; q++) s.Local[k][q] = (-0.125f + Step * (q % Side), -0.125f + Step * (q / Side), Offset);
|
||||
s.Anchor[k] = new Box3DSoaConstraintHandle[PerSheet];
|
||||
for (var q = 0; q < PerSheet; q++) s.Anchor[k][q] = w.Attach(Box3DSoaAttachKind.Body, s.P[k][q], s.Bones[k], s.Local[k][q], compliance: 1e-4f, limb: true, oneWay: true);
|
||||
}
|
||||
for (var k = 0; k + 1 < Chain; k++)
|
||||
{
|
||||
var d = new Box3DSoaDistanceDesc[Side];
|
||||
for (var i = 0; i < Side; i++) d[i] = new Box3DSoaDistanceDesc(s.P[k][i], s.P[k + 1][Side * (Side - 1) + i]);
|
||||
s.Stitch[k] = new Box3DSoaConstraintHandle[Side];
|
||||
w.CreateDistances(d, s.Stitch[k]);
|
||||
}
|
||||
s.All = s.P.SelectMany(x => x).ToArray();
|
||||
s.View = w.View;
|
||||
return s;
|
||||
}
|
||||
|
||||
private static Pos Rotate(float x, float y, float z, float w, Pos v)
|
||||
{
|
||||
var tx = 2f * (y * v.Z - z * v.Y); var ty = 2f * (z * v.X - x * v.Z); var tz = 2f * (x * v.Y - y * v.X);
|
||||
return (v.X + w * tx + (y * tz - z * ty), v.Y + w * ty + (z * tx - x * tz), v.Z + w * tz + (x * ty - y * tx));
|
||||
}
|
||||
|
||||
/// <summary>The world point the particle's attachment holds now, and the velocity of that point.</summary>
|
||||
private static (Pos Point, Pos Velocity) AnchorNow(Scene s, int sheet, int q)
|
||||
{
|
||||
var v = s.View;
|
||||
var b = s.Bones[sheet];
|
||||
var r = Rotate(v.RotationX[b], v.RotationY[b], v.RotationZ[b], v.RotationW[b], s.Local[sheet][q]);
|
||||
var p = (v.PositionX[b] + r.X, v.PositionY[b] + r.Y, v.PositionZ[b] + r.Z);
|
||||
var wv = (v.AngularVelocityX[b], v.AngularVelocityY[b], v.AngularVelocityZ[b]);
|
||||
var vel = (v.VelocityX[b] + wv.Item2 * r.Z - wv.Item3 * r.Y, v.VelocityY[b] + wv.Item3 * r.X - wv.Item1 * r.Z, v.VelocityZ[b] + wv.Item1 * r.Y - wv.Item2 * r.X);
|
||||
return (p, vel);
|
||||
}
|
||||
|
||||
private static float Dist(Pos a, Pos b) => MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
|
||||
|
||||
private static Pos At(Box3DSoaView v, int i) => (v.ParticleX[i], v.ParticleY[i], v.ParticleZ[i]);
|
||||
|
||||
private static ulong Fnv(ulong h, ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
foreach (var b in bytes) { h ^= b; h *= 1099511628211ul; }
|
||||
return h;
|
||||
}
|
||||
|
||||
private static ulong HashAll(Box3DSoaView v)
|
||||
{
|
||||
var h = 1469598103934665603ul;
|
||||
void F(ReadOnlySpan<float> lane) => h = Fnv(h, MemoryMarshal.AsBytes(lane));
|
||||
F(v.ParticleX); F(v.ParticleY); F(v.ParticleZ); F(v.ParticleVx); F(v.ParticleVy); F(v.ParticleVz); F(v.DistanceTension);
|
||||
F(v.AttachmentForceX); F(v.AttachmentForceY); F(v.AttachmentForceZ);
|
||||
F(v.PositionX); F(v.PositionY); F(v.PositionZ); F(v.RotationX); F(v.RotationY); F(v.RotationZ); F(v.RotationW);
|
||||
F(v.VelocityX); F(v.VelocityY); F(v.VelocityZ); F(v.AngularVelocityX); F(v.AngularVelocityY); F(v.AngularVelocityZ);
|
||||
F(v.ParticleImpulseX); F(v.ParticleImpulseY); F(v.ParticleImpulseZ);
|
||||
h = Fnv(h, MemoryMarshal.AsBytes(v.ParticlePinned));
|
||||
return h;
|
||||
}
|
||||
|
||||
private static float[][] ParticleLanes(Box3DSoaView v) =>
|
||||
[v.ParticleX.ToArray(), v.ParticleY.ToArray(), v.ParticleZ.ToArray(), v.ParticleVx.ToArray(), v.ParticleVy.ToArray(), v.ParticleVz.ToArray()];
|
||||
|
||||
// Every body lane a particle could have moved: pose, velocities.
|
||||
private static float[][] BodyLanes(Box3DSoaView v) =>
|
||||
[v.PositionX.ToArray(), v.PositionY.ToArray(), v.PositionZ.ToArray(), v.RotationX.ToArray(), v.RotationY.ToArray(), v.RotationZ.ToArray(), v.RotationW.ToArray(),
|
||||
v.VelocityX.ToArray(), v.VelocityY.ToArray(), v.VelocityZ.ToArray(), v.AngularVelocityX.ToArray(), v.AngularVelocityY.ToArray(), v.AngularVelocityZ.ToArray()];
|
||||
|
||||
private static byte[] Bytes(Box3DSoaView v)
|
||||
{
|
||||
var all = new List<byte>();
|
||||
foreach (var lane in ParticleLanes(v)) all.AddRange(MemoryMarshal.AsBytes(lane.AsSpan()).ToArray());
|
||||
all.AddRange(MemoryMarshal.AsBytes(v.ParticlePinned).ToArray());
|
||||
return all.ToArray();
|
||||
}
|
||||
|
||||
private static void Run(Scene s, int steps) => Box3DSoaParticleTests.Run(s.World, steps);
|
||||
|
||||
// ---- (a) ------------------------------------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void All_pinned_costs_nothing_and_moves_nothing()
|
||||
{
|
||||
using var a = Chained();
|
||||
using var b = Chained();
|
||||
Run(a, 20); Run(b, 20);
|
||||
Assert.True(a.View.ParticlePinned.ToArray().All(x => x == 0u));
|
||||
var pos = ParticleLanes(a.View);
|
||||
var swing0 = (a.View.PositionX[a.Bones[3]], a.View.PositionY[a.Bones[3]]);
|
||||
a.World.SetPinned(a.All, true);
|
||||
b.World.DestroyParticles(b.All);
|
||||
Run(a, 240); Run(b, 240);
|
||||
var v = a.View;
|
||||
Assert.True(v.ParticlePinned.ToArray().Take(Chain * PerSheet).All(x => x == 1u));
|
||||
var now = ParticleLanes(v);
|
||||
for (var l = 0; l < 6; l++) Assert.True(MemoryMarshal.AsBytes(now[l].AsSpan()).SequenceEqual(MemoryMarshal.AsBytes(pos[l].AsSpan())), $"pinned lane {l} moved");
|
||||
for (var i = 0; i < v.Count; i++) Assert.True(v.ParticleImpulseX[i] == 0f && v.ParticleImpulseY[i] == 0f && v.ParticleImpulseZ[i] == 0f, "a body took an impulse from dormant flesh");
|
||||
Assert.True(v.DistanceTension.ToArray().All(t => t == 0f) && Enumerable.Range(0, v.AttachmentCount).All(i => v.AttachmentForceX[i] == 0f && v.AttachmentForceY[i] == 0f && v.AttachmentForceZ[i] == 0f));
|
||||
var mine = BodyLanes(v); var theirs = BodyLanes(b.View);
|
||||
for (var l = 0; l < mine.Length; l++) Assert.True(MemoryMarshal.AsBytes(mine[l].AsSpan()).SequenceEqual(MemoryMarshal.AsBytes(theirs[l].AsSpan())), $"body lane {l} differs from the world without particles");
|
||||
Assert.True(MathF.Abs(v.PositionX[a.Bones[3]] - swing0.Item1) > 0.05f, "the chain swings: " + v.PositionX[a.Bones[3]]);
|
||||
}
|
||||
|
||||
// ---- (b) ------------------------------------------------------------------------------------------------
|
||||
|
||||
// Bounds by lodur:ruling:deterministic-bound-margin and deterministic-bound-zero-reading: the geometric mean of the shipped worst and the least claimed
|
||||
// mutant, and each separation at least 1.2. The mutants, each a one-line change to ymir_particles.c or ymir_box3d_soa.c, with the readings in the order
|
||||
// wake position m / wake velocity m/s / kinematic deviation m / kinematic velocity m/s / stitch length against the all-live world over rest:
|
||||
// shipped 0 / 1.20137e-7 / 2.40274e-7 / 2.07946e-2 / 1.62519e-3
|
||||
// Mk1 the kinematic pos not written at the substep's start 14.9 on kinematic velocity (the one-substep step), the rest as shipped
|
||||
// Mk2 the kinematic pp not written after the proxies predict 1.86 m / 890.667 / 3.87965
|
||||
// Mw w ignores pinned (a kinematic particle gets weight) kinematic deviation 9.13432e-3 / velocity 4.3849 / stitch 1.85605e-2
|
||||
// Mv the wake writes no velocity wake velocity 0.695914
|
||||
// Mg set_pinned does not gather the proxies first wake position 2.38419e-7 / wake velocity 6.95331e-4
|
||||
// Mr set_pinned skips rederive_active kinematic deviation 9.28324e-3 / velocity 9.27735e-2; (a), (d) fail by name
|
||||
// Mo act built in descending lane order the four determinism hashes fail
|
||||
// WakeAnchor: shipped worst 0 (counts half the unit, 1 ulp at 1 to 2 m = 1.19209e-7, so 5.96046e-8), least claimed mutant Mg 2.38419e-7, separation 4; bound sqrt(5.96046e-8 x 2.38419e-7).
|
||||
private const float WakeAnchor = 1.2e-7f;
|
||||
// WakeVelocity: shipped worst 1.20137e-7, least claimed mutant Mg 6.95331e-4, separation 5788; bound sqrt(1.20137e-7 x 6.95331e-4).
|
||||
private const float WakeVelocity = 9.14e-6f;
|
||||
// KinAnchor: shipped worst 2.40274e-7, least claimed mutant Mw 9.13432e-3, separation 38016; bound sqrt(2.40274e-7 x 9.13432e-3).
|
||||
private const float KinAnchor = 4.685e-5f;
|
||||
// KinVelocity: shipped worst 2.07946e-2, least claimed mutant Mr 9.27735e-2, separation 4.46; bound sqrt(2.07946e-2 x 9.27735e-2).
|
||||
private const float KinVelocity = 4.39e-2f;
|
||||
// StitchDifference: shipped worst 1.62519e-3, least claimed mutant Mw 1.85605e-2, separation 11.4; bound sqrt(1.62519e-3 x 1.85605e-2). Mr reads 2.51e-4 (below shipped): unclaimed here.
|
||||
private const float StitchDifference = 5.49e-3f;
|
||||
|
||||
[Fact]
|
||||
public void A_woken_sheet_starts_on_its_anchors_and_its_neighbours_are_held_on_theirs()
|
||||
{
|
||||
using var s = Chained();
|
||||
using var live = Chained(); // the same scene with every particle live all along: the stitches' lengths there are the geometry of the hinges
|
||||
var w = s.World;
|
||||
w.SetPinned(s.All, true);
|
||||
Run(s, 30);
|
||||
Run(live, 30);
|
||||
var v = s.View;
|
||||
var dormant = new List<(int Lane, Pos At)>(); // pinned and on no live constraint with an unpinned particle: the far sheet, and the rows of the near ones away from sheet 1
|
||||
for (var q = 0; q < PerSheet; q++) dormant.Add((s.P[3][q], At(v, s.P[3][q])));
|
||||
for (var q = Side; q < PerSheet; q++) dormant.Add((s.P[0][q], At(v, s.P[0][q])));
|
||||
for (var q = 0; q < PerSheet - Side; q++) dormant.Add((s.P[2][q], At(v, s.P[2][q])));
|
||||
var asleep = Bytes(v);
|
||||
w.SetPinned(s.P[1], false);
|
||||
double wakePos = 0, wakeVel = 0;
|
||||
for (var q = 0; q < PerSheet; q++)
|
||||
{
|
||||
var (point, vel) = AnchorNow(s, 1, q);
|
||||
wakePos = Math.Max(wakePos, Dist(At(v, s.P[1][q]), point));
|
||||
wakeVel = Math.Max(wakeVel, Dist((v.ParticleVx[s.P[1][q]], v.ParticleVy[s.P[1][q]], v.ParticleVz[s.P[1][q]]), vel));
|
||||
}
|
||||
Assert.True(v.ParticlePinned[s.P[1][0]] == 0u && v.ParticlePinned[s.P[0][0]] == 1u);
|
||||
var kin = new List<(int Sheet, int Q)>();
|
||||
for (var q = 0; q < Side; q++) { kin.Add((0, q)); kin.Add((2, Side * (Side - 1) + q)); } // bottom row of sheet 0, top row of sheet 2
|
||||
double kinDev = 0, kinVel = 0, stretch = 0;
|
||||
for (var step = 0; step < 60; step++)
|
||||
{
|
||||
var sub = step == 0 ? 1 : Box3DSoaParticleTests.Sub; // one substep first: the velocity of a kinematic particle the step leaves is the last substep's, so with four the first one's is overwritten
|
||||
s.World.Step(Box3DSoaParticleTests.Dt, sub);
|
||||
live.World.Step(Box3DSoaParticleTests.Dt, sub);
|
||||
foreach (var (sheet, q) in kin)
|
||||
{
|
||||
var i = s.P[sheet][q].Lane;
|
||||
kinDev = Math.Max(kinDev, Dist(At(v, i), AnchorNow(s, sheet, q).Point));
|
||||
kinVel = Math.Max(kinVel, Dist((v.ParticleVx[i], v.ParticleVy[i], v.ParticleVz[i]), AnchorNow(s, sheet, q).Velocity));
|
||||
}
|
||||
foreach (var k in new[] { 0, 1 })
|
||||
foreach (var e in s.Stitch[k])
|
||||
stretch = Math.Max(stretch, MathF.Abs(Dist(At(v, v.DistanceA[e.Lane]), At(v, v.DistanceB[e.Lane])) - Dist(At(live.View, live.View.DistanceA[e.Lane]), At(live.View, live.View.DistanceB[e.Lane]))) / v.DistanceRest[e.Lane]);
|
||||
}
|
||||
Reading($"PIN_WAKE wake position {F(wakePos)} m, wake velocity {F(wakeVel)} m/s, kinematic deviation after steps {F(kinDev)} m, kinematic velocity against the anchor point's {F(kinVel)} m/s, stitch length differing from the all-live world (over rest) {F(stretch)}");
|
||||
Assert.True(wakePos <= WakeAnchor, $"a woken particle is {wakePos} from its anchor");
|
||||
Assert.True(wakeVel <= WakeVelocity, $"a woken particle's velocity differs from its anchor point's by {wakeVel}");
|
||||
Assert.True(kinDev <= KinAnchor, $"a kinematic particle is {kinDev} from its anchor");
|
||||
Assert.True(kinVel <= KinVelocity, $"a kinematic particle moves {kinVel} m/s off its anchor point");
|
||||
Assert.True(stretch <= StitchDifference, $"a stitch differs from the all-live world by {stretch}");
|
||||
// what no walk reaches did not move: the far sheet, and the dormant rows of the near ones
|
||||
foreach (var (lane, was) in dormant) Assert.Equal(was, At(v, lane));
|
||||
Assert.False(Bytes(v).SequenceEqual(asleep));
|
||||
}
|
||||
|
||||
// ---- (c) ------------------------------------------------------------------------------------------------
|
||||
|
||||
private static unsafe int NativePin(Box3DSoaWorld world, Box3DSoaParticleHandle h, uint pinned)
|
||||
{
|
||||
var handle = (nint)typeof(Box3DSoaWorld).GetField("_handle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(world)!;
|
||||
return Box3DSoaNative.ymir_box3d_soa_set_pinned(handle, 1, &h, pinned);
|
||||
}
|
||||
|
||||
private static void Refused(Scene s, Action command, string what)
|
||||
{
|
||||
var before = HashAll(s.View);
|
||||
var e = Assert.Throws<InvalidOperationException>(command);
|
||||
Assert.Contains("status 1", e.Message);
|
||||
Assert.True(before == HashAll(s.View), $"{what}: the refusal changed a lane");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pinning_refuses_what_it_cannot_hold_and_changes_nothing()
|
||||
{
|
||||
using var s = Chained(fluid: 4, extra: 16);
|
||||
var w = s.World;
|
||||
var fluid = new Box3DSoaParticleHandle[1];
|
||||
w.CreateParticles([new Box3DSoaParticleDesc((0.5f, 1f, 0.5f), 0.02f, 0.0125f, Box3DSoaPhase.Of(9, fluid: true))], fluid);
|
||||
var bare = new Box3DSoaParticleHandle[1];
|
||||
w.CreateParticles([new Box3DSoaParticleDesc((0.5f, 1.5f, 0.5f), 0.02f, 0.0125f, Box3DSoaPhase.Of(8, noParticleContact: true))], bare);
|
||||
var rope = Graph.Rope(w, Graph.Line((1f, 1f, 0f), (0.03f, 0f, 0f), 6), 0.02f, 0.0125f, Box3DSoaPhase.Of(7, noParticleContact: true));
|
||||
w.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: (1f, 1f, 0f), tether: true);
|
||||
w.Attach(Box3DSoaAttachKind.Body, rope.Particles[5], s.Bones[0], (0f, 0f, 0.2f)); // an anchor, but the rope's component is tethered
|
||||
var doomed = new Box3DSoaParticleHandle[1];
|
||||
w.CreateParticles([new Box3DSoaParticleDesc((0.5f, 2f, 0.5f), 0.02f, 0.0125f, Box3DSoaPhase.Of(6, noParticleContact: true))], doomed);
|
||||
w.Attach(Box3DSoaAttachKind.Static, doomed[0], point: (0.5f, 2f, 0.5f));
|
||||
var view = w.View;
|
||||
s.View = view;
|
||||
Run(s, 5);
|
||||
w.DestroyParticles(doomed);
|
||||
Refused(s, () => w.SetPinned(fluid, true), "a fluid particle");
|
||||
Refused(s, () => w.SetPinned(bare, true), "no anchor");
|
||||
Refused(s, () => w.SetPinned([rope.Particles[5]], true), "a tethered component");
|
||||
Refused(s, () => w.SetPinned(doomed, true), "a stale handle");
|
||||
Refused(s, () => w.SetPinned([s.P[0][0], fluid[0]], true), "a batch with one bad handle: the good one is not pinned either");
|
||||
Assert.Equal(0u, view.ParticlePinned[s.P[0][0]]);
|
||||
var beforeTwo = HashAll(view);
|
||||
Assert.Equal(1, NativePin(w, s.P[0][0], 2)); // INVALID_ARGUMENT
|
||||
Assert.Equal(beforeTwo, HashAll(view));
|
||||
// a pinned particle's anchor cannot be removed; another attachment of it can
|
||||
w.SetPinned([s.P[0][0], s.P[1][0]], true);
|
||||
Assert.Equal(1u, view.ParticlePinned[s.P[0][0]]);
|
||||
var extra = w.Attach(Box3DSoaAttachKind.Body, s.P[0][0], s.Bones[0], s.Local[0][0]); // a higher lane: not the anchor
|
||||
Refused(s, () => w.Remove(s.Anchor[0][0]), "a pinned particle's anchor");
|
||||
w.Remove(extra);
|
||||
w.SetPinned([s.P[1][0]], false);
|
||||
w.Remove(s.Anchor[1][0]); // woken: its anchor goes like any attachment
|
||||
// destroying a pinned particle frees its lane to 0
|
||||
var victim = s.P[0][1];
|
||||
w.SetPinned([victim], true);
|
||||
Assert.Equal(1u, view.ParticlePinned[victim]);
|
||||
w.DestroyParticles([victim]);
|
||||
Assert.Equal(0u, view.ParticlePinned[victim.Lane]);
|
||||
}
|
||||
|
||||
// ---- (d) ------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>The set of particles a step may move, recomputed from the pinned lane and the live constraints: the unpinned, and the pinned ones a live distance or bend with an unpinned particle reaches.</summary>
|
||||
private static HashSet<int> MayMove(Box3DSoaView v)
|
||||
{
|
||||
var set = new HashSet<int>();
|
||||
for (var i = 0; i < v.ParticleCount; i++) if (v.ParticleLive[i] != 0 && v.ParticlePinned[i] == 0) set.Add(i);
|
||||
var unpinned = set.ToHashSet();
|
||||
for (var e = 0; e < v.DistanceCount; e++)
|
||||
if (v.DistanceLive[e] != 0 && (unpinned.Contains(v.DistanceA[e]) || unpinned.Contains(v.DistanceB[e]))) { set.Add(v.DistanceA[e]); set.Add(v.DistanceB[e]); }
|
||||
for (var k = 0; k < v.BendCount; k++)
|
||||
if (v.BendLive[k] != 0 && (unpinned.Contains(v.BendA[k]) || unpinned.Contains(v.BendB[k]) || unpinned.Contains(v.BendC[k]))) { set.Add(v.BendA[k]); set.Add(v.BendB[k]); set.Add(v.BendC[k]); }
|
||||
return set;
|
||||
}
|
||||
|
||||
private static void AssertLists(Scene s, string after)
|
||||
{
|
||||
var v = s.View;
|
||||
var may = MayMove(v);
|
||||
var before = new[] { v.ParticleX.ToArray(), v.ParticleY.ToArray(), v.ParticleZ.ToArray() };
|
||||
s.World.Step(Box3DSoaParticleTests.Dt, Box3DSoaParticleTests.Sub);
|
||||
for (var i = 0; i < v.ParticleCount; i++)
|
||||
{
|
||||
var moved = before[0][i] != v.ParticleX[i] || before[1][i] != v.ParticleY[i] || before[2][i] != v.ParticleZ[i];
|
||||
Assert.True(moved == may.Contains(i), $"{after}: particle {i} moved {moved}, active or kinematic {may.Contains(i)}");
|
||||
}
|
||||
var booked = new HashSet<int>(); // an active bend books on both its distances
|
||||
for (var k = 0; k < v.BendCount; k++)
|
||||
if (v.BendLive[k] != 0 && (v.ParticlePinned[v.BendA[k]] == 0u || v.ParticlePinned[v.BendB[k]] == 0u || v.ParticlePinned[v.BendC[k]] == 0u)) { booked.Add(v.BendE1[k]); booked.Add(v.BendE2[k]); }
|
||||
for (var e = 0; e < v.DistanceCount; e++)
|
||||
if (v.DistanceLive[e] != 0 && v.ParticlePinned[v.DistanceA[e]] == 1u && v.ParticlePinned[v.DistanceB[e]] == 1u && !booked.Contains(e))
|
||||
Assert.True(v.DistanceTension[e] == 0f, $"{after}: an inactive distance {e} carries tension");
|
||||
for (var a = 0; a < v.AttachmentCount; a++)
|
||||
if (v.AttachmentKind[a] != 2u && v.ParticlePinned[v.AttachmentParticle[a]] == 1u)
|
||||
Assert.True(v.AttachmentForceX[a] == 0f && v.AttachmentForceY[a] == 0f && v.AttachmentForceZ[a] == 0f, $"{after}: a dormant attachment {a} carries force");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_active_lists_follow_every_wake_and_pin()
|
||||
{
|
||||
using var s = Chained();
|
||||
var w = s.World;
|
||||
w.SetPinned(s.All, true);
|
||||
AssertLists(s, "all pinned");
|
||||
w.SetPinned(s.P[1], false);
|
||||
AssertLists(s, "sheet 1 woken");
|
||||
w.SetPinned(s.P[2], false);
|
||||
AssertLists(s, "sheets 1 and 2 woken");
|
||||
w.SetPinned(s.P[1], true);
|
||||
AssertLists(s, "sheet 1 pinned again");
|
||||
w.SetPinned([s.P[0][7], s.P[3][35]], false);
|
||||
AssertLists(s, "two single particles woken");
|
||||
w.Remove(s.Stitch[1][2]);
|
||||
AssertLists(s, "a stitch cut");
|
||||
w.DestroyParticles([s.P[2][3]]);
|
||||
AssertLists(s, "a woken particle destroyed");
|
||||
w.SetPinned(s.All.Where(p => s.View.ParticleLive[p.Lane] != 0).ToArray(), false);
|
||||
AssertLists(s, "everything woken");
|
||||
}
|
||||
|
||||
// ---- (e) ------------------------------------------------------------------------------------------------
|
||||
|
||||
private static ulong[] PinHashesRun(bool nudge = false)
|
||||
{
|
||||
using var s = Chained();
|
||||
var w = s.World;
|
||||
var hashes = new ulong[6];
|
||||
w.SetPinned(s.All, true);
|
||||
for (var c = 0; c < 6; c++)
|
||||
{
|
||||
for (var t = 0; t < 40; t++)
|
||||
{
|
||||
var tick = c * 40 + t;
|
||||
if (tick == 20) w.SetPinned(s.P[1], false);
|
||||
if (tick == 80) w.SetPinned(s.P[1], true);
|
||||
if (tick == 100) w.SetPinned([.. s.P[0], .. s.P[3]], false);
|
||||
if (tick == 160) w.SetPinned(s.P[2], false);
|
||||
if (tick == 200) w.SetPinned(s.P[0], true);
|
||||
if (nudge && tick == 21) w.SetPinned([s.P[2][5]], false);
|
||||
w.Step(Box3DSoaParticleTests.Dt, Box3DSoaParticleTests.Sub);
|
||||
}
|
||||
hashes[c] = HashAll(s.View);
|
||||
}
|
||||
return hashes;
|
||||
}
|
||||
|
||||
// Recorded on this commit's build (gcc 13.2, -ffp-contract=off, Release and Debug; MSVC /fp:precise gives the same bytes): pin and wake commands at fixed ticks on the chain scene, one hash per 40 steps (the hash covers the pinned lane).
|
||||
private static readonly ulong[] PinHashes = [1479169756272998701ul, 11282791371326620524ul, 7232528760214525229ul, 13136815359770158322ul, 17491214340810821373ul, 13380942627298567997ul];
|
||||
|
||||
[Fact]
|
||||
public void Pin_scene_is_byte_deterministic()
|
||||
{
|
||||
var a = PinHashesRun();
|
||||
var b = PinHashesRun();
|
||||
Assert.True(a.AsSpan().SequenceEqual(b), "two runs diverged: " + string.Join(",", a) + " vs " + string.Join(",", b));
|
||||
Assert.True(a.Distinct().Count() == 6, "the scene moves");
|
||||
Assert.False(a.AsSpan().SequenceEqual(PinHashesRun(nudge: true)), "one more wake must diverge");
|
||||
Assert.True(PinHashes.AsSpan().SequenceEqual(a), string.Join(",", a.Select(g => g + "ul")));
|
||||
}
|
||||
|
||||
// ---- (g) ------------------------------------------------------------------------------------------------
|
||||
|
||||
private static (Box3DSoaWorld World, Box3DSoaParticleHandle[][] Sheets) Fellas(int capsules)
|
||||
{
|
||||
var w = Box3DSoaParticleTests.World(bodies: capsules + 1, particles: capsules * PerSheet + 8, distances: capsules * 60 + 8, bends: capsules * 48 + 8,
|
||||
attachments: capsules * PerSheet + 8, tethers: 8, joints: 0, gravityY: 0f);
|
||||
var sheets = new Box3DSoaParticleHandle[capsules][];
|
||||
var all = new List<Box3DSoaAttachmentDesc>();
|
||||
for (var c = 0; c < capsules; c++)
|
||||
{
|
||||
var origin = (0.5f * (c % 10), 0f, 0.5f * (c / 10));
|
||||
var bone = w.AddCapsule((ulong)(c + 1), origin, 0.05f, 0.1f, 500f);
|
||||
var sheet = Graph.Sheet(w, (origin.Item1 - 0.125f, -0.125f, origin.Item3 + Offset), (Step, 0f, 0f), (0f, Step, 0f), Side, Side, 0.02f, 0.0125f,
|
||||
Box3DSoaPhase.Of((uint)(c + 1), noParticleContact: true));
|
||||
sheets[c] = sheet.Particles;
|
||||
for (var q = 0; q < PerSheet; q++)
|
||||
all.Add(new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, sheet.Particles[q], bone, (-0.125f + Step * (q % Side), -0.125f + Step * (q / Side), Offset), compliance: 1e-4f, limb: true, oneWay: true));
|
||||
}
|
||||
w.Attach(all.ToArray());
|
||||
return (w, sheets);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dormant_flesh_cost_line()
|
||||
{
|
||||
// 76 capsules each with a 6 x 6 attached sheet (2,736 particles, about four Fellas' 2,644): live, all pinned, one sheet woken, and the bodies with no
|
||||
// particles, alternately 5 times, milliseconds per step over 10 steps after 3 warm-up steps (the Debug suite pays for every step of the live world). Printed, no bound.
|
||||
static double Median(double[] x) { Array.Sort(x); return x[x.Length / 2]; }
|
||||
const int n = 76;
|
||||
var names = new[] { "live", "pinned", "one woken", "bodies only" };
|
||||
var samples = names.Select(_ => new double[5]).ToArray();
|
||||
for (var r = 0; r < 5; r++)
|
||||
{
|
||||
for (var m = 0; m < 4; m++)
|
||||
{
|
||||
var mode = (m + r) % 4;
|
||||
var (w, sheets) = Fellas(n);
|
||||
using (w)
|
||||
{
|
||||
var all = sheets.SelectMany(x => x).ToArray();
|
||||
if (mode == 3) w.DestroyParticles(all);
|
||||
if (mode == 1 || mode == 2) w.SetPinned(all, true);
|
||||
if (mode == 2) w.SetPinned(sheets[0], false);
|
||||
Box3DSoaParticleTests.Run(w, 3);
|
||||
var watch = System.Diagnostics.Stopwatch.StartNew();
|
||||
Box3DSoaParticleTests.Run(w, 10);
|
||||
samples[mode][r] = watch.Elapsed.TotalMilliseconds / 10.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
var line = "PIN_COST 76 capsules, 2736 particles, ms per step, medians of 5 interleaved: " + string.Join(", ", names.Select((nm, i) => $"{nm} {F(Median(samples[i]))}"));
|
||||
Reading(line);
|
||||
Assert.True(Median(samples[1]) > 0);
|
||||
}
|
||||
|
||||
// ---- (g) attach, wake and remove against a pinned particle ----------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void A_pinned_particle_takes_no_tether()
|
||||
{
|
||||
using var s = Chained(extra: 16);
|
||||
var w = s.World;
|
||||
var rope = Graph.Rope(w, Graph.Line((1f, 1f, 0f), (0.03f, 0f, 0f), 6), 0.02f, 0.0125f, Box3DSoaPhase.Of(7, noParticleContact: true));
|
||||
w.Attach(Box3DSoaAttachKind.Body, rope.Particles[5], s.Bones[0], (0f, 0f, 0.2f));
|
||||
s.View = w.View;
|
||||
w.SetPinned([rope.Particles[5]], true);
|
||||
Run(s, 3);
|
||||
var free = w.FreeAttachmentSlots;
|
||||
Refused(s, () => w.Attach(Box3DSoaAttachKind.Static, rope.Particles[5], point: (1f, 1f, 0f), tether: true), "a tether on a pinned particle");
|
||||
Refused(s, () => w.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: (1f, 1f, 0f), tether: true), "a tether on live flesh of a component that holds pinned flesh");
|
||||
Refused(s, () => w.Attach([new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, rope.Particles[0], -1, (1f, 1f, 0f), 0f, false, false, false),
|
||||
new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, rope.Particles[5], -1, (1f, 1f, 0f), 0f, true, false, false)]), "a batch with one tether on a pinned particle");
|
||||
Assert.Equal(free, w.FreeAttachmentSlots);
|
||||
Assert.Equal(1u, s.View.ParticlePinned[rope.Particles[5]]);
|
||||
w.SetPinned([rope.Particles[5]], false); // woken, it takes the tether like any particle
|
||||
w.Attach(Box3DSoaAttachKind.Static, rope.Particles[5], point: (1f, 1f, 0f), tether: true);
|
||||
Refused(s, () => w.SetPinned([rope.Particles[4]], true), "a tethered component");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void An_attach_in_any_lane_leaves_a_pinned_particles_anchor(bool freeBelow)
|
||||
{
|
||||
using var s = Chained(extra: 4);
|
||||
var w = s.World;
|
||||
var (b, c) = (s.P[0][1], s.P[0][2]);
|
||||
w.SetPinned([b], true); // b's anchor is lane Anchor[0][1] = 1
|
||||
if (freeBelow)
|
||||
{
|
||||
w.Remove(s.Anchor[0][0]); // lane 0, below b's anchor
|
||||
Run(s, 2); // a freed lane is reused only a step later
|
||||
}
|
||||
var v = s.View;
|
||||
var lanes = ParticleLanes(v);
|
||||
// a mixed batch, new flesh beside resting flesh plus a second attachment on the resting particle: accepted whatever lanes are free
|
||||
var made = new Box3DSoaConstraintHandle[2];
|
||||
w.Attach([new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, b, -1, (1f, 1f, 1f), 0f, false, false, false),
|
||||
new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, c, -1, (0.5f, 1.8f, 0f), 0f, false, false, false)], made);
|
||||
Assert.Equal(freeBelow, made[0].Lane < s.Anchor[0][1].Lane); // b's second attachment lands below its anchor when a lane there is free
|
||||
w.Attach(Box3DSoaAttachKind.Static, b, point: (1f, 1f, 1f)); // and alone
|
||||
v = s.View;
|
||||
Assert.Equal(s.Anchor[0][1].Lane, v.ParticleAnchor[b.Lane]);
|
||||
Assert.Equal(lanes, ParticleLanes(v)); // bit for bit
|
||||
Run(s, 2);
|
||||
w.SetPinned([b], false);
|
||||
v = s.View;
|
||||
Assert.True(Dist(At(v, b.Lane), AnchorNow(s, 0, 1).Point) <= WakeAnchor, "a woken particle lands on the anchor it was pinned on");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Waking_a_live_particle_moves_nothing()
|
||||
{
|
||||
using var s = Chained();
|
||||
var w = s.World;
|
||||
Run(s, 10);
|
||||
var v = s.View;
|
||||
var live = s.P[2][7];
|
||||
var (x, y, z, vx, vy, vz) = (v.ParticleX[live], v.ParticleY[live], v.ParticleZ[live], v.ParticleVx[live], v.ParticleVy[live], v.ParticleVz[live]);
|
||||
w.SetPinned([live], false);
|
||||
Assert.Equal((x, y, z, vx, vy, vz), (v.ParticleX[live], v.ParticleY[live], v.ParticleZ[live], v.ParticleVx[live], v.ParticleVy[live], v.ParticleVz[live]));
|
||||
w.SetPinned([s.P[0][0]], true);
|
||||
Run(s, 3);
|
||||
(x, y, z, vx, vy, vz) = (v.ParticleX[live], v.ParticleY[live], v.ParticleZ[live], v.ParticleVx[live], v.ParticleVy[live], v.ParticleVz[live]);
|
||||
w.SetPinned([live, s.P[0][0]], false); // a batch of a live and a pinned particle: only the pinned one is put on its anchor
|
||||
Assert.Equal((x, y, z, vx, vy, vz), (v.ParticleX[live], v.ParticleY[live], v.ParticleZ[live], v.ParticleVx[live], v.ParticleVy[live], v.ParticleVz[live]));
|
||||
Assert.Equal(0u, v.ParticlePinned[s.P[0][0]]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_body_that_pinned_flesh_is_attached_to_cannot_be_removed()
|
||||
{
|
||||
using var s = Chained();
|
||||
var w = s.World;
|
||||
w.SetPinned(s.P[1], true);
|
||||
Run(s, 3);
|
||||
var before = HashAll(s.View);
|
||||
var bone = new Box3DSoaBodyHandle(s.Bones[1], s.View.BodyGeneration[s.Bones[1]]);
|
||||
Assert.Throws<InvalidOperationException>(() => w.RemoveBody(bone));
|
||||
Assert.Equal((uint)Box3DSoaKind.Capsule, s.View.Kind[s.Bones[1]]);
|
||||
Assert.Equal(before, HashAll(s.View));
|
||||
Run(s, 3);
|
||||
Assert.True(s.View.PositionY[s.Bones[1]] > 1f); // the body is where it was
|
||||
}
|
||||
}
|
||||
264
tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTetherTests.cs
Normal file
264
tests/Ymir.Box3D.Soa.Tests/Box3DSoaPinTetherTests.cs
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// No distance component holds both a pinned particle and a live TETHER attachment (docs/soa-world.md, pinned): a tether loads every lane of its
|
||||
/// component and no walk moves a pinned one. rederive_topology checks it once for every command; these read it through each door a
|
||||
/// command opens, and through random command sequences.
|
||||
/// </summary>
|
||||
public sealed class Box3DSoaPinTetherTests
|
||||
{
|
||||
private const float R = 0.0125f;
|
||||
|
||||
private static ulong Fnv(ulong h, ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
foreach (var b in bytes) { h ^= b; h *= 1099511628211ul; }
|
||||
return h;
|
||||
}
|
||||
|
||||
/// <summary>Every lane the view exposes for particles, constraints, tethers and bodies, with the counts and free slots.</summary>
|
||||
private static ulong State(Box3DSoaWorld w)
|
||||
{
|
||||
var v = w.View;
|
||||
var h = 1469598103934665603ul;
|
||||
void L<T>(ReadOnlySpan<T> lane) where T : unmanaged => h = Fnv(h, MemoryMarshal.AsBytes(lane));
|
||||
void I(long x) => h = Fnv(h, BitConverter.GetBytes(x));
|
||||
I(v.ParticleCount); I(v.DistanceCount); I(v.BendCount); I(v.AttachmentCount); I(v.TetherCount);
|
||||
I(w.FreeDistanceSlots); I(w.FreeBendSlots); I(w.FreeAttachmentSlots);
|
||||
L(v.ParticleX); L(v.ParticleY); L(v.ParticleZ); L(v.ParticleVx); L(v.ParticleVy); L(v.ParticleVz); L(v.ParticleInvMass);
|
||||
L(v.ParticleLive); L(v.ParticleGeneration); L(v.ParticleComponent); L(v.ParticlePinned); L(v.ParticleAnchor);
|
||||
L(v.ParticleImpulseX); L(v.ParticleImpulseY); L(v.ParticleImpulseZ);
|
||||
L(v.DistanceA); L(v.DistanceB); L(v.DistanceRest); L(v.DistanceCompliance); L(v.DistanceTension); L(v.DistanceLive); L(v.DistanceGeneration);
|
||||
L(v.BendA); L(v.BendB); L(v.BendC); L(v.BendE1); L(v.BendE2); L(v.BendLive); L(v.BendGeneration);
|
||||
L(v.AttachmentKind); L(v.AttachmentFlags); L(v.AttachmentGeneration); L(v.AttachmentParticle); L(v.AttachmentBody);
|
||||
L(v.AttachmentPointX); L(v.AttachmentPointY); L(v.AttachmentPointZ); L(v.AttachmentForceX); L(v.AttachmentForceY); L(v.AttachmentForceZ);
|
||||
L(v.TetherAttachment); L(v.TetherParticle); L(v.TetherParent); L(v.TetherEdge); L(v.TetherOther); L(v.TetherBound);
|
||||
L(v.PositionX); L(v.PositionY); L(v.PositionZ); L(v.RotationX); L(v.RotationY); L(v.RotationZ); L(v.RotationW);
|
||||
L(v.VelocityX); L(v.VelocityY); L(v.VelocityZ); L(v.AngularVelocityX); L(v.AngularVelocityY); L(v.AngularVelocityZ);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static void Step(Box3DSoaWorld w, int n) => Box3DSoaParticleTests.Run(w, n);
|
||||
|
||||
/// <summary>Soul's scenes: rope A (4 particles, R0..R2 on a bone, `pinA` pins them) and rope B (3 particles, B0 tethered to a ball), apart.</summary>
|
||||
private sealed class Scene : IDisposable
|
||||
{
|
||||
public Box3DSoaWorld W = null!;
|
||||
public int Bone, Ball;
|
||||
public Box3DSoaParticleHandle[] A = null!, B = null!;
|
||||
public void Dispose() => W.Dispose();
|
||||
}
|
||||
|
||||
private static Scene Make(bool pinA = true, bool tetherB = true)
|
||||
{
|
||||
var s = new Scene { W = new Box3DSoaWorld(8, gravityY: 0f, particles: new Box3DSoaParticleCapacities(64, 32, 32, 32, 64, 2, 0, 0, 0)) };
|
||||
var w = s.W;
|
||||
s.Bone = w.AddAnchor(1, (0f, 1f, 0f));
|
||||
s.Ball = w.AddSphere(5, (0.45f, 1.0f, 0f), 0.05f, 1000f);
|
||||
s.A = Graph.Rope(w, Graph.Line((0f, 1f, 0f), (0.05f, 0f, 0f), 4), 0.02f, R, Box3DSoaPhase.Of(4, noParticleContact: true)).Particles;
|
||||
for (var k = 0; k < 3; k++) w.Attach(Box3DSoaAttachKind.Body, s.A[k], s.Bone, (0.05f * k, 0f, 0f), limb: true, oneWay: true);
|
||||
s.B = Graph.Rope(w, Graph.Line((0.2f, 1f, 0f), (0.05f, 0f, 0f), 3), 0.02f, R, Box3DSoaPhase.Of(5, noParticleContact: true)).Particles;
|
||||
if (tetherB) w.Attach(Box3DSoaAttachKind.Body, s.B[2], s.Ball, (-0.15f, 0f, 0f), tether: true);
|
||||
if (pinA) w.SetPinned(s.A[..3], true);
|
||||
Step(w, 3);
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>The command is refused (status 1) with every lane as in a twin that never saw it, and stays so over ten steps (the active lists too).</summary>
|
||||
private static void RefusedLikeTwin(string what, Action<Scene> command, Func<Scene>? make = null)
|
||||
{
|
||||
make ??= () => Make();
|
||||
using var s = make();
|
||||
using var twin = make();
|
||||
Assert.Equal(State(twin.W), State(s.W));
|
||||
var e = Assert.Throws<InvalidOperationException>(() => command(s));
|
||||
Assert.Contains("status 1", e.Message);
|
||||
Assert.True(State(twin.W) == State(s.W), $"{what}: the refusal changed a lane");
|
||||
Step(s.W, 10);
|
||||
Step(twin.W, 10);
|
||||
Assert.True(State(twin.W) == State(s.W), $"{what}: the refused world steps differently");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_tether_on_pinned_flesh_is_refused_whole()
|
||||
{
|
||||
RefusedLikeTwin("a tether on a pinned particle", s => s.W.Attach(Box3DSoaAttachKind.Body, s.A[1], s.Ball, (-0.4f, 0f, 0f), tether: true));
|
||||
RefusedLikeTwin("a batch: a plain attach, then a tether on a pinned particle", s => s.W.Attach([
|
||||
new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, s.A[3], s.Bone, (0.15f, 0f, 0f)),
|
||||
new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, s.A[0], s.Ball, (-0.45f, 0f, 0f), tether: true)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_tether_on_a_live_neighbour_of_pinned_flesh_is_refused_whole()
|
||||
{
|
||||
RefusedLikeTwin("a tether on live R3 of a component with pinned R0..R2", s => s.W.Attach(Box3DSoaAttachKind.Body, s.A[3], s.Ball, (-0.3f, 0f, 0f), tether: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_distance_joining_pinned_flesh_to_a_tethered_component_is_refused_whole()
|
||||
{
|
||||
RefusedLikeTwin("one distance A3-B0", s => s.W.CreateDistances([new Box3DSoaDistanceDesc(s.A[3], s.B[0])]));
|
||||
RefusedLikeTwin("a batch: one harmless distance, then the join", s => s.W.CreateDistances([
|
||||
new Box3DSoaDistanceDesc(s.B[0], s.B[2]), new Box3DSoaDistanceDesc(s.A[3], s.B[0])]));
|
||||
// the controls: woken, or with nothing tethered, the same join is accepted
|
||||
using (var woke = Make())
|
||||
{
|
||||
woke.W.SetPinned(woke.A[..3], false);
|
||||
woke.W.CreateDistances([new Box3DSoaDistanceDesc(woke.A[3], woke.B[0])]);
|
||||
Assert.Equal(woke.W.View.ParticleComponent[woke.A[0]], woke.W.View.ParticleComponent[woke.B[2]]);
|
||||
}
|
||||
using (var untethered = Make(tetherB: false))
|
||||
untethered.W.CreateDistances([new Box3DSoaDistanceDesc(untethered.A[3], untethered.B[0])]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_pin_in_a_tethered_component_is_refused_whole()
|
||||
{
|
||||
static Scene Joined()
|
||||
{
|
||||
var s = Make(pinA: false);
|
||||
s.W.CreateDistances([new Box3DSoaDistanceDesc(s.A[3], s.B[0])]);
|
||||
return s;
|
||||
}
|
||||
RefusedLikeTwin("a pin of R0..R2 joined to tethered B", s => s.W.SetPinned(s.A[..3], true), Joined);
|
||||
RefusedLikeTwin("a pin of R1 alone", s => s.W.SetPinned([s.A[1]], true), Joined);
|
||||
}
|
||||
|
||||
// ---- random command sequences ---------------------------------------------------------------------------
|
||||
|
||||
private static bool Holds(Box3DSoaView v, out string why)
|
||||
{
|
||||
var n = v.ParticleCount;
|
||||
var root = new int[n];
|
||||
for (var i = 0; i < n; i++) root[i] = i;
|
||||
int Find(int i) { while (root[i] != i) i = root[i] = root[root[i]]; return i; }
|
||||
for (var e = 0; e < v.DistanceCount; e++)
|
||||
if (v.DistanceLive[e] != 0) root[Find(v.DistanceA[e])] = Find(v.DistanceB[e]);
|
||||
var pinned = new HashSet<int>();
|
||||
var tethered = new HashSet<int>();
|
||||
for (var i = 0; i < n; i++) if (v.ParticleLive[i] != 0 && v.ParticlePinned[i] != 0) pinned.Add(Find(i));
|
||||
for (var a = 0; a < v.AttachmentCount; a++)
|
||||
if (v.AttachmentKind[a] != (uint)Box3DSoaAttachKind.Removed && (v.AttachmentFlags[a] & 1u) != 0) tethered.Add(Find(v.AttachmentParticle[a]));
|
||||
// the view's component lane names the same partition
|
||||
for (var i = 0; i < n; i++)
|
||||
for (var j = i + 1; j < n; j++)
|
||||
if (v.ParticleLive[i] != 0 && v.ParticleLive[j] != 0 && (Find(i) == Find(j)) != (v.ParticleComponent[i] == v.ParticleComponent[j]))
|
||||
{
|
||||
why = $"particles {i} and {j}: component lane disagrees with the distances";
|
||||
return false;
|
||||
}
|
||||
pinned.IntersectWith(tethered);
|
||||
why = pinned.Count == 0 ? "" : $"component of {pinned.First()} holds pinned flesh and a tether";
|
||||
return pinned.Count == 0;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] [InlineData(7)] [InlineData(8)]
|
||||
public void No_command_sequence_puts_pinned_flesh_and_a_tether_in_one_component(int seed)
|
||||
{
|
||||
const int N = 12;
|
||||
var rng = new Random(seed);
|
||||
using var w = new Box3DSoaWorld(8, gravityY: -10f, particles: new Box3DSoaParticleCapacities(N, 48, 32, 64, 8192, 2, 0, 0, 0));
|
||||
var bone = w.AddAnchor(1, (0f, 1f, 0f));
|
||||
var ball = w.AddSphere(5, (0f, 0.5f, 0.5f), 0.05f, 100f);
|
||||
var p = new Box3DSoaParticleHandle[N];
|
||||
var desc = new Box3DSoaParticleDesc[N];
|
||||
for (var i = 0; i < N; i++) desc[i] = new Box3DSoaParticleDesc((0.06f * i, 1f, 0f), 0.02f, R, Box3DSoaPhase.Of((uint)(1 + i % 3), noParticleContact: true));
|
||||
w.CreateParticles(desc, p);
|
||||
for (var i = 0; i < N; i++) w.Attach(Box3DSoaAttachKind.Body, p[i], bone, (0.06f * i, 0f, 0f), compliance: 1e-4f, limb: true, oneWay: true);
|
||||
Box3DSoaParticleHandle Any() => p[rng.Next(N)];
|
||||
Box3DSoaAttachmentDesc Tether(Box3DSoaParticleHandle q) => rng.Next(2) == 0
|
||||
? new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Static, q, -1, (w.View.ParticleX[q], w.View.ParticleY[q], 0f), tether: true)
|
||||
: new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, q, ball, (0f, 0.5f, -0.5f), tether: true);
|
||||
int accepted = 0, refused = 0, pins = 0, joins = 0, tethers = 0;
|
||||
var refusedBy = new int[12];
|
||||
for (var c = 0; c < 400; c++)
|
||||
{
|
||||
var v = w.View;
|
||||
var kind = rng.Next(12);
|
||||
Action command;
|
||||
switch (kind)
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
var d = new Box3DSoaDistanceDesc[1 + rng.Next(2)];
|
||||
for (var k = 0; k < d.Length; k++)
|
||||
{
|
||||
var a = rng.Next(N);
|
||||
d[k] = new Box3DSoaDistanceDesc(p[a], p[(a + 1 + rng.Next(N - 1)) % N], 1e-4f);
|
||||
}
|
||||
command = () => { w.CreateDistances(d); joins++; };
|
||||
break;
|
||||
}
|
||||
case 1: case 2:
|
||||
{
|
||||
var d = rng.Next(2) == 0 ? new[] { Tether(Any()) } : new[] { new Box3DSoaAttachmentDesc(Box3DSoaAttachKind.Body, Any(), bone, (0f, 0f, 0f)), Tether(Any()) };
|
||||
command = () => { w.Attach(d); tethers++; };
|
||||
break;
|
||||
}
|
||||
case 3: case 4:
|
||||
{
|
||||
var set = Enumerable.Range(0, 1 + rng.Next(4)).Select(_ => Any()).ToArray();
|
||||
command = () => { w.SetPinned(set, true); pins++; };
|
||||
break;
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
var set = Enumerable.Range(0, 1 + rng.Next(4)).Select(_ => Any()).ToArray();
|
||||
command = () => w.SetPinned(set, false);
|
||||
break;
|
||||
}
|
||||
case 6: case 7: case 8:
|
||||
{
|
||||
var live = Enumerable.Range(0, v.DistanceCount).Where(e => v.DistanceLive[e] != 0).ToArray();
|
||||
if (live.Length == 0) continue;
|
||||
var e = live[rng.Next(live.Length)];
|
||||
var h = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, e, v.DistanceGeneration[e]);
|
||||
command = () => w.Remove(h);
|
||||
break;
|
||||
}
|
||||
case 9: case 10:
|
||||
{
|
||||
// mostly a tether, so components free up for pins again
|
||||
var tethered = rng.Next(3) != 0;
|
||||
var live = Enumerable.Range(0, v.AttachmentCount).Where(a => v.AttachmentKind[a] != (uint)Box3DSoaAttachKind.Removed && (!tethered || (v.AttachmentFlags[a] & 1u) != 0)).ToArray();
|
||||
if (live.Length == 0) continue;
|
||||
var a = live[rng.Next(live.Length)];
|
||||
var h = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Attachment, a, v.AttachmentGeneration[a]);
|
||||
command = () => w.Remove(h);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
// a bend over two live distances sharing a particle, else a step
|
||||
var live = Enumerable.Range(0, v.DistanceCount).Where(e => v.DistanceLive[e] != 0 && v.DistanceRest[e] > 0f).ToArray();
|
||||
var pair = live.SelectMany(e1 => live.Where(e2 => e2 > e1 &&
|
||||
((v.DistanceA[e1] == v.DistanceA[e2] ? 1 : 0) + (v.DistanceA[e1] == v.DistanceB[e2] ? 1 : 0) + (v.DistanceB[e1] == v.DistanceA[e2] ? 1 : 0) + (v.DistanceB[e1] == v.DistanceB[e2] ? 1 : 0)) == 1)
|
||||
.Select(e2 => (e1, e2))).ToArray();
|
||||
if (pair.Length == 0 || rng.Next(2) == 0) { command = () => Step(w, 1); break; }
|
||||
var (x, y) = pair[rng.Next(pair.Length)];
|
||||
var b = new Box3DSoaBendDesc(new(Box3DSoaConstraintType.Distance, x, v.DistanceGeneration[x]), new(Box3DSoaConstraintType.Distance, y, v.DistanceGeneration[y]));
|
||||
command = () => w.CreateBends([b]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
var before = State(w);
|
||||
try
|
||||
{
|
||||
command();
|
||||
accepted++;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
refused++;
|
||||
refusedBy[kind]++;
|
||||
Assert.True(before == State(w), $"seed {seed} command {c} (kind {kind}): a refusal changed a lane");
|
||||
}
|
||||
Assert.True(Holds(w.View, out var why), $"seed {seed} after command {c} (kind {kind}): {why}");
|
||||
}
|
||||
Console.Error.WriteLine($"PIN_TETHER seed {seed}: accepted {accepted}, refused {refused}, pins {pins}, joins {joins}, tethers {tethers}; refused joins {refusedBy[0]}, tethers {refusedBy[1] + refusedBy[2]}, pins {refusedBy[3] + refusedBy[4]}");
|
||||
Assert.True(pins > 10 && joins > 10 && tethers > 10, $"seed {seed}: the sequence exercised too little (refused {refused}, pins {pins}, joins {joins}, tethers {tethers})");
|
||||
}
|
||||
}
|
||||
484
tests/Ymir.Box3D.Soa.Tests/Box3DSoaRemoveTests.cs
Normal file
484
tests/Ymir.Box3D.Soa.Tests/Box3DSoaRemoveTests.cs
Normal file
|
|
@ -0,0 +1,484 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
/// <summary>Body removal: docs/soa-world.md, Release. RemoveBody is the one body-ending path; it is refused while a liquid sensor or attachment names the body.</summary>
|
||||
public sealed class Box3DSoaRemoveTests
|
||||
{
|
||||
private const float Dt = 1f / 60f;
|
||||
private const float R = 0.0125f;
|
||||
|
||||
private static Box3DSoaWorld World(int bodies = 8, int joints = 4, int fluid = 16, int wets = 8, int sensors = 4) =>
|
||||
new(bodies, gravityY: -10f, jointCapacity: joints,
|
||||
particles: new Box3DSoaParticleCapacities(16, 16, 16, 4, 16, 2, fluid, wets, sensors));
|
||||
|
||||
private static void Run(Box3DSoaWorld world, int steps)
|
||||
{
|
||||
for (var i = 0; i < steps; i++) world.Step(Dt);
|
||||
}
|
||||
|
||||
/// <summary>The state a refusal must leave alone: every body and joint lane that RemoveBody writes.</summary>
|
||||
private static string Snapshot(Box3DSoaWorld world)
|
||||
{
|
||||
var v = world.View;
|
||||
return string.Join(",", v.Kind.ToArray()) + "|" + string.Join(",", v.BodyGeneration.ToArray()) + "|" + string.Join(",", v.StableId.ToArray()) +
|
||||
"|" + string.Join(",", v.JointKind.ToArray()) + "|" + string.Join(",", v.JointGeneration.ToArray()) + "|" + string.Join(",", v.WetLive.ToArray()) +
|
||||
"|" + string.Join(",", v.SensorLive.ToArray()) + "|" + string.Join(",", v.AttachmentKind.ToArray()) + "|" + world.StepCount;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removing_a_body_retires_its_joints_and_zeroes_its_lane()
|
||||
{
|
||||
using var world = World();
|
||||
var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f));
|
||||
var upper = world.AddCapsule(2, (0f, 4.5f, 0f), 0.1f, 0.4f, 1000f, parent: pin, limb: 3, materialId: 9);
|
||||
var lower = world.AddCapsule(3, (0f, 3.5f, 0f), 0.1f, 0.4f, 1000f, parent: upper);
|
||||
var elsewhere = world.AddSphere(4, (3f, 5f, 0f), 0.1f, 1000f);
|
||||
var j1 = world.AddJoint(Box3DSoaJointKind.Spherical, pin, upper, (0f, 5f, 0f), (0f, 0f, 1f));
|
||||
var j2 = world.AddJoint(Box3DSoaJointKind.Revolute, upper, lower, (0f, 4f, 0f), (0f, 0f, 1f));
|
||||
var j3 = world.AddJoint(Box3DSoaJointKind.Weld, pin, elsewhere, (1f, 5f, 0f), (0f, 0f, 1f));
|
||||
Run(world, 10);
|
||||
var view = world.View;
|
||||
Assert.Equal(upper.Generation, view.BodyGeneration[upper]);
|
||||
|
||||
world.RemoveBody(upper);
|
||||
Assert.Equal((uint)Box3DSoaKind.Removed, view.Kind[upper]);
|
||||
Assert.Equal(upper.Generation + 1, view.BodyGeneration[upper]);
|
||||
Assert.Equal(0ul, view.StableId[upper]);
|
||||
Assert.Equal(-1, view.Parent[upper]);
|
||||
Assert.Equal(0, view.Limb[upper]);
|
||||
Assert.Equal(0ul, view.MaterialId[upper]);
|
||||
Assert.Equal(0, view.ContactCount[upper]);
|
||||
Assert.Equal(0f, view.PositionX[upper] + view.PositionY[upper] + view.PositionZ[upper]);
|
||||
Assert.Equal(0f, view.RotationX[upper] + view.RotationW[upper] + view.VelocityY[upper]);
|
||||
Assert.Equal(0f, view.Size0[upper] + view.Size1[upper] + view.ContactImpulse[upper]);
|
||||
foreach (var joint in new[] { j1, j2 })
|
||||
{
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Removed, view.JointKind[joint]);
|
||||
Assert.Equal(joint.Generation + 1, view.JointGeneration[joint]);
|
||||
Assert.Equal(-1, view.JointBodyA[joint]);
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(joint)); // the old handles are stale
|
||||
}
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Weld, view.JointKind[j3]); // a joint that does not name it stays
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(upper)); // already gone
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(new Box3DSoaBodyHandle(lower.Lane, lower.Generation + 1))); // stale
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(new Box3DSoaBodyHandle(8, 0))); // out of range
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(new Box3DSoaBodyHandle(-1, 0)));
|
||||
|
||||
world.Step(Dt); // the removals are published by the next step, in removal order
|
||||
var bodies = world.Facts.BodiesRemoved;
|
||||
Assert.Equal(1, bodies.Length);
|
||||
Assert.Equal((upper.Lane, upper.Generation, 2ul, 0u, 0f), (bodies[0].Lane, bodies[0].Generation, bodies[0].StableId, bodies[0].WetPatches, bodies[0].WetVolume));
|
||||
var joints = world.Facts.JointsRemoved;
|
||||
Assert.Equal(2, joints.Length);
|
||||
Assert.Equal((j1.Lane, j1.Generation, pin.Lane, upper.Lane, 1u), (joints[0].Lane, joints[0].Generation, joints[0].BodyA, joints[0].BodyB, joints[0].WithBody));
|
||||
Assert.Equal((j2.Lane, j2.Generation, upper.Lane, lower.Lane, 1u), (joints[1].Lane, joints[1].Generation, joints[1].BodyA, joints[1].BodyB, joints[1].WithBody));
|
||||
world.Step(Dt);
|
||||
Assert.Equal(0, world.Facts.BodiesRemoved.Length + world.Facts.JointsRemoved.Length); // facts last one step
|
||||
Run(world, 29); // the world steps on, the removed lane stays a tombstone, the orphan falls free
|
||||
Assert.Equal((uint)Box3DSoaKind.Removed, view.Kind[upper]);
|
||||
Assert.Equal(0f, view.PositionY[upper]);
|
||||
Assert.True(view.PositionY[lower] < 3.5f - 0.5f, "the child of a removed body is free");
|
||||
Assert.Equal(lower.Generation, view.BodyGeneration[lower]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removal_is_refused_while_an_attachment_or_a_sensor_names_the_body()
|
||||
{
|
||||
using var world = World();
|
||||
var floor = world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f));
|
||||
var box = world.AddBox(2, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), 500f);
|
||||
var other = world.AddSphere(3, (1f, 0.1f, 0f), 0.1f, 500f);
|
||||
var joint = world.AddJoint(Box3DSoaJointKind.Weld, box, other, (0.5f, 0.1f, 0f), (0f, 0f, 1f));
|
||||
var p = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new((0f, 0.1f, 0f), 0.02f, R)], p);
|
||||
var attachment = world.Attach(Box3DSoaAttachKind.Body, p[0], box, (0f, 0f, 0f));
|
||||
var sensors = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(box, (0f, 0f, 0f), 0.2f)], sensors);
|
||||
Run(world, 5);
|
||||
var before = Snapshot(world);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(box)); // both name it
|
||||
Assert.Equal(before, Snapshot(world));
|
||||
world.Remove(attachment);
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(box)); // the sensor still does
|
||||
Assert.Equal((uint)Box3DSoaKind.Box, world.View.Kind[box]);
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Weld, world.View.JointKind[joint]); // a refusal retired nothing
|
||||
world.Remove(sensors[0]);
|
||||
world.RemoveBody(box);
|
||||
|
||||
var removed = box.Lane;
|
||||
Assert.Equal((uint)Box3DSoaKind.Removed, world.View.Kind[removed]);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Attach(Box3DSoaAttachKind.Body, p[0], removed, (0f, 0f, 0f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(removed, (0f, 0f, 0f), 0.2f)]));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddJoint(Box3DSoaJointKind.Weld, floor, removed, (0f, 0f, 0f), (0f, 0f, 1f)));
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddSphere(10, (2f, 1f, 0f), 0.1f, 500f, parent: removed));
|
||||
Assert.Equal(0, world.View.AttachmentCount == 0 ? 0 : world.View.AttachmentKind.ToArray().Count(k => k == (uint)Box3DSoaAttachKind.Body));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_attachment_alone_refuses_removal_and_an_anchor_is_no_exception()
|
||||
{
|
||||
using var world = World();
|
||||
var box = world.AddBox(2, (0f, 2f, 0f), (0.1f, 0.1f, 0.1f), 500f);
|
||||
var attached = world.AddAnchor(3, (1f, 2f, 0f));
|
||||
var sensed = world.AddAnchor(4, (2f, 2f, 0f));
|
||||
var p = new Box3DSoaParticleHandle[2];
|
||||
world.CreateParticles([new((0f, 2f, 0f), 0.02f, R), new((1f, 2f, 0f), 0.02f, R)], p);
|
||||
var onBox = world.Attach(Box3DSoaAttachKind.Body, p[0], box, (0f, 0f, 0f));
|
||||
var onAnchor = world.Attach(Box3DSoaAttachKind.Body, p[1], attached, (0f, 0f, 0f));
|
||||
var sensors = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(sensed, (0f, 0f, 0f), 0.2f)], sensors);
|
||||
Run(world, 3);
|
||||
var before = Snapshot(world);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(box)); // an attachment alone names it
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(attached)); // an anchor named by an attachment
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(sensed)); // an anchor named by a sensor
|
||||
Assert.Equal(before, Snapshot(world));
|
||||
|
||||
world.Remove(onBox);
|
||||
world.Remove(onAnchor);
|
||||
world.Remove(sensors[0]);
|
||||
world.RemoveBody(box);
|
||||
world.RemoveBody(attached);
|
||||
world.RemoveBody(sensed);
|
||||
Assert.All(new[] { box, attached, sensed }, h => Assert.Equal((uint)Box3DSoaKind.Removed, world.View.Kind[h]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_current_generation_handle_to_a_removed_lane_is_refused()
|
||||
{
|
||||
using var world = World();
|
||||
var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f));
|
||||
var bob = world.AddSphere(2, (0f, 4f, 0f), 0.1f, 1000f);
|
||||
var gone = world.AddSphere(3, (1f, 4f, 0f), 0.1f, 1000f);
|
||||
var joint = world.AddJoint(Box3DSoaJointKind.Weld, pin, bob, (0f, 5f, 0f), (0f, 0f, 1f));
|
||||
world.Step(Dt);
|
||||
world.DestroyJoint(joint);
|
||||
world.RemoveBody(gone);
|
||||
var view = world.View;
|
||||
// The tombstones' own generations: only the removed kind refuses these.
|
||||
var forgedJoint = new Box3DSoaJointHandle(joint.Lane, view.JointGeneration[joint]);
|
||||
var forgedBody = new Box3DSoaBodyHandle(gone.Lane, view.BodyGeneration[gone]);
|
||||
var before = Snapshot(world);
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(forgedJoint));
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(forgedBody));
|
||||
Assert.Equal(before, Snapshot(world));
|
||||
world.Step(Dt);
|
||||
Assert.Equal(1, world.Facts.JointsRemoved.Length);
|
||||
Assert.Equal(1, world.Facts.BodiesRemoved.Length);
|
||||
world.AddSphere(0, (2f, 4f, 0f), 0.1f, 1000f); // a tombstone's stable id 0 is no live id: the duplicate scan skips it
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_removed_lane_is_skipped_by_the_particle_substeps_and_the_write_lanes()
|
||||
{
|
||||
using var world = World();
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f));
|
||||
var gone = world.AddSphere(2, (1f, 0.1f, 0f), 0.1f, 1000f);
|
||||
var p = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new((-1f, 0.5f, 0f), 0.02f, R)], p); // live particles: the substep callback runs
|
||||
Run(world, 3);
|
||||
world.RemoveBody(gone);
|
||||
var view = world.View;
|
||||
view.ForceX[gone] = float.NaN; // a removed lane's write lanes are not checked, only cleared
|
||||
view.TorqueZ[gone] = float.PositiveInfinity;
|
||||
Run(world, 30);
|
||||
Assert.Equal(0f, view.ForceX[gone]);
|
||||
Assert.Equal(0f, view.TorqueZ[gone]);
|
||||
Assert.Equal(0f, view.ParticleImpulseX[gone]);
|
||||
Assert.Equal(1u, view.ParticleLive[p[0].Lane]);
|
||||
}
|
||||
|
||||
/// <summary>The retired shape table holds one step's removals (capacity: the body count); a removal every step for many steps
|
||||
/// overruns it unless each step clears it, and every removed toucher's End still names it. In a Debug build the write asserts the table has room, so the never-cleared mutant (the clear deleted) aborts the run there: a Debug-only observable, as the Release build has no bounds check.</summary>
|
||||
[Fact]
|
||||
public void The_retired_table_holds_one_steps_removals()
|
||||
{
|
||||
using var world = World(bodies: 2, joints: 0);
|
||||
var floor = world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f));
|
||||
for (var cycle = 0; cycle < 200; cycle++)
|
||||
{
|
||||
var id = (ulong)(100 + cycle);
|
||||
var ball = world.AddSphere(id, (0f, 0.1f, 0f), 0.1f, 1000f);
|
||||
world.Step(Dt);
|
||||
world.Step(Dt);
|
||||
Assert.True(world.View.ContactCount[ball] > 0, $"cycle {cycle}: touching");
|
||||
world.RemoveBody(ball);
|
||||
world.Step(Dt);
|
||||
var ends = world.Facts.End;
|
||||
Assert.Equal(1, ends.Length);
|
||||
Assert.Equal(new[] { (floor.Lane, 1ul), (ball.Lane, id) }.OrderBy(x => x.Item1),
|
||||
new[] { (ends[0].LaneA, ends[0].StableIdA), (ends[0].LaneB, ends[0].StableIdB) }.OrderBy(x => x.Item1));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_removed_anchor_ends_its_grab()
|
||||
{
|
||||
using var world = World();
|
||||
var anchor = world.AddAnchor(1, (0f, 5f, 0f));
|
||||
var sphere = world.AddSphere(2, (0f, 5f, 0f), 0.1f, 1000f);
|
||||
var grab = world.AddMotorJoint(anchor, sphere, (0f, 5f, 0f), (5f, 0.7f, 5000f), (0f, 0f, 0f));
|
||||
Run(world, 30);
|
||||
var view = world.View;
|
||||
Assert.Equal(5f, view.PositionY[sphere], 0.3f); // held
|
||||
|
||||
world.RemoveBody(anchor);
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Removed, view.JointKind[grab]);
|
||||
Assert.Throws<InvalidOperationException>(() => world.DestroyJoint(grab)); // the grab handle is stale
|
||||
Run(world, 60);
|
||||
Assert.True(view.PositionY[sphere] < 3f, "the grabbed body falls");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_drop_resting_on_a_removed_body_cannot_settle()
|
||||
{
|
||||
using var world = World();
|
||||
var floor = world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
var p = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new((0f, R, 0f), 0.015625f, R, Box3DSoaPhase.Of(0, fluid: true), 0u, null, default)], p);
|
||||
Run(world, 20);
|
||||
var view = world.View;
|
||||
Assert.Equal(floor.Lane, view.SupportBody[0]);
|
||||
world.RemoveBody(floor);
|
||||
Assert.Equal(floor.Lane, view.SupportBody[0]); // last step's fact: it may name the dead lane until the next substep
|
||||
var before = Snapshot(world);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Settle(p));
|
||||
Assert.Equal(before, Snapshot(world));
|
||||
Assert.Equal(1u, view.ParticleLive[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wet_patches_go_with_the_body()
|
||||
{
|
||||
using var world = World(fluid: 16, wets: 16);
|
||||
var a = world.AddStaticBox(1, (-1f, -0.5f, 0f), (0.5f, 0.5f, 0.5f), friction: 0.3f);
|
||||
var b = world.AddStaticBox(2, (1f, -0.5f, 0f), (0.5f, 0.5f, 0.5f), friction: 0.3f);
|
||||
var at = new[] { -1.3f, -1f, -0.7f, 0.9f, 1.2f };
|
||||
var phase = Box3DSoaPhase.Of(0, fluid: true);
|
||||
world.CreateParticles(at.Select(x => new Box3DSoaParticleDesc((x, R, 0f), 0.015625f, R, phase, 0u, null, default)).ToArray());
|
||||
Run(world, 20);
|
||||
var view = world.View;
|
||||
Assert.Equal(new[] { a.Lane, a.Lane, a.Lane, b.Lane, b.Lane }, Enumerable.Range(0, 5).Select(i => view.SupportBody[i]).ToArray());
|
||||
world.Settle(Enumerable.Range(0, 5).Select(i => new Box3DSoaParticleHandle(i, view.ParticleGeneration[i])).ToArray());
|
||||
view = world.View;
|
||||
var onA = Enumerable.Range(0, view.WetCount).Where(w => view.WetLive[w] != 0 && view.WetBody[w] == a.Lane).ToArray();
|
||||
var onB = Enumerable.Range(0, view.WetCount).Where(w => view.WetLive[w] != 0 && view.WetBody[w] == b.Lane).ToArray();
|
||||
Assert.Equal(3, onA.Length);
|
||||
Assert.Equal(2, onB.Length);
|
||||
var volumeB = view.WetVolume[b.Lane];
|
||||
var generationsB = onB.Select(w => view.WetGeneration[w]).ToArray();
|
||||
Assert.True(view.WetVolume[a.Lane] > 0f && volumeB > 0f);
|
||||
var generationsA = onA.Select(w => view.WetGeneration[w]).ToArray();
|
||||
|
||||
var volumeA = 0f;
|
||||
foreach (var w in onA) volumeA += view.WetPatchVolume[w];
|
||||
world.RemoveBody(a);
|
||||
world.Step(Dt);
|
||||
var removed = world.Facts.BodiesRemoved;
|
||||
Assert.Equal(1, removed.Length);
|
||||
Assert.Equal(3u, removed[0].WetPatches);
|
||||
Assert.Equal(volumeA, removed[0].WetVolume, volumeA * 1e-5f);
|
||||
for (var k = 0; k < onA.Length; k++)
|
||||
{
|
||||
Assert.Equal(0u, view.WetLive[onA[k]]);
|
||||
Assert.Equal(generationsA[k] + 1, view.WetGeneration[onA[k]]);
|
||||
}
|
||||
Assert.Equal(0f, view.WetVolume[a.Lane]);
|
||||
Assert.Equal(volumeB, view.WetVolume[b.Lane]); // the other body's patches are untouched
|
||||
for (var k = 0; k < onB.Length; k++)
|
||||
{
|
||||
Assert.Equal(1u, view.WetLive[onB[k]]);
|
||||
Assert.Equal(generationsB[k], view.WetGeneration[onB[k]]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_removed_toucher_ends_its_touch_by_name()
|
||||
{
|
||||
using var world = World();
|
||||
var floor = world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f));
|
||||
var ball = world.AddSphere(77, (0f, 0.12f, 0f), 0.1f, 1000f);
|
||||
var other = world.AddSphere(78, (1f, 0.12f, 0f), 0.1f, 1000f);
|
||||
Run(world, 40);
|
||||
Assert.True(world.View.ContactCount[ball] > 0);
|
||||
world.RemoveBody(ball);
|
||||
world.Step(Dt);
|
||||
var ends = world.Facts.End;
|
||||
Assert.Equal(1, ends.Length);
|
||||
Assert.Equal(new[] { (ball.Lane, 77ul), (floor.Lane, 1ul) }.OrderBy(x => x.Item1), new[] { (ends[0].LaneA, ends[0].StableIdA), (ends[0].LaneB, ends[0].StableIdB) }.OrderBy(x => x.Item1));
|
||||
world.Step(Dt);
|
||||
Assert.Equal(0, world.Facts.End.Length);
|
||||
_ = other;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Destroying_a_joint_is_a_removal_fact_too()
|
||||
{
|
||||
using var world = World();
|
||||
var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f));
|
||||
var bob = world.AddSphere(2, (0f, 4f, 0f), 0.1f, 1000f);
|
||||
var joint = world.AddJoint(Box3DSoaJointKind.Weld, pin, bob, (0f, 5f, 0f), (0f, 0f, 1f));
|
||||
world.Step(Dt);
|
||||
world.DestroyJoint(joint);
|
||||
world.Step(Dt);
|
||||
var joints = world.Facts.JointsRemoved;
|
||||
Assert.Equal(1, joints.Length);
|
||||
Assert.Equal((joint.Lane, joint.Generation, pin.Lane, bob.Lane, 0u), (joints[0].Lane, joints[0].Generation, joints[0].BodyA, joints[0].BodyB, joints[0].WithBody));
|
||||
Assert.Equal(0, world.Facts.BodiesRemoved.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_refused_step_publishes_nothing_and_keeps_the_removal_for_the_next()
|
||||
{
|
||||
using var world = World();
|
||||
var ball = world.AddSphere(1, (0f, 5f, 0f), 0.1f, 1000f);
|
||||
var other = world.AddSphere(2, (1f, 5f, 0f), 0.1f, 1000f);
|
||||
world.RemoveBody(ball);
|
||||
world.View.ForceX[other] = float.NaN;
|
||||
Assert.Throws<InvalidOperationException>(() => world.Step(Dt)); // a non-finite write lane refuses the whole step
|
||||
world.View.ForceX[other] = 0f;
|
||||
world.Step(Dt);
|
||||
Assert.Equal(1, world.Facts.BodiesRemoved.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lanes_survive_the_removal_of_others()
|
||||
{
|
||||
using var world = World(bodies: 8, joints: 0);
|
||||
var h = Enumerable.Range(0, 6).Select(i => world.AddSphere((ulong)(i + 1), (i * 0.5f, 5f + i, 0f), 0.1f, 1000f, velocity: (0.1f * i, 0f, 0f))).ToArray();
|
||||
Run(world, 10);
|
||||
var view = world.View;
|
||||
var keep = new[] { 0, 1, 2, 4, 5 };
|
||||
var posBefore = keep.Select(i => (view.PositionX[h[i]], view.PositionY[h[i]], view.VelocityX[h[i]])).ToArray();
|
||||
world.RemoveBody(h[3]);
|
||||
foreach (var i in keep)
|
||||
{
|
||||
Assert.Equal((uint)Box3DSoaKind.Sphere, view.Kind[h[i]]);
|
||||
Assert.Equal((ulong)(i + 1), view.StableId[h[i]]);
|
||||
Assert.Equal(h[i].Generation, view.BodyGeneration[h[i]]);
|
||||
}
|
||||
Assert.Equal(posBefore, keep.Select(i => (view.PositionX[h[i]], view.PositionY[h[i]], view.VelocityX[h[i]])).ToArray()); // continuity: nothing moved
|
||||
Run(world, 5);
|
||||
Assert.Equal(6, view.Count); // the high-water mark
|
||||
Assert.All(keep, i => Assert.True(view.PositionY[h[i]] < 5f + i, "the others keep falling"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_removed_lane_is_reused_one_step_later_with_a_new_generation()
|
||||
{
|
||||
using var world = World(bodies: 3, joints: 0);
|
||||
var a = world.AddSphere(1, (0f, 5f, 0f), 0.1f, 1000f);
|
||||
var b = world.AddSphere(2, (1f, 5f, 0f), 0.1f, 1000f);
|
||||
var c = world.AddSphere(3, (2f, 5f, 0f), 0.1f, 1000f);
|
||||
Assert.Equal(0, world.FreeBodySlots);
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddSphere(4, (3f, 5f, 0f), 0.1f, 1000f)); // full
|
||||
world.RemoveBody(b);
|
||||
Assert.Equal(0, world.FreeBodySlots); // not within the removing step
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddSphere(4, (3f, 5f, 0f), 0.1f, 1000f));
|
||||
world.Step(Dt);
|
||||
Assert.Equal(1, world.FreeBodySlots);
|
||||
var d = world.AddSphere(2, (3f, 5f, 0f), 0.1f, 1000f); // the removed stable id may be reused
|
||||
Assert.Equal(b.Lane, d.Lane);
|
||||
Assert.Equal(b.Generation + 1, d.Generation);
|
||||
var view = world.View;
|
||||
Assert.Equal((uint)Box3DSoaKind.Sphere, view.Kind[d]);
|
||||
Assert.Equal(3f, view.PositionX[d], 1e-5f);
|
||||
Assert.Equal(3, view.Count);
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(b)); // the old handle is stale against the new occupant
|
||||
Assert.Equal((uint)Box3DSoaKind.Sphere, view.Kind[d]);
|
||||
Assert.Throws<InvalidOperationException>(() => world.AddSphere(2, (4f, 5f, 0f), 0.1f, 1000f)); // a live stable id still collides (and the world is full)
|
||||
world.RemoveBody(a);
|
||||
world.Step(Dt);
|
||||
Assert.Equal(a.Lane, world.AddSphere(7, (5f, 5f, 0f), 0.1f, 1000f).Lane); // lowest free lane first
|
||||
_ = c;
|
||||
}
|
||||
|
||||
/// <summary>Random add/remove churn of falling spheres on a floor. Run it in Debug too: Box3D validates its broad-phase there, and a
|
||||
/// body removed while its proxy was the only one moving left the dynamic tree flagged enlarged (fixed in box3d c790839).</summary>
|
||||
[Fact]
|
||||
public void Add_and_remove_churn_keeps_the_world_valid()
|
||||
{
|
||||
for (var seed = 1; seed <= 12; seed++)
|
||||
{
|
||||
using var world = World(bodies: 6, joints: 0);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 4f));
|
||||
var rng = new Random(seed);
|
||||
var live = new List<Box3DSoaBodyHandle>();
|
||||
var next = 2ul;
|
||||
var removals = 0;
|
||||
for (var step = 0; step < 120; step++)
|
||||
{
|
||||
if (rng.Next(3) == 0)
|
||||
{
|
||||
if (live.Count > 0 && (world.FreeBodySlots == 0 || rng.Next(2) == 0))
|
||||
{
|
||||
var k = rng.Next(live.Count);
|
||||
world.RemoveBody(live[k]);
|
||||
live.RemoveAt(k);
|
||||
removals++;
|
||||
}
|
||||
else if (world.FreeBodySlots > 0)
|
||||
{
|
||||
live.Add(world.AddSphere(next++, (4f * rng.NextSingle() - 2f, 0.2f + 2f * rng.NextSingle(), 4f * rng.NextSingle() - 2f), 0.1f, 1000f));
|
||||
}
|
||||
}
|
||||
world.Step(Dt);
|
||||
}
|
||||
Assert.True(removals >= 5, $"seed {seed}: {removals} removals");
|
||||
var view = world.View;
|
||||
Assert.All(live, h => Assert.Equal((uint)Box3DSoaKind.Sphere, view.Kind[h]));
|
||||
Assert.All(live, h => Assert.InRange(view.PositionY[h], 0f, 2.5f)); // on or above the floor, none lost through it
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Replay()
|
||||
{
|
||||
using var world = World(bodies: 8, joints: 4);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 4f));
|
||||
var a = world.AddCapsule(2, (0f, 1f, 0f), 0.1f, 0.3f, 800f);
|
||||
var b = world.AddSphere(3, (0.3f, 2f, 0f), 0.1f, 800f);
|
||||
var c = world.AddBox(4, (-0.3f, 3f, 0f), (0.1f, 0.1f, 0.1f), 800f);
|
||||
var j1 = world.AddJoint(Box3DSoaJointKind.Spherical, a, b, (0.1f, 1.5f, 0f), (0f, 0f, 1f), forceThreshold: 50f);
|
||||
var j2 = world.AddJoint(Box3DSoaJointKind.Weld, a, c, (-0.1f, 1.5f, 0f), (0f, 0f, 1f));
|
||||
var view = world.View;
|
||||
var o = new MemoryStream();
|
||||
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
|
||||
for (var i = 0; i < 300; i++)
|
||||
{
|
||||
if (i == 60) world.RemoveBody(b);
|
||||
if (i == 120) world.SetJointThresholds(j2, 5f, float.PositiveInfinity);
|
||||
world.Step(Dt);
|
||||
B(view.PositionX); B(view.PositionY); B(view.RotationW); B(view.VelocityY); B(view.Kind); B(view.BodyGeneration); B(view.StableId);
|
||||
B(view.JointKind); B(view.JointGeneration); B(view.JointConstraintForceY); B(view.JointConstraintTorqueZ);
|
||||
B(world.Facts.Overloads);
|
||||
}
|
||||
Assert.Equal((uint)Box3DSoaJointKind.Removed, view.JointKind[j1]);
|
||||
return o.ToArray();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_world_with_removals_and_thresholds_repeats_bit_for_bit()
|
||||
{
|
||||
var first = Replay();
|
||||
Assert.True(first.AsSpan().SequenceEqual(Replay()));
|
||||
Assert.Contains(first, x => x != 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removing_a_body_and_the_step_after_allocate_nothing_managed()
|
||||
{
|
||||
using var world = World(bodies: 8, joints: 2);
|
||||
var a = world.AddSphere(1, (0f, 5f, 0f), 0.1f, 1000f);
|
||||
var b = world.AddSphere(2, (1f, 5f, 0f), 0.1f, 1000f);
|
||||
world.AddJoint(Box3DSoaJointKind.Weld, a, b, (0.5f, 5f, 0f), (0f, 0f, 1f));
|
||||
Run(world, 5);
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
world.RemoveBody(a);
|
||||
world.Step(Dt);
|
||||
Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
}
|
||||
249
tests/Ymir.Box3D.Soa.Tests/Box3DSoaSensorTests.cs
Normal file
249
tests/Ymir.Box3D.Soa.Tests/Box3DSoaSensorTests.cs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Liquid sensors: docs/soa-world.md, Sensors. A sphere fixed in a body reads the liquid volume inside it at the end of every step; nothing reads it back.</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
/// <summary>The volume the sensor must read: (2 r)^3 summed in lane order over the live fluid lanes whose centre is within <paramref name="radius"/> of <paramref name="centre"/>, the count, and the closest any centre comes to the sphere's surface.</summary>
|
||||
private static (float Volume, int Count, double Margin) Inside(Box3DSoaView v, Pos centre, float radius)
|
||||
{
|
||||
var volume = 0f;
|
||||
var count = 0;
|
||||
var margin = double.MaxValue;
|
||||
for (var i = 0; i < v.ParticleCount; i++)
|
||||
{
|
||||
if (v.ParticleLive[i] == 0 || (v.ParticlePhase[i] & Box3DSoaPhase.Fluid) == 0) continue;
|
||||
double dx = v.ParticleX[i] - centre.X, dy = v.ParticleY[i] - centre.Y, dz = v.ParticleZ[i] - centre.Z;
|
||||
var d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||
margin = Math.Min(margin, Math.Abs(d - radius));
|
||||
if (d <= radius)
|
||||
{
|
||||
var side = 2f * v.ParticleRadius[i];
|
||||
volume += side * side * side;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return (volume, count, margin);
|
||||
}
|
||||
|
||||
/// <summary>A well of half-width 0.15 (floor is body lane 0, top at y 0, frame origin at y -0.5) with a 6 x 6 x 6 block of water in it.</summary>
|
||||
private static Box3DSoaWorld Pool(int sensors, int bodies = 8)
|
||||
{
|
||||
var world = FluidWorld(256, bodies, gravityY: -9.81f, sensors: sensors);
|
||||
Well(world, 0.15f);
|
||||
Graph.Block(world, (-0.0625f, 0.0125f, -0.0625f), 6, 6, 6, R, FluidMass, FluidPhase);
|
||||
return world;
|
||||
}
|
||||
|
||||
private static void Run(Box3DSoaWorld world, int ticks)
|
||||
{
|
||||
for (var t = 0; t < ticks; t++) world.Step(Dt, Sub);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensor_reads_the_liquid_inside()
|
||||
{
|
||||
using var world = Pool(sensors: 4);
|
||||
var handles = new Box3DSoaConstraintHandle[3];
|
||||
// The floor's frame origin is (0, -0.5, 0): a body-frame y of 0.5 + h is world height h over the floor.
|
||||
world.CreateSensors([(0, (0f, 0.54f, 0f), 0.06f), (0, (0f, 1.5f, 0f), 0.1f), (0, (0f, 0.55f, 0f), 1f)], handles);
|
||||
Run(world, 90);
|
||||
var v = world.View;
|
||||
var part = Inside(v, (0f, 0.04f, 0f), 0.06f);
|
||||
var above = Inside(v, (0f, 1f, 0f), 0.1f);
|
||||
var all = Inside(v, (0f, 0.05f, 0f), 1f);
|
||||
Assert.True(part.Count > 0 && part.Count < all.Count, $"the scene must split the pool: {part.Count} of {all.Count}");
|
||||
Assert.True(part.Margin > 1e-4 && all.Margin > 1e-4, $"a centre within 0.1 mm of a sensor's surface: {part.Margin} {all.Margin}");
|
||||
Assert.Equal(216, all.Count);
|
||||
Assert.Equal(part.Volume, v.SensorLiquidVolume[handles[0]]);
|
||||
Assert.Equal(0f, above.Volume);
|
||||
Assert.Equal(0f, v.SensorLiquidVolume[handles[1]]);
|
||||
Assert.Equal(all.Volume, v.SensorLiquidVolume[handles[2]]);
|
||||
Assert.Equal(3, v.SensorCount);
|
||||
Readings.Add($"SENSOR pool 216 drops: partial sensor {part.Count} drops = {part.Volume:E4} m^3, all {all.Count} = {all.Volume:E4} m^3, margin {part.Margin:E2} m");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensor_on_a_dunked_and_lifted_body_reads_up_then_0()
|
||||
{
|
||||
using var world = Pool(sensors: 2);
|
||||
var anchor = world.AddAnchor(9, (0f, 0.6f, 0f));
|
||||
var handle = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(anchor, (0.02f, 0f, 0f), 0.05f)], handle);
|
||||
Run(world, 60);
|
||||
var v = world.View;
|
||||
Assert.Equal(0f, v.SensorLiquidVolume[handle[0]]);
|
||||
var peak = 0f;
|
||||
var reads = new List<float>();
|
||||
for (var t = 0; t < 40; t++)
|
||||
{
|
||||
var y = t < 20 ? 0.6f - 0.03f * (t + 1) : 0.03f * (t - 19); // down to y 0, then back up to 0.6
|
||||
world.SetAnchorTarget(anchor, (0f, y, 0f), default, Dt);
|
||||
world.Step(Dt, Sub);
|
||||
v = world.View;
|
||||
var want = Inside(v, (v.PositionX[anchor] + 0.02f, v.PositionY[anchor], v.PositionZ[anchor]), 0.05f);
|
||||
Assert.True(want.Margin > 1e-4, $"tick {t}: a centre within 0.1 mm of the surface ({want.Margin})");
|
||||
Assert.Equal(want.Volume, v.SensorLiquidVolume[handle[0]]);
|
||||
reads.Add(v.SensorLiquidVolume[handle[0]]);
|
||||
peak = MathF.Max(peak, reads[^1]);
|
||||
}
|
||||
Assert.True(peak >= 3f * DropVolume, $"dunked: peak {peak}");
|
||||
Assert.True(reads.Take(3).All(r => r == 0f), "above the surface it reads 0 on the way down");
|
||||
Assert.Equal(0f, reads[^1]);
|
||||
Readings.Add($"SENSOR dunk and lift: peak {peak:E4} m^3 ({peak / DropVolume:F1} drops), first {reads[0]}, last {reads[^1]}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensor_follows_its_body_frame_and_the_pose_the_step_ends_in()
|
||||
{
|
||||
// Zero gravity, drops 0.5 m apart so none moves. The anchor is turned a quarter about z, so its body-frame point (0.3, 0, 0) lies at world (x, y + 0.3, z) over it,
|
||||
// and it runs 0.5 m a tick along x: at the end of tick s it is over x 0.5 s. A drop waits there for even s only, so a sensor that reads the wrong place or pose
|
||||
// differs on the odd ticks, where a decoy lies at (x + 0.3, 0, 0) (an unrotated frame's centre) 0.42 m from the true centre (inside a radius compared unsquared).
|
||||
using var world = FluidWorld(32, 4, gravityY: 0f, sensors: 2);
|
||||
var descs = new List<Box3DSoaParticleDesc>();
|
||||
for (var k = 0; k < 10; k++)
|
||||
{
|
||||
if (k % 2 == 0) descs.Add(Fluid((0.5f * k, 0.3f, 0f), FluidMass, R));
|
||||
descs.Add(Fluid((0.5f * k + 0.3f, 0f, 0f), FluidMass, R));
|
||||
}
|
||||
world.CreateParticles(descs.ToArray());
|
||||
var q = (0f, 0f, 0.70710678f, 0.70710678f);
|
||||
var anchor = world.AddAnchor(9, (0f, 0f, 0f), q);
|
||||
var handle = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(anchor, (0.3f, 0f, 0f), 0.2f)], handle);
|
||||
var reads = new float[10];
|
||||
for (var s = 1; s <= 9; s++)
|
||||
{
|
||||
world.SetAnchorTarget(anchor, (0.5f * s, 0f, 0f), q, Dt);
|
||||
world.Step(Dt, Sub);
|
||||
reads[s] = world.View.SensorLiquidVolume[handle[0]];
|
||||
}
|
||||
for (var s = 1; s <= 9; s++) Assert.Equal(s % 2 == 0 ? DropVolume : 0f, reads[s]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensor_reads_0_once_every_drop_is_gone()
|
||||
{
|
||||
// The step's end returns early with no live particle; the sensor pass must run before that, or the sensor keeps its last reading.
|
||||
foreach (var how in new[] { "destroyed", "destroyed with a solid left", "settled" })
|
||||
{
|
||||
using var world = FluidWorld(64, gravityY: -9.81f, wets: 8, sensors: 2);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
var drops = Graph.Block(world, (0f, 0.0125f, 0f), 3, 1, 3, R, FluidMass, FluidPhase);
|
||||
if (how == "destroyed with a solid left") world.CreateParticles([new Box3DSoaParticleDesc((1f, 1f, 1f), 1f, R)]);
|
||||
var handle = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(0, (0f, 0.5f, 0f), 0.5f)], handle);
|
||||
Run(world, 20);
|
||||
var nine = 0f;
|
||||
for (var k = 0; k < 9; k++) nine += DropVolume; // the lane-order float sum the native pass makes
|
||||
Assert.Equal(nine, world.View.SensorLiquidVolume[handle[0]]);
|
||||
if (how == "settled") world.Settle(drops);
|
||||
else world.DestroyParticles(drops);
|
||||
world.Step(Dt, Sub);
|
||||
Assert.Equal(0f, world.View.SensorLiquidVolume[handle[0]]);
|
||||
Assert.Equal(how == "destroyed with a solid left" ? 1 : 0, world.View.ParticleLive.ToArray().Count(l => l != 0));
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] SensorBytes(Box3DSoaView v)
|
||||
{
|
||||
var o = new MemoryStream();
|
||||
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
|
||||
B(v.SensorBody); B(v.SensorX); B(v.SensorY); B(v.SensorZ); B(v.SensorRadius); B(v.SensorLiquidVolume); B(v.SensorLive); B(v.SensorGeneration); B(v.SensorRemovedAt);
|
||||
o.Write(BitConverter.GetBytes(v.SensorCount));
|
||||
return o.ToArray();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensor_refusals_and_reuse()
|
||||
{
|
||||
using var world = FluidWorld(16, 3, gravityY: 0f, sensors: 3);
|
||||
world.AddStaticBox(1, (0f, 0f, 0f), (1f, 1f, 1f));
|
||||
world.AddAnchor(2, (0f, 3f, 0f));
|
||||
var before = SensorBytes(world.View);
|
||||
var bad = new (int Body, Pos Point, float Radius)[]
|
||||
{
|
||||
(-1, (0f, 0f, 0f), 0.1f), (2, (0f, 0f, 0f), 0.1f), (0, (0f, 0f, 0f), 0f), (0, (0f, 0f, 0f), -0.1f), (0, (0f, 0f, 0f), float.NaN),
|
||||
(0, (0f, 0f, 0f), float.PositiveInfinity), (0, (float.NaN, 0f, 0f), 0.1f), (0, (0f, float.PositiveInfinity, 0f), 0.1f),
|
||||
};
|
||||
foreach (var b in bad)
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(0, (0f, 0f, 0f), 0.1f), b]));
|
||||
Assert.True(before.AsSpan().SequenceEqual(SensorBytes(world.View)), "a refused batch changed a lane");
|
||||
Assert.Equal(3, world.FreeSensorSlots);
|
||||
}
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(0, default, 0.1f), (0, default, 0.1f), (0, default, 0.1f), (0, default, 0.1f)]));
|
||||
Assert.True(before.AsSpan().SequenceEqual(SensorBytes(world.View)), "a batch past the capacity changed a lane");
|
||||
var h = new Box3DSoaConstraintHandle[3];
|
||||
world.CreateSensors([(0, (0.1f, 0.2f, 0.3f), 0.4f), (1, (0f, 0f, 0f), 0.5f), (0, (1f, 1f, 1f), 0.6f)], h);
|
||||
Assert.Equal([0, 1, 2], h.Select(x => x.Lane));
|
||||
Assert.All(h, x => Assert.Equal(Box3DSoaConstraintType.Sensor, x.Type));
|
||||
var view = world.View;
|
||||
Assert.Equal(0, world.FreeSensorSlots);
|
||||
Assert.Equal([0, 1, 0], view.SensorBody.ToArray());
|
||||
Assert.Equal(0.2f, view.SensorY[0]);
|
||||
Assert.Equal(0.5f, view.SensorRadius[1]);
|
||||
// Remove: a tombstone reading 0, its lane back after a step, the lowest first, the old handle refused.
|
||||
world.Remove([h[0], h[2]]);
|
||||
view = world.View;
|
||||
Assert.Equal([0u, 1u, 0u], view.SensorLive.ToArray());
|
||||
Assert.Equal([-1, 1, -1], view.SensorBody.ToArray());
|
||||
Assert.Equal(0f, view.SensorRadius[0]);
|
||||
Assert.Equal(0, world.FreeSensorSlots);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Remove(h[0]));
|
||||
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(0, default, 0.1f)]));
|
||||
world.Step(Dt, Sub);
|
||||
Assert.Equal(2, world.FreeSensorSlots);
|
||||
var again = new Box3DSoaConstraintHandle[2];
|
||||
world.CreateSensors([(1, (0f, 0f, 0f), 0.7f), (0, (0f, 0f, 0f), 0.8f)], again);
|
||||
Assert.Equal([0, 2], again.Select(x => x.Lane));
|
||||
Assert.Equal([1u, 1u], again.Select(x => x.Generation));
|
||||
Assert.Throws<InvalidOperationException>(() => world.Remove(h[0])); // the old occupant's handle
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sensors_move_nothing()
|
||||
{
|
||||
// The same pool with and without four sensors steps to the same bytes in every other lane.
|
||||
static byte[] Bytes(bool sensors)
|
||||
{
|
||||
using var world = Pool(sensors ? 4 : 0);
|
||||
if (sensors) world.CreateSensors([(0, (0f, 0.54f, 0f), 0.06f), (0, (0.06f, 0.55f, 0f), 0.07f), (0, (0f, 0.6f, 0f), 0.2f), (0, (0f, 1.5f, 0f), 0.1f)]);
|
||||
Run(world, 120);
|
||||
var v = world.View;
|
||||
var o = new MemoryStream();
|
||||
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
|
||||
B(v.ParticleX); B(v.ParticleY); B(v.ParticleZ); B(v.ParticleVx); B(v.ParticleVy); B(v.ParticleVz); B(v.ParticleDensity); B(v.SupportBody); B(v.SupportParticle);
|
||||
B(v.PositionX); B(v.PositionY); B(v.PositionZ); B(v.ParticleImpulseX); B(v.ParticleImpulseY); B(v.ParticleImpulseZ); B(v.ParticleLive); B(v.ParticleGeneration);
|
||||
return o.ToArray();
|
||||
}
|
||||
Assert.True(Bytes(true).AsSpan().SequenceEqual(Bytes(false)), "a sensor moved something");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_sensor_never_reaches_the_topology_derivation_and_Ymir_names_no_organ()
|
||||
{
|
||||
var source = NativeSource("ymir_particles.c").Replace("\r\n", "\n");
|
||||
var at = source.IndexOf("if (type == YMIR_LANES_SENSOR)", StringComparison.Ordinal);
|
||||
Assert.True(at > 0);
|
||||
var branch = source.Substring(at, source.IndexOf("return YMIR_PARTICLES_OK;", at, StringComparison.Ordinal) - at);
|
||||
branch = System.Text.RegularExpressions.Regex.Replace(branch, "//[^\n]*", "");
|
||||
Assert.DoesNotContain("rederive_", branch);
|
||||
Assert.DoesNotContain("TOPO_", branch);
|
||||
// Ymir exposes a volume; what a head or a lung does with it is the caller's.
|
||||
var organ = new System.Text.RegularExpressions.Regex("airway|lung|throat", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
for (var d = new DirectoryInfo(AppContext.BaseDirectory); d is not null; d = d.Parent)
|
||||
{
|
||||
var native = Path.Combine(d.FullName, "native", "Ymir.Box3D");
|
||||
var src = Path.Combine(d.FullName, "src", "Ymir.Box3D");
|
||||
if (!Directory.Exists(native) || !Directory.Exists(src)) continue;
|
||||
foreach (var file in Directory.EnumerateFiles(native, "*.c").Concat(Directory.EnumerateFiles(native, "*.h")).Concat(Directory.EnumerateFiles(src, "*.cs")))
|
||||
Assert.False(organ.IsMatch(File.ReadAllText(file)), file + " names an organ");
|
||||
return;
|
||||
}
|
||||
throw new DirectoryNotFoundException("repo root");
|
||||
}
|
||||
}
|
||||
144
tests/Ymir.Box3D.Soa.Tests/Box3DSoaSensorWetTests.cs
Normal file
144
tests/Ymir.Box3D.Soa.Tests/Box3DSoaSensorWetTests.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Liquid sensors read settled liquid too (lodur:ruling:liquid-sensor-reads-pooled-liquid): the wet patches whose centre is inside the sphere, on any body or solid particle, in a lane of their own.</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
/// <summary>The volume the pooled lane must read, by a scan of every wet lane (what the sensor's culled lookup must equal): the patches' volumes summed in lane order over the live patches whose centre, taken to the world, is within <paramref name="radius"/> of <paramref name="centre"/>; with the closest any centre comes to the surface.</summary>
|
||||
private static (float Volume, int Count, double Margin) PooledInside(Box3DSoaView v, Pos centre, float radius)
|
||||
{
|
||||
var volume = 0f;
|
||||
var count = 0;
|
||||
var margin = double.MaxValue;
|
||||
for (var w = 0; w < v.WetCount; w++)
|
||||
{
|
||||
if (v.WetLive[w] == 0) continue;
|
||||
Pos at;
|
||||
if (v.WetBody[w] >= 0)
|
||||
{
|
||||
var b = v.WetBody[w];
|
||||
var (qx, qy, qz, qw) = (v.RotationX[b], v.RotationY[b], v.RotationZ[b], v.RotationW[b]);
|
||||
var (px, py, pz) = (v.WetX[w], v.WetY[w], v.WetZ[w]);
|
||||
var (tx, ty, tz) = (qy * pz - qz * py + qw * px, qz * px - qx * pz + qw * py, qx * py - qy * px + qw * pz);
|
||||
at = (v.PositionX[b] + px + 2f * (qy * tz - qz * ty), v.PositionY[b] + py + 2f * (qz * tx - qx * tz), v.PositionZ[b] + pz + 2f * (qx * ty - qy * tx));
|
||||
}
|
||||
else
|
||||
{
|
||||
var i = v.WetParticle[w];
|
||||
at = (v.ParticleX[i], v.ParticleY[i], v.ParticleZ[i]);
|
||||
}
|
||||
double dx = at.X - centre.X, dy = at.Y - centre.Y, dz = at.Z - centre.Z;
|
||||
var d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||
margin = Math.Min(margin, Math.Abs(d - radius));
|
||||
if (d <= radius)
|
||||
{
|
||||
volume += v.WetPatchVolume[w];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return (volume, count, margin);
|
||||
}
|
||||
|
||||
/// <summary>A floor (body lane 0, frame origin (0, -0.5, 0)) with one drop on it at each of <paramref name="at"/> (x, z), rested 20 ticks so each reads its support.</summary>
|
||||
private static (Box3DSoaWorld World, Box3DSoaParticleHandle[] Drops) DropsOnFloor(Pos[] at, int wets, int sensors)
|
||||
{
|
||||
var world = FluidWorld(at.Length + 8, 8, gravityY: -9.81f, wets: wets, sensors: sensors);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
var desc = at.Select(p => new Box3DSoaParticleDesc((p.X, R, p.Z), FluidMass, R, FluidPhase, 0u, null, default)).ToArray();
|
||||
world.CreateParticles(desc);
|
||||
Run(world, 20);
|
||||
return (world, Enumerable.Range(0, at.Length).Select(i => Handle(world, i)).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settled_liquid_in_a_sphere_reads_in_the_pooled_lane_and_0_live()
|
||||
{
|
||||
var (world, drops) = DropsOnFloor([(-0.4f, 0f, 0f), (-0.2f, 0f, 0f), (0.2f, 0f, 0f), (0.4f, 0f, 0f)], 8, 4);
|
||||
using var _ = world;
|
||||
var anchor = world.AddAnchor(9, (0.2f, 0.3f, 0f));
|
||||
var h = new Box3DSoaConstraintHandle[3];
|
||||
// floor frame: body-frame y 0.5 is the floor's top. A holds the drops at x -0.4 and -0.2; B (r 5 cm) none; C is on the anchor, so the patch at x 0.2 is on another body.
|
||||
world.CreateSensors([(0, (-0.3f, 0.5f, 0f), 0.15f), (0, (0.3f, 0.5f, 0f), 0.05f), (anchor, (0f, 0f, 0f), 0.31f)], h);
|
||||
world.Step(Dt, Sub);
|
||||
var live = world.View.SensorLiquidVolume.ToArray();
|
||||
Assert.True(live[h[0]] >= 2f * DropVolume && world.View.SensorWetVolume.ToArray().All(x => x == 0f), "unsettled drops read live, none pooled");
|
||||
world.Settle(drops);
|
||||
Assert.Equal(live[h[0]], world.View.SensorLiquidVolume[h[0]]); // end-of-step values: a Settle between steps shows at the next step
|
||||
Assert.Equal(0f, world.View.SensorWetVolume[h[0]]);
|
||||
world.Step(Dt, Sub);
|
||||
var v = world.View;
|
||||
var a = PooledInside(v, (-0.3f, 0f, 0f), 0.15f);
|
||||
var b = PooledInside(v, (0.3f, 0f, 0f), 0.05f);
|
||||
var c = PooledInside(v, (0.2f, 0.3f, 0f), 0.31f);
|
||||
Assert.True(Math.Min(a.Margin, Math.Min(b.Margin, c.Margin)) > 1e-4, $"a patch centre within 0.1 mm of a surface: {a.Margin} {b.Margin} {c.Margin}");
|
||||
Assert.Equal(2, a.Count);
|
||||
Assert.Equal(0, b.Count);
|
||||
Assert.Equal(1, c.Count);
|
||||
Assert.Equal(2f * DropVolume, a.Volume);
|
||||
Assert.Equal(a.Volume, v.SensorWetVolume[h[0]]);
|
||||
Assert.Equal(0f, v.SensorWetVolume[h[1]]); // a patch outside reads 0
|
||||
Assert.Equal(c.Volume, v.SensorWetVolume[h[2]]); // a patch on another body counts
|
||||
for (var s = 0; s < 3; s++) Assert.Equal(0f, v.SensorLiquidVolume[h[s]]);
|
||||
Readings.Add($"SENSOR pooled: A {v.SensorWetVolume[h[0]]:E4} m^3 ({a.Count} patches), B {v.SensorWetVolume[h[1]]}, C (anchor, other body) {v.SensorWetVolume[h[2]]:E4}, live 0 after the step");
|
||||
// The lane is a reading, not a record: removing a patch shows at the next step too.
|
||||
world.Step(Dt, Sub);
|
||||
Assert.Equal(a.Volume, world.View.SensorWetVolume[h[0]]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pooled_lane_equals_a_scan_of_every_patch_on_a_dense_floor()
|
||||
{
|
||||
// 64 patches on a 0.15 m grid (a patch disc is 7 cm, so none merge), every one the same volume, so the sum is the same in any order; sensors cut the grid at assorted places.
|
||||
var at = new List<Pos>();
|
||||
for (var i = 0; i < 8; i++) for (var j = 0; j < 8; j++) at.Add((-0.525f + 0.15f * i, 0f, -0.525f + 0.15f * j));
|
||||
var (world, drops) = DropsOnFloor(at.ToArray(), 64, 8);
|
||||
using var _ = world;
|
||||
var spec = new (Pos Point, float Radius)[]
|
||||
{
|
||||
((0.075f, 0.5f, 0.075f), 0.12f), ((0.0f, 0.5f, 0.0f), 0.08f), ((-0.3f, 0.5f, 0.2f), 0.33f), ((0.45f, 0.5f, -0.45f), 0.2f),
|
||||
((0.0f, 0.5f, 0.0f), 1.5f), ((0.0f, 0.9f, 0.0f), 0.3f), ((3f, 0.5f, 0f), 0.5f), ((-0.12f, 0.5f, 0.3f), 0.17f),
|
||||
};
|
||||
var h = new Box3DSoaConstraintHandle[spec.Length];
|
||||
world.CreateSensors(spec.Select(x => (0, x.Point, x.Radius)).ToArray(), h);
|
||||
world.Settle(drops);
|
||||
world.Step(Dt, Sub);
|
||||
var v = world.View;
|
||||
Assert.Equal(64, v.WetLive.ToArray().Count(l => l != 0));
|
||||
var seen = new List<int>();
|
||||
for (var s = 0; s < spec.Length; s++)
|
||||
{
|
||||
var want = PooledInside(v, (spec[s].Point.X, spec[s].Point.Y - 0.5f, spec[s].Point.Z), spec[s].Radius);
|
||||
Assert.True(want.Margin > 1e-4, $"sensor {s}: a patch centre within 0.1 mm of the surface ({want.Margin})");
|
||||
Assert.Equal(want.Volume, v.SensorWetVolume[h[s]]);
|
||||
seen.Add(want.Count);
|
||||
}
|
||||
Assert.Contains(seen, n => n > 0 && n < 64);
|
||||
Assert.Contains(seen, n => n == 64);
|
||||
Assert.Contains(seen, n => n == 0);
|
||||
Readings.Add($"SENSOR pooled dense: patches inside per sensor {string.Join(",", seen)} of 64, each equal to a scan of every lane");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settled_liquid_on_a_solid_particle_reads_pooled()
|
||||
{
|
||||
using var world = FluidWorld(64, 8, gravityY: -9.81f, wets: 4, sensors: 2);
|
||||
world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f));
|
||||
var plate = Graph.Block(world, (-0.05f, 0.2f, -0.05f), 5, 1, 5, R, 0f, Box3DSoaPhase.Of(4));
|
||||
var drop = Graph.Block(world, (0.0f, 0.2f + 2f * R + 0.001f, 0.0f), 1, 1, 1, R, FluidMass, FluidPhase);
|
||||
var h = new Box3DSoaConstraintHandle[2];
|
||||
world.CreateSensors([(0, (0f, 50.2f, 0f), 0.3f), (0, (0f, 52f, 0f), 0.3f)], h);
|
||||
Run(world, 20);
|
||||
Assert.True(world.View.SupportParticle[drop[0].Lane] >= 0, "the drop rests on the plate");
|
||||
world.Settle(drop);
|
||||
world.Step(Dt, Sub);
|
||||
var v = world.View;
|
||||
var want = PooledInside(v, (0f, 0.2f, 0f), 0.3f);
|
||||
Assert.Equal(1, want.Count);
|
||||
Assert.Equal(DropVolume, v.SensorWetVolume[h[0]]);
|
||||
Assert.Equal(0f, v.SensorWetVolume[h[1]]);
|
||||
Assert.Equal(0f, v.SensorLiquidVolume[h[0]]);
|
||||
}
|
||||
}
|
||||
287
tests/Ymir.Box3D.Soa.Tests/Box3DSoaTakeWetTests.cs
Normal file
287
tests/Ymir.Box3D.Soa.Tests/Box3DSoaTakeWetTests.cs
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>take_wet (ABI 21): pooled liquid leaves the wet patches a liquid sensor reads, every patch the same fraction (docs/soa-world.md, Take).</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
// A floor (body 0, its frame origin y -0.5) with three patches: A (x -0.3, two drops, 2 D), B (x -0.1, D) and C (x 0.4, D), and bare floor between.
|
||||
// Sensor centres are given by x on the floor's top (body-frame y 0.5).
|
||||
private static (Box3DSoaWorld World, Box3DSoaConstraintHandle[] Sensors) TakeFloor(params (float X, float Radius)[] sensors)
|
||||
{
|
||||
var (world, drops) = DropsOnFloor([(-0.3f, 0f, 0f), (-0.285f, 0f, 0f), (-0.1f, 0f, 0f), (0.4f, 0f, 0f)], 8, 4);
|
||||
var h = new Box3DSoaConstraintHandle[sensors.Length];
|
||||
world.CreateSensors(sensors.Select(s => (0, (s.X, 0.5f, 0f), s.Radius)).ToArray(), h);
|
||||
world.Settle(drops);
|
||||
world.Step(Dt, Sub);
|
||||
return (world, h);
|
||||
}
|
||||
|
||||
private static float WetRadiusOf(float volume) => MathF.Sqrt(volume / (3.14159265358979f * 1.0e-3f));
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_a_partial_take_leaves_every_patch_in_the_sphere_the_same_fraction()
|
||||
{
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f));
|
||||
using var _ = world;
|
||||
var before = world.View;
|
||||
var vol = before.WetPatchVolume.ToArray();
|
||||
var rad = before.WetRadius.ToArray();
|
||||
var x = before.WetX.ToArray();
|
||||
var live = before.WetLive.ToArray();
|
||||
var inside = Enumerable.Range(0, before.WetCount).Where(w => live[w] != 0 && x[w] < 0f).ToArray();
|
||||
var outside = Enumerable.Range(0, before.WetCount).Where(w => live[w] != 0 && x[w] > 0f).ToArray();
|
||||
Assert.Equal(2, inside.Length);
|
||||
Assert.Single(outside);
|
||||
var pooled = before.SensorWetVolume[s[0]];
|
||||
Assert.Equal(inside.Sum(w => vol[w]), pooled, pooled * 1e-5f);
|
||||
Assert.NotEqual(vol[inside[0]], vol[inside[1]]); // 2 D and D: an equal share would differ from a proportional one
|
||||
var bodyBefore = before.WetVolume[0];
|
||||
var ask = pooled / 3f;
|
||||
var taken = new float[1];
|
||||
world.TakeWet(s, [ask], taken);
|
||||
var v = world.View;
|
||||
Assert.Equal(ask, taken[0], ask * 1e-5f);
|
||||
var keep = 1f - ask / pooled;
|
||||
foreach (var w in inside)
|
||||
{
|
||||
Assert.Equal(vol[w] * keep, v.WetPatchVolume[w], vol[w] * 1e-5f);
|
||||
Assert.Equal(WetRadiusOf(v.WetPatchVolume[w]), v.WetRadius[w], 1e-6f);
|
||||
Assert.Equal(1u, v.WetLive[w]);
|
||||
}
|
||||
foreach (var w in outside)
|
||||
{
|
||||
Assert.Equal(vol[w], v.WetPatchVolume[w]);
|
||||
Assert.Equal(rad[w], v.WetRadius[w]);
|
||||
}
|
||||
Assert.Equal(bodyBefore - taken[0], v.WetVolume[0], bodyBefore * 1e-5f);
|
||||
Assert.Equal(pooled, v.SensorWetVolume[s[0]]); // a reading: it changes at the next step
|
||||
world.Step(Dt, Sub);
|
||||
v = world.View;
|
||||
Assert.Equal(pooled - ask, v.SensorWetVolume[s[0]], pooled * 1e-5f);
|
||||
Assert.Equal(PooledInside(v, (-0.2f, 0f, 0f), 0.15f).Volume, v.SensorWetVolume[s[0]]);
|
||||
Readings.Add($"TAKE partial: pooled {pooled:E4} asked {ask:E4} taken {taken[0]:E4}, keep {keep:F4} in both patches");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_taking_at_least_what_is_there_empties_the_sphere()
|
||||
{
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f));
|
||||
using var _ = world;
|
||||
var before = world.View;
|
||||
var vol = before.WetPatchVolume.ToArray();
|
||||
var x = before.WetX.ToArray();
|
||||
var live = before.WetLive.ToArray();
|
||||
var gen = before.WetGeneration.ToArray();
|
||||
var inside = Enumerable.Range(0, before.WetCount).Where(w => live[w] != 0 && x[w] < 0f).ToArray();
|
||||
var outside = Enumerable.Range(0, before.WetCount).Single(w => live[w] != 0 && x[w] > 0f);
|
||||
var pooled = before.SensorWetVolume[s[0]];
|
||||
var bodyBefore = before.WetVolume[0];
|
||||
var taken = new float[1];
|
||||
world.TakeWet(s, [10f], taken);
|
||||
var v = world.View;
|
||||
Assert.Equal(pooled, taken[0]);
|
||||
foreach (var w in inside)
|
||||
{
|
||||
Assert.Equal(0u, v.WetLive[w]);
|
||||
Assert.Equal(gen[w] + 1, v.WetGeneration[w]);
|
||||
}
|
||||
Assert.Equal(vol[outside], v.WetPatchVolume[outside]);
|
||||
Assert.Equal(1u, v.WetLive[outside]);
|
||||
Assert.Equal(bodyBefore - pooled, v.WetVolume[0], bodyBefore * 1e-5f);
|
||||
world.Step(Dt, Sub);
|
||||
Assert.Equal(0f, world.View.SensorWetVolume[s[0]]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_nothing_to_take_changes_nothing()
|
||||
{
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f), (0.1f, 0.05f)); // the second is over bare floor
|
||||
using var _ = world;
|
||||
var wet = WetBytes(world.View);
|
||||
var body = world.View.WetVolume[0];
|
||||
var taken = new float[] { 9f, 9f };
|
||||
world.TakeWet(s, [0f, 1f], taken);
|
||||
Assert.Equal([0f, 0f], taken);
|
||||
Assert.True(wet.AsSpan().SequenceEqual(WetBytes(world.View)), "a wet lane changed");
|
||||
Assert.Equal(body, world.View.WetVolume[0]);
|
||||
world.TakeWet([], [], default);
|
||||
Assert.True(wet.AsSpan().SequenceEqual(WetBytes(world.View)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_a_patch_on_a_solid_particle_is_taken_as_one_on_a_body()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(4, gravityY: -9.81f, particles: new Box3DSoaParticleCapacities(256, 160, 140, 16, 1024, 2, 16, 4, 2));
|
||||
world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f));
|
||||
var sheet = Graph.Sheet(world, (0f, 0.6f, 0f), (0.04f, 0f, 0f), (0f, 0f, 0.04f), 8, 8, 0.02f, 0.02f, Box3DSoaPhase.Of(4, true, true));
|
||||
for (var j = 0; j < 8; j++)
|
||||
for (var i = 0; i < 8; i += 7)
|
||||
world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[j * 8 + i], point: (0.04f * i, 0.6f, 0.04f * j));
|
||||
var drops = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((0.12f, 0.64f, 0.12f))], drops);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
var under = world.View.SupportParticle[drops[0].Lane];
|
||||
Assert.True(under >= 0);
|
||||
world.Settle(drops);
|
||||
var v0 = world.View;
|
||||
var h = new Box3DSoaConstraintHandle[1];
|
||||
world.CreateSensors([(0, (v0.ParticleX[under], v0.ParticleY[under] + 50f, v0.ParticleZ[under]), 0.02f)], h);
|
||||
world.Step(Dt, Sub);
|
||||
var pooled = world.View.SensorWetVolume[h[0]];
|
||||
var vol = world.View.WetPatchVolume[0];
|
||||
Assert.True(pooled > 0f, "the patch on the solid particle is inside the sphere");
|
||||
Assert.Equal(pooled, vol);
|
||||
var taken = new float[1];
|
||||
world.TakeWet(h, [pooled / 4f], taken);
|
||||
Assert.Equal(vol * 0.75f, world.View.WetPatchVolume[0], vol * 1e-5f);
|
||||
Assert.Equal(WetRadiusOf(world.View.WetPatchVolume[0]), world.View.WetRadius[0], 1e-6f);
|
||||
Assert.Equal(pooled / 4f, taken[0], pooled * 1e-5f);
|
||||
world.TakeWet(h, [1f], taken);
|
||||
Assert.Equal(0u, world.View.WetLive[0]);
|
||||
Assert.Equal(1u, world.View.WetGeneration[0]);
|
||||
Assert.Equal(-1, world.View.WetParticle[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_two_sensors_in_one_call()
|
||||
{
|
||||
// disjoint: the first over A and B, the second over C.
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f), (0.4f, 0.1f));
|
||||
using (world)
|
||||
{
|
||||
var (pa, pc) = (world.View.SensorWetVolume[s[0]], world.View.SensorWetVolume[s[1]]);
|
||||
Assert.True(pa > 0f && pc > 0f);
|
||||
var taken = new float[2];
|
||||
world.TakeWet(s, [pa / 2f, pc / 2f], taken);
|
||||
Assert.Equal(pa / 2f, taken[0], pa * 1e-5f);
|
||||
Assert.Equal(pc / 2f, taken[1], pc * 1e-5f);
|
||||
world.Step(Dt, Sub);
|
||||
Assert.Equal(pa / 2f, world.View.SensorWetVolume[s[0]], pa * 1e-5f);
|
||||
Assert.Equal(pc / 2f, world.View.SensorWetVolume[s[1]], pc * 1e-5f);
|
||||
}
|
||||
// overlapping: the same sphere twice: the second sees what the first left, asks for more than is there, and no patch goes below 0.
|
||||
var (world2, t) = TakeFloor((-0.2f, 0.15f), (-0.2f, 0.15f));
|
||||
using (world2)
|
||||
{
|
||||
var before = world2.View.WetPatchVolume.ToArray();
|
||||
var x = world2.View.WetX.ToArray();
|
||||
var pooled = world2.View.SensorWetVolume[t[0]];
|
||||
var taken = new float[2];
|
||||
var first = pooled / 3f;
|
||||
world2.TakeWet(t, [first, 10f], taken);
|
||||
Assert.Equal(first, taken[0], first * 1e-5f);
|
||||
Assert.Equal(pooled - first, taken[1], pooled * 1e-5f);
|
||||
var v = world2.View;
|
||||
for (var w = 0; w < v.WetCount; w++) Assert.True(v.WetPatchVolume[w] >= 0f && v.WetPatchVolume[w] <= before[w]);
|
||||
world2.Step(Dt, Sub);
|
||||
Assert.Equal(0f, world2.View.SensorWetVolume[t[0]]);
|
||||
Assert.Equal(0f, world2.View.SensorWetVolume[t[1]]);
|
||||
for (var w = 0; w < v.WetCount; w++) if (x[w] > 0f) Assert.Equal(before[w], world2.View.WetPatchVolume[w]); // C untouched
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_a_later_sensor_finds_its_patch_after_an_earlier_take_removed_one()
|
||||
{
|
||||
// A lies first in the body's index by centre x: removing it resets its centre to 0, which would put it between B and C and hide B from the second sensor's search.
|
||||
var (world, s) = TakeFloor((-0.3f, 0.05f), (-0.1f, 0.05f));
|
||||
using var _ = world;
|
||||
var pb = world.View.SensorWetVolume[s[1]];
|
||||
Assert.True(pb > 0f && world.View.SensorWetVolume[s[0]] > 0f);
|
||||
var taken = new float[2];
|
||||
world.TakeWet(s, [10f, 10f], taken);
|
||||
Assert.Equal(pb, taken[1]);
|
||||
Assert.Equal(1, Enumerable.Range(0, world.View.WetCount).Count(w => world.View.WetLive[w] != 0)); // only C is left
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1f / 3f)]
|
||||
[InlineData(1e-6f)]
|
||||
[InlineData(1e-9f)]
|
||||
public void TakeWet_taken_is_what_left_the_patches(float share)
|
||||
{
|
||||
// A sensor over A and B: taken is the patches' own loss (float rounding included), not the ask.
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f));
|
||||
using var _ = world;
|
||||
var pooled = world.View.SensorWetVolume[s[0]];
|
||||
var before = world.View.WetPatchVolume.ToArray();
|
||||
var taken = new float[1];
|
||||
world.TakeWet(s, [pooled * share], taken);
|
||||
var after = world.View.WetPatchVolume;
|
||||
double lost = 0;
|
||||
for (var w = 0; w < before.Length; w++) lost += (double)before[w] - after[w];
|
||||
Assert.Equal((float)lost, taken[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_a_kill_takes_the_whole_pool()
|
||||
{
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f));
|
||||
using var _ = world;
|
||||
var pooled = world.View.SensorWetVolume[s[0]];
|
||||
var taken = new float[1];
|
||||
world.TakeWet(s, [pooled * 2f], taken);
|
||||
Assert.Equal(pooled, taken[0], pooled * 1e-6f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_a_patch_an_earlier_sensor_killed_is_not_killed_again()
|
||||
{
|
||||
// the second sphere also holds A, which the first took to nothing: A's dead lane keeps its centre, and the walk must pass over it
|
||||
var (world, s) = TakeFloor((-0.3f, 0.05f), (-0.2f, 0.15f));
|
||||
using var _ = world;
|
||||
var gen = world.View.WetGeneration.ToArray();
|
||||
var live = world.View.WetLive.ToArray();
|
||||
var taken = new float[2];
|
||||
world.TakeWet(s, [10f, 10f], taken);
|
||||
Assert.True(taken[0] > 0f);
|
||||
Assert.True(taken[1] > 0f);
|
||||
var killed = 0;
|
||||
for (var w = 0; w < gen.Length; w++)
|
||||
{
|
||||
if (live[w] != 0 && world.View.WetLive[w] == 0)
|
||||
{
|
||||
killed++;
|
||||
Assert.Equal(gen[w] + 1, world.View.WetGeneration[w]);
|
||||
}
|
||||
else Assert.Equal(gen[w], world.View.WetGeneration[w]);
|
||||
}
|
||||
Assert.True(killed > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_rederives_the_wet_index_once()
|
||||
{
|
||||
// A command ends in one rederive_wet; a kill never repairs the index mid-call (pinned on the source, as Remove_wet_never_reaches_the_topology_derivation is).
|
||||
var source = NativeSource("ymir_particles.c").Replace("\r\n", "\n");
|
||||
var at = source.IndexOf("int32_t ymir_particles_take_wet(", StringComparison.Ordinal);
|
||||
Assert.True(at > 0);
|
||||
var body = source.Substring(at, source.IndexOf("ymir_particles_create_sensors(", at, StringComparison.Ordinal) - at);
|
||||
Assert.Equal(1, System.Text.RegularExpressions.Regex.Matches(body, @"rederive_wet\(").Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TakeWet_refusals_change_nothing()
|
||||
{
|
||||
var (world, s) = TakeFloor((-0.2f, 0.15f), (0.4f, 0.1f));
|
||||
using var _ = world;
|
||||
var wet = WetBytes(world.View);
|
||||
var good = world.View.SensorWetVolume[s[0]] * 0.5f;
|
||||
void Unchanged() => Assert.True(wet.AsSpan().SequenceEqual(WetBytes(world.View)), "a wet lane changed on a refusal");
|
||||
// the first sensor is valid and would take; each refusal is in the second place, so the first must not have run
|
||||
Assert.ThrowsAny<Exception>(() => world.TakeWet(s, [good, -1f])); Unchanged();
|
||||
Assert.ThrowsAny<Exception>(() => world.TakeWet(s, [good, float.NaN])); Unchanged();
|
||||
Assert.ThrowsAny<Exception>(() => world.TakeWet(s, [good, float.PositiveInfinity])); Unchanged();
|
||||
Assert.ThrowsAny<Exception>(() => world.TakeWet([s[0], s[0]], [good, good])); Unchanged();
|
||||
Assert.ThrowsAny<Exception>(() => world.TakeWet([s[0], s[1] with { Generation = s[1].Generation + 1 }], [good, good])); Unchanged();
|
||||
var gone = s[1];
|
||||
world.Remove(gone);
|
||||
Assert.ThrowsAny<Exception>(() => world.TakeWet([s[0], gone], [good, good])); Unchanged();
|
||||
Assert.Throws<ArgumentException>(() => world.TakeWet([new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Wet, 0, 0)], [good])); Unchanged();
|
||||
Assert.Throws<ArgumentException>(() => world.TakeWet([s[0]], [good, good])); Unchanged();
|
||||
Assert.Throws<ArgumentException>(() => world.TakeWet([s[0], s[0]], [good, good], new float[1])); Unchanged();
|
||||
}
|
||||
}
|
||||
308
tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs
Normal file
308
tests/Ymir.Box3D.Soa.Tests/Box3DSoaTerrainTests.cs
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
using System.Numerics;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
public sealed class Box3DSoaTerrainTests
|
||||
{
|
||||
private const float Dt = 1f / 60f;
|
||||
private const float G = 10f;
|
||||
|
||||
/// <summary>
|
||||
/// Smooth bowl heightfield: h(x, z) = 0.04 * (dx^2 + dz^2) where dx = x - cx, dz = z - cz.
|
||||
/// Grid vertex (gx, gz) sits in world space at origin + (gx * scaleX, h(gx, gz) * scaleY, gz * scaleZ).
|
||||
/// </summary>
|
||||
private static float[] BuildBowlHeights(int countX, int countZ, float scaleX, float scaleZ, out float minH, out float maxH)
|
||||
{
|
||||
var cx = 0.5f * (countX - 1) * scaleX;
|
||||
var cz = 0.5f * (countZ - 1) * scaleZ;
|
||||
var heights = new float[countX * countZ];
|
||||
minH = float.PositiveInfinity;
|
||||
maxH = float.NegativeInfinity;
|
||||
for (var gz = 0; gz < countZ; gz++)
|
||||
{
|
||||
for (var gx = 0; gx < countX; gx++)
|
||||
{
|
||||
var dx = gx * scaleX - cx;
|
||||
var dz = gz * scaleZ - cz;
|
||||
var h = 0.04f * (dx * dx + dz * dz);
|
||||
heights[gz * countX + gx] = h;
|
||||
if (h < minH) minH = h;
|
||||
if (h > maxH) maxH = h;
|
||||
}
|
||||
}
|
||||
return heights;
|
||||
}
|
||||
|
||||
private static (Vector3[] Vertices, int[] Indices) BuildBoxPrismMesh(float hx, float hy, float hz)
|
||||
{
|
||||
// CCW outward winding matching Box3D b3CreateBoxMesh.
|
||||
var vertices = new Vector3[]
|
||||
{
|
||||
new( hx, hy, hz), // 0: +x +y +z
|
||||
new(-hx, hy, hz), // 1: -x +y +z
|
||||
new(-hx, -hy, hz), // 2: -x -y +z
|
||||
new( hx, -hy, hz), // 3: +x -y +z
|
||||
new( hx, hy, -hz), // 4: +x +y -z
|
||||
new(-hx, hy, -hz), // 5: -x +y -z
|
||||
new(-hx, -hy, -hz), // 6: -x -y -z
|
||||
new( hx, -hy, -hz), // 7: +x -y -z
|
||||
};
|
||||
var indices = new[]
|
||||
{
|
||||
0, 1, 3, 1, 2, 3, // +Z front
|
||||
0, 4, 1, 1, 4, 5, // +Y top
|
||||
0, 3, 7, 4, 0, 7, // +X right
|
||||
4, 7, 5, 6, 5, 7, // -Z back
|
||||
1, 5, 2, 6, 2, 5, // -X left
|
||||
3, 2, 7, 6, 7, 2, // -Y bottom
|
||||
};
|
||||
return (vertices, indices);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dynamic_box_and_sphere_dropped_20m_onto_bowl_heightfield_land_and_rest_at_expected_elevation()
|
||||
{
|
||||
const int countX = 25;
|
||||
const int countZ = 25;
|
||||
const float scaleX = 1f;
|
||||
const float scaleZ = 1f;
|
||||
const float scaleY = 1f;
|
||||
var origin = (-12f, 2f, -12f); // bowl centre sits at world (0, 2, 0)
|
||||
var heights = BuildBowlHeights(countX, countZ, scaleX, scaleZ, out var minH, out var maxH);
|
||||
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G);
|
||||
var terrain = world.AddStaticHeightField(
|
||||
1001, origin, heights, countX, countZ, (scaleX, scaleY, scaleZ), minH, maxH, friction: 0.25f);
|
||||
const float sphereRadius = 0.5f;
|
||||
const float boxHalfY = 0.4f;
|
||||
// Sphere dropped off-centre at x = 4, z = 0 from y = 22 (20 m above the bowl base y = 2):
|
||||
// it lands on the slope and slides down into the bowl centre (x = 0, z = 0, terrain y = 2).
|
||||
var sphere = world.AddSphere(2001, (4f, 22f, 0f), sphereRadius, density: 1f, friction: 0.25f);
|
||||
// Box dropped straight onto the bowl centre at (0, 22, 0): rests flat at y = 2 + boxHalfY.
|
||||
var box = world.AddBox(2002, (0f, 22f, 0f), (0.5f, boxHalfY, 0.5f), density: 1f, friction: 0.8f);
|
||||
|
||||
var view = world.View;
|
||||
Assert.Equal((uint)Box3DSoaKind.StaticHeightField, view.Kind[terrain]);
|
||||
Assert.Equal(0f, view.Mass[terrain]);
|
||||
Assert.Equal(origin, (view.PositionX[terrain], view.PositionY[terrain], view.PositionZ[terrain]));
|
||||
|
||||
var minSphereY = float.PositiveInfinity;
|
||||
var minBoxY = float.PositiveInfinity;
|
||||
for (var i = 0; i < 600; i++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
if (view.PositionY[sphere] < minSphereY) minSphereY = view.PositionY[sphere];
|
||||
if (view.PositionY[box] < minBoxY) minBoxY = view.PositionY[box];
|
||||
}
|
||||
|
||||
// Zero tunneling: neither body ever fell below the bowl floor.
|
||||
Assert.True(minSphereY >= origin.Item2 + sphereRadius - 0.1f, $"sphere tunneled: minY={minSphereY}");
|
||||
Assert.True(minBoxY >= origin.Item2 + boxHalfY - 0.1f, $"box tunneled: minY={minBoxY}");
|
||||
|
||||
// Sphere slid down the slope toward the bowl centre and sits on the terrain surface.
|
||||
Assert.True(MathF.Abs(view.PositionX[sphere]) < 1.5f, $"sphere did not slide toward bowl centre: x={view.PositionX[sphere]}");
|
||||
var sphereTerrainY = origin.Item2 + 0.04f * (view.PositionX[sphere] * view.PositionX[sphere] + view.PositionZ[sphere] * view.PositionZ[sphere]);
|
||||
Assert.InRange(view.PositionY[sphere], sphereTerrainY + sphereRadius - 0.05f, sphereTerrainY + sphereRadius + 0.1f);
|
||||
|
||||
// Box rests on the bowl centre at y = 2 + boxHalfY (slightly lifted at corners by bowl curvature).
|
||||
Assert.InRange(view.PositionY[box], origin.Item2 + boxHalfY - 0.02f, origin.Item2 + boxHalfY + 0.08f);
|
||||
Assert.True(MathF.Abs(view.VelocityY[box]) < 0.05f);
|
||||
Assert.True(view.ContactCount[terrain] >= 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dynamic_box_collides_cleanly_with_static_mesh_roof_and_wall_without_penetrating()
|
||||
{
|
||||
var (vertices, indices) = BuildBoxPrismMesh(hx: 2f, hy: 2f, hz: 2f);
|
||||
var buildingOrigin = (10f, 2f, 0f); // occupies x in [8, 12], y in [0, 4], z in [-2, 2]
|
||||
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (40f, 0.5f, 40f)); // floor top y = 0
|
||||
var building = world.AddStaticMesh(1002, buildingOrigin, vertices, indices, friction: 0.6f);
|
||||
|
||||
// Roof drop: box dropped onto the mesh roof (y = 4) from y = 10.
|
||||
var roofBox = world.AddBox(2001, (10f, 10f, 0f), (0.5f, 0.5f, 0.5f), density: 1f);
|
||||
// Wall drive: box on the floor at x = 4 pushed in +X toward the building's -X wall at x = 8.
|
||||
var wallBox = world.AddBox(2002, (4f, 0.5f, 0f), (0.5f, 0.5f, 0.5f), density: 1f, friction: 0.1f);
|
||||
|
||||
var view = world.View;
|
||||
Assert.Equal((uint)Box3DSoaKind.StaticMesh, view.Kind[building]);
|
||||
Assert.Equal(0f, view.Mass[building]);
|
||||
|
||||
for (var i = 0; i < 240; i++)
|
||||
{
|
||||
if (i < 120)
|
||||
{
|
||||
view.ForceX[wallBox] = 80f;
|
||||
}
|
||||
world.Step(Dt);
|
||||
// Wall box must never penetrate past the building's -X wall (x = 8 - 0.5 = 7.5).
|
||||
Assert.True(view.PositionX[wallBox] <= 7.5f + 0.03f, $"wall penetration at step {i}: x={view.PositionX[wallBox]}");
|
||||
}
|
||||
|
||||
// Roof box rests cleanly on top of the mesh roof (y = 4 + 0.5 = 4.5).
|
||||
Assert.InRange(view.PositionY[roofBox], 4.5f - 0.03f, 4.5f + 0.03f);
|
||||
Assert.True(MathF.Abs(view.VelocityY[roofBox]) < 0.05f);
|
||||
// Wall box stopped flush against the -X wall.
|
||||
Assert.InRange(view.PositionX[wallBox], 7.4f, 7.53f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CastRayClosest_hits_both_static_heightfield_and_static_mesh_with_accurate_point_normal_and_identity()
|
||||
{
|
||||
// Sloped plane heightfield: h(x, z) = 0.5 * x, so surface normal is (-0.5, 1, 0) / sqrt(1.25).
|
||||
const int countX = 5;
|
||||
const int countZ = 5;
|
||||
var heights = new float[countX * countZ];
|
||||
for (var gz = 0; gz < countZ; gz++)
|
||||
{
|
||||
for (var gx = 0; gx < countX; gx++)
|
||||
{
|
||||
heights[gz * countX + gx] = 0.5f * gx;
|
||||
}
|
||||
}
|
||||
var hfOrigin = (-2f, 1f, -2f);
|
||||
const ulong hfStableId = 7001ul;
|
||||
|
||||
var (vertices, indices) = BuildBoxPrismMesh(hx: 1.5f, hy: 2f, hz: 1.5f);
|
||||
var meshOrigin = (20f, 2f, 0f); // -X face at x = 18.5, normal (-1, 0, 0)
|
||||
const ulong meshStableId = 7002ul;
|
||||
|
||||
using var world = new Box3DSoaWorld(capacity: 8, gravityY: -G);
|
||||
var hf = world.AddStaticHeightField(hfStableId, hfOrigin, heights, countX, countZ, (1f, 1f, 1f), 0f, 2f);
|
||||
var mesh = world.AddStaticMesh(meshStableId, meshOrigin, vertices, indices);
|
||||
|
||||
// Ray straight down at world (0.25, 10, 0.25) -> local (2.25, 9, 2.25) -> terrain height = 1 + 0.5 * 2.25 = 2.125.
|
||||
var hfHit = world.CastRayClosest((0.25f, 10f, 0.25f), (0f, -20f, 0f));
|
||||
Assert.True(hfHit.Hit);
|
||||
Assert.Equal(hf.Lane, hfHit.Lane);
|
||||
Assert.Equal(hfStableId, hfHit.StableId);
|
||||
Assert.InRange(hfHit.Point.X, 0.249f, 0.251f);
|
||||
Assert.InRange(hfHit.Point.Y, 2.125f - 0.002f, 2.125f + 0.002f);
|
||||
Assert.InRange(hfHit.Point.Z, 0.249f, 0.251f);
|
||||
var invLen = 1f / MathF.Sqrt(1.25f);
|
||||
Assert.InRange(hfHit.Normal.X, -0.5f * invLen - 0.005f, -0.5f * invLen + 0.005f);
|
||||
Assert.InRange(hfHit.Normal.Y, 1.0f * invLen - 0.005f, 1.0f * invLen + 0.005f);
|
||||
Assert.InRange(hfHit.Normal.Z, -0.005f, 0.005f);
|
||||
|
||||
// Ray in +X toward the mesh's -X face at x = 18.5.
|
||||
var meshHit = world.CastRayClosest((15f, 2f, 0.25f), (10f, 0f, 0f));
|
||||
Assert.True(meshHit.Hit);
|
||||
Assert.Equal(mesh.Lane, meshHit.Lane);
|
||||
Assert.Equal(meshStableId, meshHit.StableId);
|
||||
Assert.InRange(meshHit.Point.X, 18.499f, 18.501f);
|
||||
Assert.InRange(meshHit.Point.Y, 1.999f, 2.001f);
|
||||
Assert.InRange(meshHit.Normal.X, -1.001f, -0.999f);
|
||||
Assert.InRange(meshHit.Normal.Y, -0.001f, 0.001f);
|
||||
Assert.InRange(meshHit.Normal.Z, -0.001f, 0.001f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repeated_add_step_remove_and_dispose_cycles_leave_no_crashes_or_stale_handles()
|
||||
{
|
||||
var flatHeights = new float[9];
|
||||
var (vertices, indices) = BuildBoxPrismMesh(hx: 1f, hy: 1f, hz: 1f);
|
||||
|
||||
for (var worldCycle = 0; worldCycle < 10; worldCycle++)
|
||||
{
|
||||
using var world = new Box3DSoaWorld(
|
||||
capacity: 6, gravityY: -G,
|
||||
particles: new Box3DSoaParticleCapacities(4, 0, 0, 0, 0, 1));
|
||||
// Live particle ensures ymir_soa_gather_proxies walks static heightfield & mesh lanes safely.
|
||||
world.CreateParticles([new((10f, 5f, 0f), 0.1f, 0.05f)]);
|
||||
|
||||
for (var cycle = 0; cycle < 20; cycle++)
|
||||
{
|
||||
var hfId = (ulong)(100 + cycle * 2);
|
||||
var meshId = (ulong)(101 + cycle * 2);
|
||||
var hf = world.AddStaticHeightField(hfId, (-1f, 0f, -1f), flatHeights, 3, 3, (1f, 1f, 1f), -1f, 1f);
|
||||
var mesh = world.AddStaticMesh(meshId, (5f, 1f, 0f), vertices, indices);
|
||||
var ball = world.AddSphere((ulong)(1000 + cycle), (0f, 0.4f, 0f), 0.5f, density: 1f);
|
||||
|
||||
world.Step(Dt);
|
||||
Assert.True(world.View.ContactCount[hf] >= 1);
|
||||
|
||||
world.RemoveBody(hf);
|
||||
world.RemoveBody(mesh);
|
||||
world.RemoveBody(ball);
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(hf));
|
||||
Assert.Throws<InvalidOperationException>(() => world.RemoveBody(mesh));
|
||||
|
||||
world.Step(Dt);
|
||||
Assert.Equal(3, world.Facts.BodiesRemoved.Length);
|
||||
Assert.Contains(world.Facts.End.ToArray(), e => e.StableIdA == hfId || e.StableIdB == hfId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public unsafe void Invalid_heightfield_and_mesh_inputs_are_refused_cleanly()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 2);
|
||||
var heights = new float[4];
|
||||
var (vertices, indices) = BuildBoxPrismMesh(1f, 1f, 1f);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 1, 4, (1f, 1f, 1f), -1f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (0f, 1f, 1f), -1f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1f), 2f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), [0f, float.NaN, 0f, 0f], 2, 2, (1f, 1f, 1f), -1f, 1f));
|
||||
Assert.Throws<ArgumentException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), new float[3], 2, 2, (1f, 1f, 1f), -1f, 1f));
|
||||
// Height range and scaled-bound float overflow / >= 1e5f limits.
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1f), -2e38f, 2e38f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1e5f, 1f, 1f), -1f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1e5f), -1f, 1f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1e4f, 1f), -10f, 10f));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticHeightField(1, (0f, 0f, 0f), heights, 2, 2, (1f, 1e20f, 1f), 1e20f, 1e20f));
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), vertices.AsSpan(0, 2), [0, 1, 0]));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), vertices, [0, 1, 99]));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, new(float.NaN, 0f, 0f), Vector3.UnitZ], [0, 1, 2]));
|
||||
Assert.Throws<ArgumentException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), vertices, [0, 1]));
|
||||
// Degenerate meshes (collinear or repeated-index triangles) and out-of-bounds vertex coordinates must be refused before b3CreateMesh.
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, Vector3.UnitX, new(2f, 0f, 0f)], [0, 1, 2]));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, Vector3.UnitX, Vector3.UnitZ], [0, 1, 0, 1, 2, 2]));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, new(1.5e5f, 0f, 0f), Vector3.UnitZ], [0, 1, 2]));
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(2, (0f, 0f, 0f), [Vector3.Zero, new(50000f, 0f, 0f), Vector3.UnitZ], [0, 1, 2]));
|
||||
|
||||
// Native cap refusals (YMIR_SOA_INVALID_ARGUMENT == 1) without allocating 200+ MB in tests.
|
||||
var nativeHandle = (nint)typeof(Box3DSoaWorld)
|
||||
.GetField("_handle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
|
||||
.GetValue(world)!;
|
||||
fixed (float* hPtr = heights)
|
||||
fixed (Vector3* vPtr = vertices)
|
||||
fixed (int* iPtr = indices)
|
||||
{
|
||||
Assert.Equal(1, Box3DSoaNative.ymir_box3d_soa_add_static_heightfield(
|
||||
nativeHandle, 3, 0f, 0f, 0f, hPtr, 8192, 8193, 1f, 1f, 1f, -1f, 1f, 0.6f, 0f, 0, out _));
|
||||
Assert.Equal(1, Box3DSoaNative.ymir_box3d_soa_add_static_mesh(
|
||||
nativeHandle, 4, 0f, 0f, 0f, (float*)vPtr, vertices.Length, iPtr, 16 * 1024 * 1024 + 1, 0.6f, 0f, 0, out _));
|
||||
Assert.Equal(1, Box3DSoaNative.ymir_box3d_soa_add_static_mesh(
|
||||
nativeHandle, 5, 0f, 0f, 0f, (float*)vPtr, 32 * 1024 * 1024 + 1, iPtr, 1, 0.6f, 0f, 0, out _));
|
||||
}
|
||||
|
||||
// Valid additions still fit because refusals consumed no slots.
|
||||
world.AddStaticHeightField(10, (0f, 0f, 0f), heights, 2, 2, (1f, 1f, 1f), -1f, 1f);
|
||||
world.AddStaticMesh(11, (10f, 0f, 0f), vertices, indices);
|
||||
Assert.Throws<InvalidOperationException>(() =>
|
||||
world.AddStaticMesh(12, (20f, 0f, 0f), vertices, indices)); // full
|
||||
}
|
||||
}
|
||||
133
tests/Ymir.Box3D.Soa.Tests/Box3DSoaTouchingPairsTests.cs
Normal file
133
tests/Ymir.Box3D.Soa.Tests/Box3DSoaTouchingPairsTests.cs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The touching-pair span against an independent oracle: the set built from the Begin and End facts.
|
||||
/// The ground is added first in one run and last in the other, so a static partner sits below and above the dynamic lanes.
|
||||
/// </summary>
|
||||
public sealed class Box3DSoaTouchingPairsTests
|
||||
{
|
||||
private const float Dt = 1f / 60f;
|
||||
|
||||
private static (int, int) Key(int a, int b) => (Math.Min(a, b), Math.Max(a, b));
|
||||
|
||||
private static void Track(Box3DSoaWorld world, HashSet<(int, int)> oracle)
|
||||
{
|
||||
foreach (var t in world.Facts.End) oracle.Remove(Key(t.LaneA, t.LaneB));
|
||||
foreach (var t in world.Facts.Begin) oracle.Add(Key(t.LaneA, t.LaneB));
|
||||
}
|
||||
|
||||
/// <summary>Structural checks on the span; returns the pair set, or fails the test with the step named.</summary>
|
||||
private static HashSet<(int, int)> ReadSpan(Box3DSoaWorld world, HashSet<int> dead, int step, bool checkCounts)
|
||||
{
|
||||
var facts = world.Facts;
|
||||
var view = world.View;
|
||||
var seen = new HashSet<(int, int)>();
|
||||
var count = new int[view.ContactCount.Length];
|
||||
var last = -1;
|
||||
foreach (var t in facts.Touching)
|
||||
{
|
||||
Assert.True(t.LaneA < t.LaneB, $"pair {t.LaneA},{t.LaneB} unordered at step {step}");
|
||||
Assert.True(seen.Add((t.LaneA, t.LaneB)), $"pair {t.LaneA},{t.LaneB} repeated at step {step}");
|
||||
Assert.True(t.LaneA >= last, $"lane_a not monotone at step {step}");
|
||||
last = t.LaneA;
|
||||
Assert.False(dead.Contains(t.LaneA) || dead.Contains(t.LaneB), $"pair {t.LaneA},{t.LaneB} names a removed lane at step {step}");
|
||||
Assert.True(view.StableId[t.LaneA] == t.StableIdA && view.StableId[t.LaneB] == t.StableIdB, $"stable ids of pair {t.LaneA},{t.LaneB} do not match their lanes at step {step}");
|
||||
count[t.LaneA]++;
|
||||
count[t.LaneB]++;
|
||||
}
|
||||
if (checkCounts)
|
||||
{
|
||||
for (var lane = 0; lane < count.Length; lane++)
|
||||
{
|
||||
Assert.True(view.ContactCount[lane] == count[lane], $"lane {lane}: ContactCount {view.ContactCount[lane]} but {count[lane]} pairs at step {step}");
|
||||
}
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
private static Box3DSoaWorld Build(bool groundLast, out List<Box3DSoaBodyHandle> bodies, int capacity = 40, int? factCapacity = null)
|
||||
{
|
||||
var world = new Box3DSoaWorld(capacity: capacity, gravityY: -10f, factCapacity: factCapacity);
|
||||
bodies = new List<Box3DSoaBodyHandle>();
|
||||
if (!groundLast) world.AddStaticBox(1, (0f, -0.5f, 0f), (50f, 0.5f, 50f), materialId: 3);
|
||||
ulong id = 100;
|
||||
for (var x = 0; x < 4; x++)
|
||||
{
|
||||
for (var z = 0; z < 3; z++)
|
||||
{
|
||||
bodies.Add(world.AddSphere(id++, (x * 0.9f - 1.4f, 2f + 0.6f * (x + z), z * 0.9f - 0.9f), 0.5f, density: 1f,
|
||||
velocity: (0.2f * z, 0f, -0.1f * x), materialId: (ulong)(x + 10)));
|
||||
}
|
||||
}
|
||||
bodies.Add(world.AddBox(300, (4f, 0.3f, 0f), (0.3f, 0.3f, 0.3f), 1f));
|
||||
bodies.Add(world.AddBox(301, (4f, 0.9f, 0f), (0.3f, 0.3f, 0.3f), 1f));
|
||||
if (groundLast) world.AddStaticBox(1, (0f, -0.5f, 0f), (50f, 0.5f, 50f), materialId: 3);
|
||||
return world;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void The_touching_span_equals_the_begin_end_oracle_whether_the_ground_is_added_first_or_last(bool groundLast)
|
||||
{
|
||||
using var world = Build(groundLast, out _);
|
||||
var oracle = new HashSet<(int, int)>();
|
||||
var dead = new HashSet<int>();
|
||||
var sawGround = false;
|
||||
for (var step = 0; step < 1500; step++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
Track(world, oracle);
|
||||
var seen = ReadSpan(world, dead, step, checkCounts: world.Facts.Dropped.Touching == 0);
|
||||
Assert.True(seen.SetEquals(oracle), $"span differs from the Begin/End oracle at step {step}: touching {seen.Count}, oracle {oracle.Count}");
|
||||
foreach (var t in world.Facts.Touching) sawGround |= t.StableIdA == 1 || t.StableIdB == 1;
|
||||
}
|
||||
Assert.True(sawGround, "bodies rested on the static ground, so the static partner was exercised");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removed_lanes_leave_the_span_and_a_reused_lane_pairs_afresh()
|
||||
{
|
||||
using var world = Build(false, out var bodies);
|
||||
var oracle = new HashSet<(int, int)>();
|
||||
var dead = new HashSet<int>();
|
||||
var reusedLane = -1;
|
||||
var sawNewPair = false;
|
||||
for (var step = 0; step < 900; step++)
|
||||
{
|
||||
if (step == 200) { var h = bodies[5]; world.RemoveBody(h); dead.Add(h.Lane); }
|
||||
if (step == 205) { var h = bodies[2]; world.RemoveBody(h); dead.Add(h.Lane); }
|
||||
if (step == 300)
|
||||
{
|
||||
reusedLane = world.AddSphere(900, (0.1f, 3f, 0.1f), 0.5f, density: 1f).Lane;
|
||||
dead.Remove(reusedLane);
|
||||
}
|
||||
world.Step(Dt);
|
||||
Track(world, oracle);
|
||||
if (step >= 300) foreach (var t in world.Facts.Touching) sawNewPair |= t.LaneA == reusedLane || t.LaneB == reusedLane;
|
||||
var seen = ReadSpan(world, dead, step, checkCounts: world.Facts.Dropped.Touching == 0);
|
||||
Assert.True(seen.SetEquals(oracle), $"span differs from the Begin/End oracle at step {step}");
|
||||
}
|
||||
Assert.True(sawNewPair, "the reused lane touched something");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_overfull_span_keeps_what_fits_and_counts_the_rest()
|
||||
{
|
||||
using var world = Build(false, out _, factCapacity: 5);
|
||||
var oracle = new HashSet<(int, int)>();
|
||||
var sawDropped = false;
|
||||
for (var step = 0; step < 600; step++)
|
||||
{
|
||||
world.Step(Dt);
|
||||
Track(world, oracle);
|
||||
var facts = world.Facts;
|
||||
Assert.True(facts.Touching.Length <= 5, $"span holds {facts.Touching.Length} pairs past its capacity at step {step}");
|
||||
Assert.True(facts.Touching.Length + facts.Dropped.Touching == oracle.Count, $"kept {facts.Touching.Length} + dropped {facts.Dropped.Touching} != oracle {oracle.Count} at step {step}");
|
||||
sawDropped |= facts.Dropped.Touching > 0;
|
||||
}
|
||||
Assert.True(sawDropped, "the span overflowed, so the drop count was exercised");
|
||||
}
|
||||
}
|
||||
273
tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetFrictionTests.cs
Normal file
273
tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetFrictionTests.cs
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Settled liquid lowers friction where it lands: docs/soa-world.md, Wet friction. Body-body contact through the world's friction hook, particle-body through wet_mu.</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
private const float BoxMass = 5f;
|
||||
private const float PushForce = 20f; // below mu m g = 29.4 N dry, above the wet 0.1 m g = 4.9 N
|
||||
private const float WetMu = 0.1f;
|
||||
private const float DropRadius = 0.03f; // a patch of radius sqrt((2 r)^3 / (pi film)) = 0.262 m
|
||||
private const int PushTicks = 40;
|
||||
private const double WetAcceleration = (PushForce - WetMu * BoxMass * 9.81) / BoxMass;
|
||||
|
||||
/// <summary>A floor of friction 0.6 (body lane 0, top at y 0) with one drop of liquid (wet friction 0.1) settled at <paramref name="patchAt"/> (or destroyed when there is no patch), then 0.2 m boxes of 5 kg on it.</summary>
|
||||
private static (Box3DSoaWorld World, int[] Boxes) WetBoxes(Pos[] boxes, bool patch, Pos patchAt)
|
||||
{
|
||||
var world = FluidWorld(8, wets: 4, gravityY: -9.81f);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 2f), friction: 0.6f);
|
||||
world.SetMaterial(0, 0.6f);
|
||||
world.SetMaterial(1, 0.6f, wetFriction: WetMu);
|
||||
var scale = DropRadius / R;
|
||||
world.CreateParticles([Fluid((patchAt.X, DropRadius, patchAt.Z), FluidMass * scale * scale * scale, DropRadius, material: 1u)]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(Dt, Sub);
|
||||
if (patch) world.Settle([Handle(world, 0)]); else world.DestroyParticles([Handle(world, 0)]);
|
||||
var lanes = boxes.Select((at, i) => (int)world.AddBox(10ul + (ulong)i, (at.X, 0.1f, at.Z), (0.1f, 0.1f, 0.1f), BoxMass / 0.008f, friction: 0.6f)).ToArray();
|
||||
return (world, lanes);
|
||||
}
|
||||
|
||||
/// <summary>Pushes every box along x with a constant force for <paramref name="ticks"/> ticks.</summary>
|
||||
private static void Push(Box3DSoaWorld world, int[] boxes, int ticks)
|
||||
{
|
||||
var view = world.View;
|
||||
for (var tick = 0; tick < ticks; tick++)
|
||||
{
|
||||
foreach (var b in boxes) view.ForceX[b] = PushForce;
|
||||
world.Step(Dt, Sub);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The distance a box moves over <see cref="PushTicks"/> pushed ticks from rest.</summary>
|
||||
private static double Moved(Box3DSoaWorld world, int[] boxes, int box)
|
||||
{
|
||||
var x0 = world.View.PositionX[boxes[box]];
|
||||
Push(world, boxes, PushTicks);
|
||||
return world.View.PositionX[boxes[box]] - x0;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Box_slides_on_a_wet_floor()
|
||||
{
|
||||
double dry, wet;
|
||||
{
|
||||
var (world, boxes) = WetBoxes([(0f, 0f, 0f)], patch: false, (0f, 0f, 0f));
|
||||
using (world) dry = Math.Abs(Moved(world, boxes, 0));
|
||||
}
|
||||
{
|
||||
var (world, boxes) = WetBoxes([(0f, 0f, 0f)], patch: true, (0f, 0f, 0f));
|
||||
using (world) wet = 2.0 * Moved(world, boxes, 0) / ((double)PushTicks * Dt * PushTicks * Dt);
|
||||
}
|
||||
Readings.Add($"WETFRICTION box: dry moved {dry:E3} m; wet acceleration {wet:F4} against {WetAcceleration:F4}, relative error {Math.Abs(wet / WetAcceleration - 1.0):E3}");
|
||||
Assert.True(dry < DryBound, $"the dry box moved {dry} m");
|
||||
Assert.True(Math.Abs(wet / WetAcceleration - 1.0) <= SlideBound, $"wet acceleration {wet} against {WetAcceleration}");
|
||||
}
|
||||
|
||||
// Bounds (lodur:ruling:deterministic-bound-margin, bound = sqrt(shipped worst x least claimed mutant)). Wet acceleration, relative error against (F - mu m g) / m: shipped
|
||||
// 6.284e-3; M1 (the patch test in the world frame) and M2 (the hook takes max) leave the box held, 0.9998: bound sqrt(6.284e-3 x 0.9998) = 0.079, separation 12.6. Dry box off
|
||||
// the patch, metres moved in 40 ticks: shipped worst 3.123e-5; M4 (no disc: the patch is the whole floor) 0.1688, B slides with A: bound sqrt(3.123e-5 x 0.1688) = 2.3e-3,
|
||||
// separation 74. The box under the patch moves 0.1688 m shipped; M1 and M2 read 0.0000, counted one unit (1e-6 m) by lodur:ruling:deterministic-bound-zero-reading:
|
||||
// bound sqrt(0.1688 x 1e-6) = 4.1e-4 m, separation 410.
|
||||
// The late-settled patch under a resting box reads 6.276e-3 shipped (rest 100 ticks); M5 (the fork does not run the hook on recycled contacts) holds the box, 1.0: the same 0.079.
|
||||
// The dry readings across the tests: shipped worst 3.839e-5 m (the patch removed from under a resting box); least claimed mutant M5 (no hook on recycled contacts) 0.1128 m there: bound sqrt(3.839e-5 x 0.1128) = 2.1e-3, tightened from 2.3e-3, separation 54.
|
||||
private const double SlideBound = 0.079;
|
||||
private const double DryBound = 2.1e-3;
|
||||
private const double MovedBound = 4.1e-4;
|
||||
|
||||
[Fact]
|
||||
public void Dry_box_beside_a_wet_patch_holds()
|
||||
{
|
||||
// The patch is under box A; B, 1 m away on the same floor under the same push, stays: friction is lowered where the liquid is, not on the floor.
|
||||
var (world, boxes) = WetBoxes([(0f, 0f, 0f), (1f, 0f, 0f)], patch: true, (0f, 0f, 0f));
|
||||
using (world)
|
||||
{
|
||||
var (a0, b0) = (world.View.PositionX[boxes[0]], world.View.PositionX[boxes[1]]);
|
||||
Push(world, boxes, PushTicks);
|
||||
var (a, b) = (world.View.PositionX[boxes[0]] - a0, Math.Abs(world.View.PositionX[boxes[1]] - b0));
|
||||
Readings.Add($"WETFRICTION beside: A moved {a:F4} m, B moved {b:E3} m");
|
||||
Assert.True(a > MovedBound, $"A moved {a} m");
|
||||
Assert.True(b < DryBound, $"B, off the patch, moved {b} m");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Patch_elsewhere_changes_nothing()
|
||||
{
|
||||
// A patch 2 m from the boxes against no patch (the drop destroyed instead of settled): the bodies' bytes are equal.
|
||||
static byte[] Bytes((Box3DSoaWorld World, int[] Boxes) w)
|
||||
{
|
||||
using var world = w.World;
|
||||
Push(world, w.Boxes, 60);
|
||||
var v = world.View;
|
||||
var o = new MemoryStream();
|
||||
foreach (var b in w.Boxes)
|
||||
foreach (var f in new[] { v.PositionX[b], v.PositionY[b], v.PositionZ[b], v.VelocityX[b], v.VelocityY[b], v.VelocityZ[b] }) o.Write(BitConverter.GetBytes(f));
|
||||
return o.ToArray();
|
||||
}
|
||||
var with = Bytes(WetBoxes([(0f, 0f, 0f), (1f, 0f, 0f)], patch: true, (-2f, 0f, 0f)));
|
||||
var without = Bytes(WetBoxes([(0f, 0f, 0f), (1f, 0f, 0f)], patch: false, (-2f, 0f, 0f)));
|
||||
Assert.True(with.AsSpan().SequenceEqual(without), "a patch away from every contact moved a body");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fluid_keeps_its_own_friction_on_a_wet_floor()
|
||||
{
|
||||
// A fluid particle sliding over a patch moves as it does over a bare floor (idea ymir-fluid-reval.rejected-fluid-reads-patches).
|
||||
static float Slide(bool patch)
|
||||
{
|
||||
var (world, _) = WetBoxes([], patch, (0f, 0f, 0f));
|
||||
using (world)
|
||||
{
|
||||
world.CreateParticles([Fluid((-0.1f, R, 0f), velocity: (1.5f, 0f, 0f))]);
|
||||
for (var tick = 0; tick < 60; tick++) world.Step(Dt, Sub);
|
||||
return world.View.ParticleX[1];
|
||||
}
|
||||
}
|
||||
var (with, without) = (Slide(true), Slide(false));
|
||||
Readings.Add($"WETFRICTION fluid slide: patch {with:F6}, none {without:F6}");
|
||||
Assert.Equal(BitConverter.SingleToInt32Bits(without), BitConverter.SingleToInt32Bits(with));
|
||||
}
|
||||
|
||||
// The wet rope's slide in 2 s, metres: shipped 0.535; M1 (the patch test in the world frame) reads 0.000, counted one unit (1e-6 m) by lodur:ruling:deterministic-bound-zero-reading:
|
||||
// bound sqrt(0.535 x 1e-6) = 7.3e-4, separation 730. The dry rope's 0.01 holds as in Material_friction_holds_on_a_slope (shipped 0).
|
||||
private const float SlopeBound = 7.3e-4f;
|
||||
|
||||
[Fact]
|
||||
public void Rope_slides_on_a_wet_slope()
|
||||
{
|
||||
// Material_friction_holds_on_a_slope's scene (Box3DSoaCouplingTests): the rope holds dry at 0.6 and slides with a patch under it.
|
||||
static float Slid(bool patch)
|
||||
{
|
||||
var tilt = 20f * MathF.PI / 180f;
|
||||
using var world = new Box3DSoaWorld(8, gravityX: 10f * MathF.Sin(tilt), gravityY: -10f, jointCapacity: 2,
|
||||
particles: new Box3DSoaParticleCapacities(256, 600, 600, 8, 600, 2, 16, 4));
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.6f);
|
||||
world.SetMaterial(0, 0.6f);
|
||||
world.SetMaterial(1, 0.6f, wetFriction: 0.05f);
|
||||
var rope = Graph.Rope(world, Graph.Line((0f, Box3DSoaParticleTests.ParticleRadius, 0f), (0f, 0f, Box3DSoaParticleTests.Spacing), 12),
|
||||
Box3DSoaParticleTests.ParticleMass, Box3DSoaParticleTests.ParticleRadius);
|
||||
if (patch)
|
||||
{
|
||||
var scale = 0.05f / R;
|
||||
world.CreateParticles([Fluid((-0.3f, 0.05f, 0.15f), FluidMass * scale * scale * scale, 0.05f, material: 1u)]);
|
||||
world.Step(Dt, Sub);
|
||||
world.Settle([Handle(world, 12)]);
|
||||
}
|
||||
for (var tick = 0; tick < 2 * 120; tick++) world.Step(Dt, Sub);
|
||||
return MathF.Abs(world.View.ParticleX[rope.Particles[6]]);
|
||||
}
|
||||
var (dry, wet) = (Slid(false), Slid(true));
|
||||
Readings.Add($"WETFRICTION slope: dry slid {dry:E3} m, wet slid {wet:F3} m in 2 s");
|
||||
Assert.True(dry < 0.01f, $"dry slid {dry} m");
|
||||
Assert.True(wet > SlopeBound, $"wet slid only {wet} m");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_reused_lane_is_not_slippery()
|
||||
{
|
||||
// Liquid settled on a solid particle makes that particle slip (particle_wet_mu); when the solid is destroyed the lane goes dry, and a solid created on the reused lane slides
|
||||
// as one that never met the liquid (the control destroys the drop instead of settling it).
|
||||
static (float X, int Lane, int Reused) Slide(bool patch)
|
||||
{
|
||||
var world = FluidWorld(16, wets: 4, gravityY: -9.81f);
|
||||
using (world)
|
||||
{
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 2f), friction: 0.6f);
|
||||
world.SetMaterial(0, 0.6f);
|
||||
world.SetMaterial(1, 0.6f, wetFriction: 0.05f);
|
||||
var solid = Box3DSoaPhase.Of(1);
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, R, 0f), 0.02f, R, solid, 0u, null, default)]);
|
||||
world.CreateParticles([Fluid((0f, 3f * R, 0f), material: 1u)]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(Dt, Sub);
|
||||
var under = world.View.SupportParticle[1];
|
||||
if (patch) { Assert.Equal(0, under); world.Settle([Handle(world, 1)]); } else world.DestroyParticles([Handle(world, 1)]);
|
||||
world.DestroyParticles([Handle(world, 0)]);
|
||||
world.Step(Dt, Sub);
|
||||
var made = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0f, R, 0f), 0.02f, R, solid, 0u, null, (1.5f, 0f, 0f))], made);
|
||||
for (var tick = 0; tick < 60; tick++) world.Step(Dt, Sub);
|
||||
return (world.View.ParticleX[made[0].Lane], made[0].Lane, 0);
|
||||
}
|
||||
}
|
||||
var (with, without) = (Slide(true), Slide(false));
|
||||
Readings.Add($"WETFRICTION reused lane: lane {with.Lane}, x {with.X:F6} after a settled patch, {without.X:F6} without");
|
||||
Assert.Equal(0, with.Lane);
|
||||
Assert.Equal(BitConverter.SingleToInt32Bits(without.X), BitConverter.SingleToInt32Bits(with.X));
|
||||
}
|
||||
|
||||
/// <summary>A floor, a drop of liquid 0.4 m off settled into a patch of radius 0.56 m (wet friction 0.1) that holds the point 0, a box of 5 kg at 0 that rests <paramref name="rest"/> ticks, then <paramref name="between"/> and <paramref name="settleLate"/>.</summary>
|
||||
private static double RestedThenPushed(int rest, bool settleLate, bool removeAfter)
|
||||
{
|
||||
var world = FluidWorld(8, wets: 4, gravityY: -9.81f);
|
||||
using (world)
|
||||
{
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 2f), friction: 0.6f);
|
||||
world.SetMaterial(0, 0.6f);
|
||||
world.SetMaterial(1, 0.6f, wetFriction: WetMu);
|
||||
var scale = 0.05f / R;
|
||||
world.CreateParticles([Fluid((0.4f, 0.05f, 0f), FluidMass * scale * scale * scale, 0.05f, material: 1u)]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(Dt, Sub);
|
||||
var patch = new Box3DSoaConstraintHandle[1];
|
||||
if (!settleLate) world.Settle([Handle(world, 0)], patch);
|
||||
var box = world.AddBox(10ul, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), BoxMass / 0.008f, friction: 0.6f);
|
||||
for (var tick = 0; tick < rest; tick++) world.Step(Dt, Sub);
|
||||
if (settleLate) world.Settle([Handle(world, 0)], patch);
|
||||
if (removeAfter) world.Remove(patch[0]);
|
||||
for (var tick = 0; tick < 5; tick++) world.Step(Dt, Sub);
|
||||
return Moved(world, [box], 0);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(5)]
|
||||
[InlineData(100)]
|
||||
public void Liquid_settled_under_a_resting_box_makes_it_slide(int rest)
|
||||
{
|
||||
// The box rests dry (its contact recycled, held by friction), then a patch is settled under it: the hook runs on the recycled contact, so friction drops.
|
||||
var moved = RestedThenPushed(rest, settleLate: true, removeAfter: false);
|
||||
var acceleration = 2.0 * moved / ((double)PushTicks * Dt * PushTicks * Dt);
|
||||
Readings.Add($"WETFRICTION late patch after {rest} ticks: acceleration {acceleration:F4} against {WetAcceleration:F4}, relative error {Math.Abs(acceleration / WetAcceleration - 1.0):E3}");
|
||||
Assert.True(Math.Abs(acceleration / WetAcceleration - 1.0) <= SlideBound, $"acceleration {acceleration} against {WetAcceleration}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Liquid_removed_from_under_a_resting_box_restores_friction()
|
||||
{
|
||||
// The box rests on the patch (friction lowered), the patch is removed: the recycled contact takes the floor's friction back and holds the push.
|
||||
var moved = Math.Abs(RestedThenPushed(20, settleLate: false, removeAfter: true));
|
||||
Readings.Add($"WETFRICTION patch removed from under a resting box: moved {moved:E3} m");
|
||||
Assert.True(moved < DryBound, $"the box moved {moved} m");
|
||||
}
|
||||
|
||||
// Overlapping patches of two liquids: the lowest lane decides, wherever its centre sorts. Wet acceleration, relative error against (F - 0.3 m g) / m: shipped 2.262e-2; M7 (the
|
||||
// first holder in x order wins: the 0.05 patch, acceleration 3.51) 2.32: bound sqrt(2.262e-2 x 2.32) = 0.229, separation 10.1.
|
||||
private const double LowestLaneBound = 0.229;
|
||||
|
||||
[Fact]
|
||||
public void Lowest_lane_decides_where_patches_overlap()
|
||||
{
|
||||
var world = FluidWorld(8, wets: 4, gravityY: -9.81f, materials: 3);
|
||||
using (world)
|
||||
{
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 2f), friction: 0.6f);
|
||||
world.SetMaterial(0, 0.6f);
|
||||
world.SetMaterial(1, 0.6f, wetFriction: 0.3f);
|
||||
world.SetMaterial(2, 0.6f, wetFriction: 0.05f);
|
||||
var scale = DropRadius / R;
|
||||
// Lane 0 sits at +0.05 m (wet 0.3), lane 1 at -0.05 m (wet 0.05): both hold the point 0, and the sort by x meets lane 1 first.
|
||||
world.CreateParticles([Fluid((0.05f, DropRadius, 0f), FluidMass * scale * scale * scale, DropRadius, material: 1u),
|
||||
Fluid((-0.05f, DropRadius, 0f), FluidMass * scale * scale * scale, DropRadius, material: 2u)]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(Dt, Sub);
|
||||
world.Settle([Handle(world, 0)]);
|
||||
world.Settle([Handle(world, 1)]);
|
||||
var box = world.AddBox(10ul, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), BoxMass / 0.008f, friction: 0.6f);
|
||||
var moved = Moved(world, [box], 0);
|
||||
var expected = (PushForce - 0.3 * BoxMass * 9.81) / BoxMass;
|
||||
var acceleration = 2.0 * moved / ((double)PushTicks * Dt * PushTicks * Dt);
|
||||
Readings.Add($"WETFRICTION lowest lane: acceleration {acceleration:F4} against {expected:F4}, relative error {Math.Abs(acceleration / expected - 1.0):E3}");
|
||||
Assert.True(Math.Abs(acceleration / expected - 1.0) <= LowestLaneBound, $"acceleration {acceleration} against {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
523
tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs
Normal file
523
tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs
Normal file
|
|
@ -0,0 +1,523 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace Ymir.Box3D.Soa.Tests;
|
||||
|
||||
using Pos = (float X, float Y, float Z);
|
||||
|
||||
/// <summary>Settled liquid as data: docs/soa-world.md, Settle. The step writes no wet lane; settle, remove and destroy do.</summary>
|
||||
public sealed partial class Box3DSoaFluidTests
|
||||
{
|
||||
private const float DropVolume = (2f * R) * (2f * R) * (2f * R); // (2 r)^3, in float as the native computes it
|
||||
|
||||
private static Box3DSoaParticleHandle Handle(Box3DSoaWorld world, int lane) => new(lane, world.View.ParticleGeneration[lane]);
|
||||
|
||||
/// <summary>A floor (body lane 0, top at y 0) and a world with room for patches; the drops rest on it for 20 ticks so each reads its support.</summary>
|
||||
private static Box3DSoaWorld WetFloor(int particles, int wets, Pos[] at, uint[]? material = null, float[]? radius = null, int materials = 2)
|
||||
{
|
||||
var world = FluidWorld(particles, gravityY: -9.81f, materials: materials, wets: wets);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
var desc = new Box3DSoaParticleDesc[at.Length];
|
||||
for (var i = 0; i < at.Length; i++)
|
||||
{
|
||||
var r = radius?[i] ?? R;
|
||||
desc[i] = new Box3DSoaParticleDesc((at[i].X, r, at[i].Z), FluidMass * (r / R) * (r / R) * (r / R), r, FluidPhase, material?[i] ?? 0u, null, default);
|
||||
}
|
||||
world.CreateParticles(desc);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
return world;
|
||||
}
|
||||
|
||||
private static Box3DSoaParticleHandle[] Handles(Box3DSoaWorld world, int count) =>
|
||||
Enumerable.Range(0, count).Select(i => Handle(world, i)).ToArray();
|
||||
|
||||
private static byte[] WetBytes(Box3DSoaView v)
|
||||
{
|
||||
var o = new MemoryStream();
|
||||
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(MemoryMarshal.AsBytes(lane));
|
||||
B(v.WetBody); B(v.WetParticle); B(v.WetX); B(v.WetY); B(v.WetZ); B(v.WetRadius); B(v.WetPatchVolume); B(v.WetMaterial);
|
||||
B(v.WetLive); B(v.WetGeneration); B(v.WetRemovedAt); B(v.WetVolume);
|
||||
return o.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] WorldBytes(Box3DSoaView v)
|
||||
{
|
||||
var o = new MemoryStream();
|
||||
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(MemoryMarshal.AsBytes(lane));
|
||||
o.Write(WetBytes(v));
|
||||
B(v.ParticleLive); B(v.ParticleGeneration); B(v.ParticleX); B(v.ParticleY); B(v.ParticleZ); B(v.ParticleVx); B(v.ParticleVy); B(v.ParticleVz);
|
||||
B(v.ParticleRemovedAt); B(v.SupportBody); B(v.SupportParticle);
|
||||
B(v.TetherAttachment); B(v.TetherParticle); B(v.TetherParent); B(v.TetherEdge); B(v.TetherOther); B(v.TetherBound); B(v.ParticleComponent);
|
||||
return o.ToArray();
|
||||
}
|
||||
|
||||
private static int LivePatches(Box3DSoaView v) => v.WetLive.ToArray().Count(l => l != 0);
|
||||
|
||||
// Relative error of the patch volumes' sum against n (2 r)^3, over three settle orders of the same 100 drops (ascending, descending, interleaved): shipped
|
||||
// worst 1.909e-7 (a float sum, so the bound takes the worst across orders by lodur:ruling:ymir-column-mean-bound-order-noise), M1 (a merge forgets the volume
|
||||
// already in the patch) 0.84 in each order: bound sqrt(1.909e-7 x 0.84) = 4.0e-4, separation 4.4e6. M2 (no merge) and M2b (merge across materials) conserve the sum and are
|
||||
// claimed by Settle_merges_inside_a_patch.
|
||||
private const double ConserveBound = 4.0e-4;
|
||||
|
||||
[Fact]
|
||||
public void Settle_conserves_volume()
|
||||
{
|
||||
var worst = 0.0;
|
||||
foreach (var order in new[] { "ascending", "descending", "interleaved" })
|
||||
{
|
||||
var at = new Pos[100];
|
||||
for (var k = 0; k < 10; k++) for (var i = 0; i < 10; i++) at[k * 10 + i] = (-0.14f + 2.5f * R * i, 0f, -0.14f + 2.5f * R * k);
|
||||
using var world = WetFloor(128, 16, at);
|
||||
var view = world.View;
|
||||
Assert.All(Enumerable.Range(0, 100), i => Assert.True(view.SupportBody[i] >= 0, $"drop {i} reads no support"));
|
||||
var tethers = Snapshot(view);
|
||||
var drops = Handles(world, 100);
|
||||
if (order == "descending") Array.Reverse(drops);
|
||||
if (order == "interleaved") drops = drops.Where((_, i) => i % 2 == 0).Concat(drops.Where((_, i) => i % 2 == 1).Reverse()).ToArray();
|
||||
world.Settle(drops);
|
||||
view = world.View;
|
||||
SameTethers(tethers, Snapshot(view));
|
||||
Assert.All(Enumerable.Range(0, 100), i => Assert.Equal(0u, view.ParticleLive[i]));
|
||||
var sum = 0.0;
|
||||
for (var w = 0; w < view.WetCount; w++) if (view.WetLive[w] != 0) sum += view.WetPatchVolume[w];
|
||||
var error = Math.Abs(sum - 100.0 * DropVolume) / (100.0 * DropVolume);
|
||||
Readings.Add($"WET conserve {order}: {LivePatches(view)} patches, relative error {error:E3}");
|
||||
worst = Math.Max(worst, error);
|
||||
}
|
||||
Assert.True(worst <= ConserveBound, $"relative error {worst:E3}");
|
||||
}
|
||||
|
||||
// Centre of a merged patch against the volume-weighted mean of its two contact points, in metres: shipped worst 5.96e-8, M3 (an unweighted mean) 2.333e-2:
|
||||
// bound sqrt(5.96e-8 x 2.333e-2) = 3.7e-5 m, separation 3.9e5.
|
||||
private const double CentreBound = 3.7e-5;
|
||||
|
||||
[Fact]
|
||||
public void Settle_merges_inside_a_patch()
|
||||
{
|
||||
// A drop's patch is a disc of radius sqrt((2 r)^3 / (pi film)) = 70.5 mm. Two drops 30 mm apart: one patch.
|
||||
using (var world = WetFloor(16, 4, [(-0.015f, 0f, 0f), (0.015f, 0f, 0f)]))
|
||||
{
|
||||
world.Settle(Handles(world, 2));
|
||||
Assert.Equal(1, LivePatches(world.View));
|
||||
Assert.Equal(2f * DropVolume, world.View.WetPatchVolume[0], 1e-9f);
|
||||
}
|
||||
// Two spots 200 mm apart: two.
|
||||
using (var world = WetFloor(16, 4, [(-0.1f, 0f, 0f), (0.1f, 0f, 0f)]))
|
||||
{
|
||||
world.Settle(Handles(world, 2));
|
||||
Assert.Equal(2, LivePatches(world.View));
|
||||
}
|
||||
// The same spot, two materials: two (liquids of different material do not mix).
|
||||
using (var world = WetFloor(16, 4, [(-0.015f, 0f, 0f), (0.015f, 0f, 0f)], material: [0u, 1u]))
|
||||
{
|
||||
world.Settle(Handles(world, 2));
|
||||
var view = world.View;
|
||||
Assert.Equal(2, LivePatches(view));
|
||||
Assert.Equal(0u, view.WetMaterial[0]);
|
||||
Assert.Equal(1u, view.WetMaterial[1]);
|
||||
}
|
||||
// Unequal drops (volume 1 : 8) merge to the volume-weighted centre, in the body's frame (the floor body is at y -0.5: the contact point is 0.5 above its origin).
|
||||
using (var world = WetFloor(16, 4, [(-0.03f, 0f, 0f), (0.03f, 0f, 0f)], radius: [R, 2f * R]))
|
||||
{
|
||||
var view = world.View;
|
||||
var (x0, x1) = ((double)view.ParticleX[0], (double)view.ParticleX[1]);
|
||||
var (v0, v1) = ((double)DropVolume, 8.0 * DropVolume);
|
||||
var (z0, z1) = ((double)view.ParticleZ[0], (double)view.ParticleZ[1]);
|
||||
world.Settle(Handles(world, 2));
|
||||
view = world.View;
|
||||
Assert.Equal(1, LivePatches(view));
|
||||
var cx = (x0 * v0 + x1 * v1) / (v0 + v1);
|
||||
var cz = (z0 * v0 + z1 * v1) / (v0 + v1);
|
||||
var error = Math.Max(Math.Abs(view.WetX[0] - cx), Math.Max(Math.Abs(view.WetZ[0] - cz), Math.Abs(view.WetY[0] - 0.5)));
|
||||
Readings.Add($"WET centre error {error:E3} m, weighted x {cx:F5}, unweighted {(x0 + x1) / 2:F5}");
|
||||
Assert.Equal(0, view.WetBody[0]);
|
||||
Assert.Equal(-1, view.WetParticle[0]);
|
||||
Assert.True(error <= CentreBound, $"centre error {error:E3} m");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settle_refusals_change_nothing()
|
||||
{
|
||||
// One patch lane. A pedestal (body 1) beside the floor (body 0); a drop on each, a second on the floor, a solid particle, a drop in flight.
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 1);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (0.5f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
var made = new Box3DSoaParticleHandle[4];
|
||||
world.CreateParticles([Fluid((-0.5f, R, 0f)), Fluid((-0.45f, R, 0f)), Fluid((0.5f, 0.2f + R, 0f)), Fluid((0.9f, 30f, 0f))], made);
|
||||
var solid = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([new Box3DSoaParticleDesc((0.2f, 0.5f, 0f), 0.02f, R, 0u, 0, null, default)], solid);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
var (floorA, floorB, pedestal, flight) = (made[0], made[1], made[2], made[3]);
|
||||
Assert.Equal(0, world.View.SupportBody[floorA.Lane]);
|
||||
Assert.Equal(1, world.View.SupportBody[pedestal.Lane]);
|
||||
world.Settle([floorA]); // the only lane is taken, on the floor
|
||||
Assert.Equal(1, LivePatches(world.View));
|
||||
var gone = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((0.9f, 30f, 0.5f))], gone);
|
||||
world.DestroyParticles(gone);
|
||||
var before = WorldBytes(world.View);
|
||||
void Refused(params Box3DSoaParticleHandle[] batch)
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() => world.Settle(batch));
|
||||
Assert.True(before.AsSpan().SequenceEqual(WorldBytes(world.View)), "a refused batch changed a lane");
|
||||
}
|
||||
Refused(floorB, solid[0]); // a solid particle
|
||||
Refused(floorB, flight); // no support
|
||||
Refused(floorB, gone[0]); // a stale handle
|
||||
Refused(floorB, floorB); // named twice
|
||||
var centre = (world.View.WetX[0], world.View.WetY[0], world.View.WetZ[0]);
|
||||
world.Settle([pedestal]); // no lane and no patch on the pedestal: it adds its volume to the floor patch, whose centre stays
|
||||
Assert.Equal(1, LivePatches(world.View));
|
||||
Assert.Equal(2f * DropVolume, world.View.WetPatchVolume[0], 1e-9f);
|
||||
Assert.Equal(centre, (world.View.WetX[0], world.View.WetY[0], world.View.WetZ[0]));
|
||||
Assert.Equal(0, world.View.WetBody[0]);
|
||||
world.Settle([floorB]); // and a floor drop merges as before
|
||||
Assert.Equal(1, LivePatches(world.View));
|
||||
Assert.Equal(3f * DropVolume, world.View.WetPatchVolume[0], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Patches_follow_their_body()
|
||||
{
|
||||
// A patch on a free box keeps its point in the box's frame while the box is shoved along the floor.
|
||||
{
|
||||
using var world = FluidWorld(64, gravityY: -9.81f, wets: 4);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
var box = world.AddBox(2, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), 5000f, friction: 0.3f);
|
||||
var drop = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((0.03f, 0.2f + R, 0.02f))], drop);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
Assert.Equal(box, world.View.SupportBody[drop[0].Lane]);
|
||||
world.Settle(drop);
|
||||
var view = world.View;
|
||||
var (x, y, z) = (view.WetX[0], view.WetY[0], view.WetZ[0]);
|
||||
Assert.Equal(box, view.WetBody[0]);
|
||||
var rest = view.PositionX[box];
|
||||
world.ApplyImpulse(box, (1500f, 0f, 0f), (view.PositionX[box], view.PositionY[box], view.PositionZ[box]));
|
||||
for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, Sub);
|
||||
view = world.View;
|
||||
Assert.True(view.PositionX[box] - rest > 0.1f, "the box moved");
|
||||
Assert.Equal((x, y, z), (view.WetX[0], view.WetY[0], view.WetZ[0]));
|
||||
Assert.Equal(box, view.WetBody[0]);
|
||||
}
|
||||
// A patch on a solid particle goes when that particle is destroyed; a patch on a body does not.
|
||||
{
|
||||
using var world = new Box3DSoaWorld(4, gravityY: -9.81f, particles: new Box3DSoaParticleCapacities(256, 160, 140, 16, 1024, 2, 16, 4));
|
||||
world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f));
|
||||
var sheet = Graph.Sheet(world, (0f, 0.6f, 0f), (0.04f, 0f, 0f), (0f, 0f, 0.04f), 8, 8, 0.02f, 0.02f, Box3DSoaPhase.Of(4, true, true));
|
||||
for (var j = 0; j < 8; j++)
|
||||
for (var i = 0; i < 8; i += 7)
|
||||
world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[j * 8 + i], point: (0.04f * i, 0.6f, 0.04f * j));
|
||||
var drops = new Box3DSoaParticleHandle[1];
|
||||
world.CreateParticles([Fluid((0.12f, 0.64f, 0.12f))], drops);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
var under = world.View.SupportParticle[drops[0].Lane];
|
||||
Assert.True(under >= 0);
|
||||
world.Settle(drops);
|
||||
var view = world.View;
|
||||
Assert.Equal(1, LivePatches(view));
|
||||
Assert.Equal(under, view.WetParticle[0]);
|
||||
Assert.Equal(-1, view.WetBody[0]);
|
||||
Assert.Equal((0f, 0f, 0f), (view.WetX[0], view.WetY[0], view.WetZ[0]));
|
||||
world.DestroyParticles([sheet.Particles.Single(h => h.Lane == under)]);
|
||||
view = world.View;
|
||||
Assert.Equal(0, LivePatches(view));
|
||||
Assert.Equal(0f, view.WetPatchVolume[0]);
|
||||
Assert.Equal(-1, view.WetParticle[0]);
|
||||
Assert.Equal(1u, view.WetGeneration[0]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wet_volume_reads_patches()
|
||||
{
|
||||
using var world = WetFloor(16, 4, [(-0.1f, 0f, 0f), (0.1f, 0f, 0f), (0.11f, 0f, 0.01f)]);
|
||||
void Reads()
|
||||
{
|
||||
var v = world.View;
|
||||
var sum = new float[v.Count];
|
||||
for (var w = 0; w < v.WetCount; w++) if (v.WetLive[w] != 0) sum[v.WetBody[w]] += v.WetPatchVolume[w];
|
||||
Assert.True(sum.AsSpan().SequenceEqual(v.WetVolume), "wet volume is not the patch sum");
|
||||
}
|
||||
Assert.Equal(0f, world.View.WetVolume[0]);
|
||||
var patches = new Box3DSoaConstraintHandle[3];
|
||||
world.Settle(Handles(world, 3), patches);
|
||||
Reads();
|
||||
Assert.Equal(3f * DropVolume, world.View.WetVolume[0], 1e-9f);
|
||||
Assert.Equal(patches[1].Lane, patches[2].Lane);
|
||||
var before = WetBytes(world.View);
|
||||
for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, Sub); // a step writes no wet lane and no wet volume
|
||||
Assert.True(before.AsSpan().SequenceEqual(WetBytes(world.View)), "a step changed a wet lane");
|
||||
Assert.Equal(2, world.FreeWetSlots); // two of four lanes taken
|
||||
world.Remove(patches[0]);
|
||||
Reads();
|
||||
Assert.Equal(2f * DropVolume, world.View.WetVolume[0], 1e-9f);
|
||||
Assert.Equal(2, world.FreeWetSlots); // a freed lane waits for a step to pass
|
||||
world.Step(1f / 60f, Sub);
|
||||
Assert.Equal(3, world.FreeWetSlots);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Remove(patches[0])); // a stale handle
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settle_joins_the_lowest_patch_that_holds_the_point()
|
||||
{
|
||||
// Patches at x -0.05 and 0.05 (100 mm apart, radius 70.5 mm: separate); a drop at 0 lies in both discs and joins the lower lane.
|
||||
using var world = WetFloor(16, 4, [(-0.05f, 0f, 0f), (0.05f, 0f, 0f), (0f, 0f, 0f)]);
|
||||
var v = world.View;
|
||||
Assert.True(v.ParticleX[1] - v.ParticleX[0] > 0.0705f && MathF.Abs(v.ParticleX[2] - v.ParticleX[0]) < 0.07f && MathF.Abs(v.ParticleX[2] - v.ParticleX[1]) < 0.07f, "the scene did not hold its geometry");
|
||||
world.Settle([Handle(world, 0)]);
|
||||
world.Settle([Handle(world, 1)]);
|
||||
Assert.Equal(2, LivePatches(world.View));
|
||||
var landed = new Box3DSoaConstraintHandle[1];
|
||||
world.Settle([Handle(world, 2)], landed);
|
||||
v = world.View;
|
||||
Assert.Equal(0, landed[0].Lane);
|
||||
Assert.Equal(2f * DropVolume, v.WetPatchVolume[0], 1e-9f);
|
||||
Assert.Equal(DropVolume, v.WetPatchVolume[1], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settle_with_no_lane_joins_the_nearest_patch_of_its_material()
|
||||
{
|
||||
// Three lanes, all taken: lane 0 material 0 at x -0.12, lane 1 material 0 at -0.4, lane 2 material 1 at 0.09. A material 0 drop at 0 lies in no disc and no lane
|
||||
// is free: it joins lane 0, the nearest of its own material (lane 2 is nearer and lane 1 farther, and neither may take it).
|
||||
using var world = WetFloor(16, 3, [(-0.12f, 0f, 0f), (-0.4f, 0f, 0f), (0.09f, 0f, 0f), (0f, 0f, 0f)], material: [0u, 0u, 1u, 0u]);
|
||||
var v = world.View;
|
||||
Assert.True(v.ParticleX[3] - v.ParticleX[0] > 0.0705f && v.ParticleX[2] - v.ParticleX[3] > 0.0705f && v.ParticleX[3] - v.ParticleX[0] > v.ParticleX[2] - v.ParticleX[3], "the scene did not hold its geometry");
|
||||
world.Settle([Handle(world, 0), Handle(world, 1), Handle(world, 2)]);
|
||||
Assert.Equal(0, world.FreeWetSlots);
|
||||
var landed = new Box3DSoaConstraintHandle[1];
|
||||
world.Settle([Handle(world, 3)], landed);
|
||||
v = world.View;
|
||||
Assert.Equal(0, landed[0].Lane);
|
||||
Assert.Equal(3, LivePatches(v));
|
||||
Assert.Equal(2f * DropVolume, v.WetPatchVolume[0], 1e-9f);
|
||||
Assert.Equal(DropVolume, v.WetPatchVolume[1], 1e-9f);
|
||||
Assert.Equal(DropVolume, v.WetPatchVolume[2], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settle_with_no_lane_and_no_patch_on_its_support_pools_into_the_nearest_patch_in_the_world()
|
||||
{
|
||||
// Two lanes, both taken by floor patches of material 0 at x -0.5 and x 0.9. A pedestal drop (its own support, no patch) at x 0.5 adds its volume to the nearer, lane 1,
|
||||
// and moves no centre; the sum of the volumes is conserved.
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 2);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (0.5f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
world.CreateParticles([Fluid((-0.5f, R, 0f)), Fluid((0.9f, R, 0f)), Fluid((0.5f, 0.2f + R, 0f))]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
world.Settle([Handle(world, 0), Handle(world, 1)]);
|
||||
Assert.Equal(0, world.FreeWetSlots);
|
||||
var v = world.View;
|
||||
var before = (v.WetX[0], v.WetY[0], v.WetZ[0], v.WetX[1], v.WetY[1], v.WetZ[1]);
|
||||
world.Settle([Handle(world, 2)]);
|
||||
v = world.View;
|
||||
Assert.Equal(DropVolume, v.WetPatchVolume[0], 1e-9f);
|
||||
Assert.Equal(2f * DropVolume, v.WetPatchVolume[1], 1e-9f);
|
||||
Assert.Equal(before, (v.WetX[0], v.WetY[0], v.WetZ[0], v.WetX[1], v.WetY[1], v.WetZ[1]));
|
||||
Assert.Equal(2, LivePatches(v));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settle_refusal_undoes_a_merge_it_made()
|
||||
{
|
||||
// One lane taken by a floor patch. The batch is a floor drop that merges into it, then a drop of material 1 that finds no lane and no live patch of its material anywhere: FULL.
|
||||
// The merge must go back: every lane is as it was.
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 1);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (0.5f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
world.CreateParticles([Fluid((-0.5f, R, 0f)), Fluid((-0.45f, R, 0f)), Fluid((0.5f, 0.2f + R, 0f), material: 1u)]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
world.Settle([Handle(world, 0)]);
|
||||
var before = WorldBytes(world.View);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Settle([Handle(world, 1), Handle(world, 2)]));
|
||||
Assert.True(before.AsSpan().SequenceEqual(WorldBytes(world.View)), "a refused batch left a merge behind");
|
||||
Assert.Equal(DropVolume, world.View.WetPatchVolume[0], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_drop_with_no_patch_on_its_support_pools_into_the_patch_nearest_in_world_position()
|
||||
{
|
||||
// Two lanes, both taken: a floor patch A (floor at y -0.5, point 1.7 m left of the drop's body) and a pedestal patch B (body at x -0.4, 0.6 m from the drop). In each body's own frame
|
||||
// A (-1.7, 0.5, 0) is nearer the drop's world point (-1, 0.2, 0) than B (0, 0.1, 0); in the world B is. Only the body's pose puts B first.
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 2);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (-0.4f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
world.AddStaticBox(3, (-1.0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
world.CreateParticles([Fluid((-1.7f, R, 0f)), Fluid((-0.4f, 0.2f + R, 0f)), Fluid((-1.0f, 0.2f + R, 0f))]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
Assert.Equal(2, world.View.SupportBody[2]); // body lanes: floor 0, pedestal 1, the drop's box 2
|
||||
world.Settle([Handle(world, 0), Handle(world, 1)]);
|
||||
Assert.Equal(0, world.FreeWetSlots);
|
||||
Assert.Equal(1, world.View.WetBody[1]);
|
||||
world.Settle([Handle(world, 2)]);
|
||||
Assert.Equal(DropVolume, world.View.WetPatchVolume[0], 1e-9f);
|
||||
Assert.Equal(2f * DropVolume, world.View.WetPatchVolume[1], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_drop_with_no_patch_on_its_support_pools_into_the_patch_on_a_rotated_body()
|
||||
{
|
||||
// A capsule lying on its side (rotated 90 degrees about z) with a patch on its top at x -1.25, a floor patch at x -2.0, no lane free; a pedestal drop at x -1.6 pools into the capsule
|
||||
// patch, 0.35 m away in the world (0.70 and 0.85 m if the body's rotation is left out or applied backwards).
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 2);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (4f, 0.5f, 2f), friction: 0.6f);
|
||||
var s = MathF.Sqrt(0.5f);
|
||||
var capsule = world.AddCapsule(2, (-1.0f, 0.1f, 0f), 0.1f, 0.3f, 1000f, rotation: (0f, 0f, s, s), friction: 0.6f);
|
||||
world.AddStaticBox(3, (-1.6f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.6f);
|
||||
world.CreateParticles([Fluid((-2.0f, R, 0f)), Fluid((-1.25f, 0.2f + 2 * R, 0f)), Fluid((-1.6f, 0.2f + R, 0f))]);
|
||||
for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, Sub);
|
||||
var v = world.View;
|
||||
Assert.Equal(0, v.SupportBody[0]);
|
||||
Assert.Equal((int)capsule.Lane, v.SupportBody[1]);
|
||||
Assert.Equal(2, v.SupportBody[2]);
|
||||
world.Settle([Handle(world, 0), Handle(world, 1)]);
|
||||
Assert.Equal(0, world.FreeWetSlots);
|
||||
v = world.View;
|
||||
int onCapsule = v.WetBody[0] == capsule.Lane ? 0 : 1, onFloor = 1 - onCapsule;
|
||||
world.Settle([Handle(world, 2)]);
|
||||
v = world.View;
|
||||
Assert.Equal(DropVolume, v.WetPatchVolume[onFloor], 1e-9f);
|
||||
Assert.Equal(2f * DropVolume, v.WetPatchVolume[onCapsule], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_drop_equidistant_from_two_patches_pools_into_the_lower_lane()
|
||||
{
|
||||
// Floor patches A (x -0.5, lane 0) and B (x +0.5, lane 1), no lane free; the drop on a pedestal at x 0 is the same distance from both, and the lowest lane takes it.
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 2);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
world.CreateParticles([Fluid((-0.5f, R, 0f)), Fluid((0.5f, R, 0f)), Fluid((0f, 0.2f + R, 0f))]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
world.Settle([Handle(world, 0), Handle(world, 1)]);
|
||||
var v = world.View;
|
||||
var da = Math.Abs(v.WetX[0]) - Math.Abs(v.WetX[1]);
|
||||
Assert.Equal(0.0, da, 1e-6); // the scene is a tie
|
||||
world.Settle([Handle(world, 2)]);
|
||||
v = world.View;
|
||||
Assert.Equal(2f * DropVolume, v.WetPatchVolume[0], 1e-9f);
|
||||
Assert.Equal(DropVolume, v.WetPatchVolume[1], 1e-9f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Settle_refusal_unwinds_a_patch_it_created()
|
||||
{
|
||||
// One lane; the floor drop (material 0) creates the patch, then the pedestal drop (material 1) finds no lane and no live patch of its material anywhere: FULL. The created patch and the count go back.
|
||||
using var world = FluidWorld(16, gravityY: -9.81f, wets: 1);
|
||||
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
|
||||
world.AddStaticBox(2, (0.5f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f);
|
||||
world.CreateParticles([Fluid((-0.5f, R, 0f)), Fluid((0.5f, 0.2f + R, 0f), material: 1u), Fluid((-0.45f, R, 0f))]);
|
||||
for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub);
|
||||
Assert.Equal(0, world.View.WetCount);
|
||||
var before = WorldBytes(world.View);
|
||||
Assert.Throws<InvalidOperationException>(() => world.Settle([Handle(world, 0), Handle(world, 1)]));
|
||||
Assert.Equal(0, world.View.WetCount);
|
||||
Assert.Equal(0, LivePatches(world.View));
|
||||
Assert.True(before.AsSpan().SequenceEqual(WorldBytes(world.View)), "a refused batch changed a lane");
|
||||
var landed = new Box3DSoaConstraintHandle[1];
|
||||
world.Settle([Handle(world, 0)], landed); // the lane is still free and its generation unmoved
|
||||
Assert.Equal(0u, world.View.WetGeneration[0]);
|
||||
// A lane below the count, dead and a step old, is taken again by the batch and must read dead again after the refusal.
|
||||
world.Remove(landed[0]);
|
||||
world.Step(1f / 60f, Sub);
|
||||
before = WorldBytes(world.View);
|
||||
Assert.Equal(1, world.View.WetCount);
|
||||
Assert.Equal(0, LivePatches(world.View));
|
||||
Assert.Throws<InvalidOperationException>(() => world.Settle([Handle(world, 2), Handle(world, 1)]));
|
||||
Assert.Equal(0, LivePatches(world.View));
|
||||
Assert.True(before.AsSpan().SequenceEqual(WorldBytes(world.View)), "a refused batch changed a lane");
|
||||
}
|
||||
|
||||
private static string NativeSource(string file)
|
||||
{
|
||||
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
|
||||
{
|
||||
var path = Path.Combine(dir.FullName, "native", "Ymir.Box3D", file);
|
||||
if (File.Exists(path)) return File.ReadAllText(path);
|
||||
}
|
||||
throw new FileNotFoundException(file);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Remove_wet_never_reaches_the_topology_derivation()
|
||||
{
|
||||
// Rederiving an unchanged graph writes the same bytes, so no lane tells the call from its absence; the rule is pinned on the source (the authority map: remove(WET)
|
||||
// ends in rederive_wet, never in rederive_topology; rederive_wet's callers are settle, remove(WET), release_body and destroy).
|
||||
var source = NativeSource("ymir_particles.c").Replace("\r\n", "\n");
|
||||
var at = source.IndexOf("if (type == YMIR_LANES_WET)", StringComparison.Ordinal);
|
||||
Assert.True(at > 0);
|
||||
var branch = source.Substring(at, source.IndexOf("return YMIR_PARTICLES_OK;", at, StringComparison.Ordinal) - at);
|
||||
branch = System.Text.RegularExpressions.Regex.Replace(branch, "//[^\n]*", ""); // the comments name what the branch avoids
|
||||
Assert.Contains("rederive_wet(p);", branch);
|
||||
Assert.DoesNotContain("rederive_topology", branch);
|
||||
Assert.DoesNotContain("TOPO_", branch);
|
||||
Assert.Equal(5, System.Text.RegularExpressions.Regex.Matches(source, @"[^_]rederive_wet\(p\);").Count); // settle, take_wet (once, at the end), remove(WET), release_body (a removed body takes its patches), and destroy when a destroyed solid takes its patches (particle_wet_mu goes dry again)
|
||||
}
|
||||
|
||||
// ---- determinism ----------------------------------------------------------------------------------------
|
||||
|
||||
private static ulong HashWet(Box3DSoaView v)
|
||||
{
|
||||
var h = 1469598103934665603ul;
|
||||
h = Fnv(h, WorldBytes(v));
|
||||
void F(ReadOnlySpan<float> lane) => h = Fnv(h, MemoryMarshal.AsBytes(lane));
|
||||
F(v.PositionX); F(v.PositionY); F(v.PositionZ);
|
||||
return h;
|
||||
}
|
||||
|
||||
private static ulong[] WetCheckpoints(bool nudge = false)
|
||||
{
|
||||
// A pool poured into a well that holds a free box; every 10 ticks every drop that reads a support settles.
|
||||
using var world = FluidWorld(256, gravityY: -9.81f, wets: 32);
|
||||
Well(world, 0.1f);
|
||||
world.AddBox(6, (0f, 0.04f, 0f), (0.04f, 0.04f, 0.04f), 2000f, friction: 0.3f);
|
||||
var desc = new Box3DSoaParticleDesc[100];
|
||||
for (var k = 0; k < 5; k++) for (var j = 0; j < 4; j++) for (var i = 0; i < 5; i++)
|
||||
desc[(k * 4 + j) * 5 + i] = new Box3DSoaParticleDesc((-0.05f + 0.03f * i, 0.12f + 0.03f * j, -0.05f + 0.03f * k), FluidMass, R, FluidPhase, 0, null, default);
|
||||
if (nudge) desc[40].X = BitConverter.UInt32BitsToSingle(BitConverter.SingleToUInt32Bits(desc[40].X) + 1);
|
||||
world.CreateParticles(desc);
|
||||
var hashes = new ulong[6];
|
||||
for (var c = 0; c < 6; c++)
|
||||
{
|
||||
for (var t = 0; t < 40; t++)
|
||||
{
|
||||
world.Step(1f / 60f, Sub);
|
||||
if (t % 10 != 9) continue;
|
||||
var v = world.View;
|
||||
var supported = new List<Box3DSoaParticleHandle>();
|
||||
for (var lane = 0; lane < v.ParticleCount; lane++)
|
||||
if (v.ParticleLive[lane] != 0 && (v.SupportBody[lane] >= 0 || v.SupportParticle[lane] >= 0)) supported.Add(new Box3DSoaParticleHandle(lane, v.ParticleGeneration[lane]));
|
||||
world.Settle(supported.ToArray());
|
||||
}
|
||||
hashes[c] = HashWet(world.View);
|
||||
}
|
||||
Assert.True(LivePatches(world.View) > 0, "nothing settled");
|
||||
return hashes;
|
||||
}
|
||||
|
||||
// Recorded on this commit's build (gcc 13.2, -ffp-contract=off): the wet pour at ticks 40, 80, ... 240. Re-pinned when the Box3D fork ran the friction hook on recycled contacts
|
||||
// (lodur:ruling:wet-friction-on-recycled-contacts): this world settles liquid under a resting box, whose friction now follows it; the fork at 2a43fae reproduces the old values.
|
||||
private static readonly ulong[] WetHashes = [6720483314439625191ul, 15807674163676588943ul, 8969239209631959286ul, 3159003609627402407ul, 16856749248747581653ul, 3168406661706779043ul];
|
||||
|
||||
[Fact]
|
||||
public void Wet_world_is_byte_deterministic()
|
||||
{
|
||||
var a = WetCheckpoints();
|
||||
var b = WetCheckpoints();
|
||||
Assert.True(a.AsSpan().SequenceEqual(b), "two runs diverged: " + string.Join(",", a) + " vs " + string.Join(",", b));
|
||||
Assert.True(a.Distinct().Count() > 1, "the scene moves");
|
||||
Assert.False(a.AsSpan().SequenceEqual(WetCheckpoints(nudge: true)), "a one-ulp input difference must diverge");
|
||||
Assert.True(WetHashes.AsSpan().SequenceEqual(a), string.Join(",", a.Select(g => g + "ul")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Wet_world_is_the_same_bytes_on_any_thread_under_load()
|
||||
{
|
||||
var serial = WetCheckpoints();
|
||||
var results = Enumerable.Range(0, 8).Select(_ => Task.Factory.StartNew(() => WetCheckpoints(), TaskCreationOptions.LongRunning)).ToArray();
|
||||
await Task.WhenAll(results);
|
||||
foreach (var r in results) Assert.True(Enumerable.SequenceEqual(serial, await r), "a concurrent run diverged from the serial one");
|
||||
}
|
||||
}
|
||||
|
|
@ -122,6 +122,46 @@ public sealed unsafe class Box3DSoaWorldTests
|
|||
Assert.False(Lanes(a.View).AsSpan().SequenceEqual(Lanes(b.View)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Each_kind_reads_back_its_size_lanes_at_its_lane_index_and_step_never_changes_them()
|
||||
{
|
||||
// All four kinds interleaved, so a wrong lane-major offset would read one kind's size from another's slot.
|
||||
using var world = new Box3DSoaWorld(capacity: 16);
|
||||
var ground = world.AddStaticBox(1, (0f, -0.5f, 0f), (40f, 0.5f, 30f));
|
||||
var sphere = world.AddSphere(2, (0f, 4f, 0f), radius: 0.7f, density: 1f);
|
||||
var capsule = world.AddCapsule(3, (3f, 4f, 0f), radius: 0.3f, halfLength: 0.9f, density: 1f);
|
||||
var box = world.AddBox(4, (-3f, 4f, 0f), (0.4f, 0.6f, 0.8f), density: 1f);
|
||||
var wall = world.AddStaticBox(5, (0f, 2f, 20f), (2f, 3f, 0.25f));
|
||||
var sphere2 = world.AddSphere(6, (6f, 4f, 0f), radius: 0.2f, density: 1f);
|
||||
|
||||
(float, float, float)[] expected = new (float, float, float)[6];
|
||||
expected[ground] = (40f, 0.5f, 30f);
|
||||
expected[sphere] = (0.7f, 0f, 0f);
|
||||
expected[capsule] = (0.3f, 0.9f, 0f);
|
||||
expected[box] = (0.4f, 0.6f, 0.8f);
|
||||
expected[wall] = (2f, 3f, 0.25f);
|
||||
expected[sphere2] = (0.2f, 0f, 0f);
|
||||
|
||||
var view = world.View;
|
||||
byte[] Sizes(Box3DSoaView v) =>
|
||||
MemoryMarshal.AsBytes(v.Size0).ToArray().Concat(MemoryMarshal.AsBytes(v.Size1).ToArray())
|
||||
.Concat(MemoryMarshal.AsBytes(v.Size2).ToArray()).ToArray();
|
||||
void AssertSizes(Box3DSoaView v)
|
||||
{
|
||||
Assert.Equal(6, v.Size0.Length);
|
||||
for (var i = 0; i < expected.Length; i++)
|
||||
{
|
||||
Assert.Equal(expected[i], (v.Size0[i], v.Size1[i], v.Size2[i]));
|
||||
}
|
||||
}
|
||||
|
||||
AssertSizes(view);
|
||||
var before = Sizes(view);
|
||||
Run(world, 120);
|
||||
AssertSizes(world.View);
|
||||
Assert.True(before.AsSpan().SequenceEqual(Sizes(world.View)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Refuses_bad_input_and_a_full_or_duplicate_world()
|
||||
{
|
||||
|
|
@ -147,4 +187,78 @@ public sealed unsafe class Box3DSoaWorldTests
|
|||
Assert.Throws<ObjectDisposedException>(() => world.Step(Dt));
|
||||
Assert.Throws<ObjectDisposedException>(() => world.View);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_view_taken_before_dispose_refuses_lane_access_after()
|
||||
{
|
||||
var world = Build();
|
||||
var view = world.View;
|
||||
Assert.True(view.PositionY.Length > 0);
|
||||
world.Dispose();
|
||||
Assert.Throws<ObjectDisposedException>(() => view.PositionY.Length);
|
||||
Assert.Throws<ObjectDisposedException>(() => view.ForceX.Length);
|
||||
Assert.Throws<ObjectDisposedException>(() => view.JointAngle.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_default_view_refuses_lane_access()
|
||||
{
|
||||
var view = default(Box3DSoaView);
|
||||
Assert.Throws<InvalidOperationException>(() => view.PositionY.Length);
|
||||
}
|
||||
|
||||
// Box3D's own mass is the owner; the formulas below live here only as the oracle of it.
|
||||
[Fact]
|
||||
public void Mass_is_density_times_the_shapes_volume()
|
||||
{
|
||||
const float rho = 800f, r = 0.3f, h = 0.45f;
|
||||
using var world = new Box3DSoaWorld(capacity: 4);
|
||||
var sphere = world.AddSphere(1, (0f, 1f, 0f), r, rho);
|
||||
var capsule = world.AddCapsule(2, (3f, 1f, 0f), r, h, rho);
|
||||
var box = world.AddBox(3, (6f, 1f, 0f), (0.2f, 0.3f, 0.5f), rho);
|
||||
var view = world.View;
|
||||
Assert.Equal(rho * 4f / 3f * MathF.PI * r * r * r, view.Mass[sphere], rho * 4f / 3f * MathF.PI * r * r * r * 1e-5f);
|
||||
var capsuleVolume = MathF.PI * r * r * 2f * h + 4f / 3f * MathF.PI * r * r * r;
|
||||
Assert.Equal(rho * capsuleVolume, view.Mass[capsule], rho * capsuleVolume * 1e-5f);
|
||||
var boxVolume = 8f * 0.2f * 0.3f * 0.5f;
|
||||
Assert.Equal(rho * boxVolume, view.Mass[box], rho * boxVolume * 1e-5f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Static_and_removed_lanes_read_zero_mass()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4);
|
||||
var ground = world.AddStaticBox(1, (0f, -0.5f, 0f), (5f, 0.5f, 5f));
|
||||
var ball = world.AddSphere(2, (0f, 2f, 0f), 0.5f, 1000f);
|
||||
var view = world.View;
|
||||
Assert.Equal(0f, view.Mass[ground]);
|
||||
Assert.True(view.Mass[ball] > 0f);
|
||||
world.RemoveBody(ball);
|
||||
Assert.Equal(0f, view.Mass[ball]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_hung_capsules_joint_carries_mass_times_gravity()
|
||||
{
|
||||
using var world = new Box3DSoaWorld(capacity: 4, jointCapacity: 2);
|
||||
var pin = world.AddStaticBox(1, (0f, 5f, 0f), (0.1f, 0.1f, 0.1f));
|
||||
var capsule = world.AddCapsule(2, (0f, 4f, 0f), 0.05f, 0.4f, 1000f);
|
||||
var joint = world.AddJoint(Box3DSoaJointKind.Spherical, pin, capsule, (0f, 5f, 0f), (0f, 0f, 1f));
|
||||
var view = world.View;
|
||||
for (var i = 0; i < 180; i++) world.Step(Dt);
|
||||
var g = world.Gravity;
|
||||
var weight = view.Mass[capsule] * MathF.Sqrt(g.X * g.X + g.Y * g.Y + g.Z * g.Z);
|
||||
var load = MathF.Sqrt(view.JointConstraintForceX[joint] * view.JointConstraintForceX[joint] +
|
||||
view.JointConstraintForceY[joint] * view.JointConstraintForceY[joint] +
|
||||
view.JointConstraintForceZ[joint] * view.JointConstraintForceZ[joint]);
|
||||
Assert.Equal(weight, load, weight * 0.01f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gravity_reads_back_the_constructor_arguments()
|
||||
{
|
||||
using (var world = new Box3DSoaWorld(capacity: 1)) Assert.Equal((0f, -10f, 0f), world.Gravity);
|
||||
using (var world = new Box3DSoaWorld(capacity: 1, gravityX: 0f, gravityY: 0f, gravityZ: 0f)) Assert.Equal((0f, 0f, 0f), world.Gravity);
|
||||
using (var world = new Box3DSoaWorld(capacity: 1, gravityX: 1f, gravityY: -9.81f, gravityZ: 2f)) Assert.Equal((1f, -9.81f, 2f), world.Gravity);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Ymir.Core\Ymir.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,92 +0,0 @@
|
|||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using Ymir.Core;
|
||||
|
||||
namespace Ymir.Tests;
|
||||
|
||||
public sealed class YmirServicePublicationTests
|
||||
{
|
||||
[Fact]
|
||||
public void PublicationAdvertisesBox3DOwnershipBoundary()
|
||||
{
|
||||
var now = DateTimeOffset.Parse("2026-07-14T12:00:00Z");
|
||||
|
||||
var advertisement = YmirServicePublication.ProviderAdvertisement(now);
|
||||
var diagnostics = YmirServicePublication.OperatorState(now);
|
||||
|
||||
Assert.Contains("Box3D", advertisement.Description, StringComparison.Ordinal);
|
||||
Assert.Contains("Box3D-only isolated snapshot stepping", advertisement.Owns);
|
||||
Assert.Contains("public in-process retained sessions with explicit mutation receipts", advertisement.Owns);
|
||||
Assert.Contains("typed Begin, Hit, and End contact facts for retained steps", advertisement.Owns);
|
||||
Assert.Contains("daemon-owned named session registry or CultMesh command lowering yet", advertisement.DoesNotOwn);
|
||||
Assert.Empty(advertisement.CommandLowerings);
|
||||
Assert.Contains("Box3D solver and collision semantics", advertisement.DoesNotOwn);
|
||||
Assert.Equal("Box3D v0.1.0 (C17)", diagnostics.NumericSubstrate);
|
||||
Assert.Contains("does not own physics algorithms", diagnostics.BatchKernel, StringComparison.Ordinal);
|
||||
Assert.Contains("world_state.v2", diagnostics.Persistence, StringComparison.Ordinal);
|
||||
Assert.Contains("replay checkpoint v1", diagnostics.Persistence, StringComparison.Ordinal);
|
||||
Assert.Contains("host-owned private journal persistence", diagnostics.Persistence, StringComparison.Ordinal);
|
||||
Assert.Equal("box3d-retained-session", diagnostics.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublicationPersistsAndReopensWithCombinedRegistry()
|
||||
{
|
||||
var path = TemporaryStorePath();
|
||||
try
|
||||
{
|
||||
await YmirServicePublicationStore.RegenerateDerivedStoreAsync(path, DateTimeOffset.UtcNow);
|
||||
|
||||
using var cache = await CultCacheMessagePack.OpenAsync(path, new CultCacheOpenOptions
|
||||
{
|
||||
Registry = new CultDocumentRegistry(),
|
||||
UseDirectoryStore = true
|
||||
});
|
||||
|
||||
Assert.NotNull(cache.Get<YmirOperatorStateDocument>(new CultRecordKey("ymir:operator:ymir.physics")));
|
||||
Assert.Single(cache.GetAll<YmirOperatorStateDocument>());
|
||||
}
|
||||
finally
|
||||
{
|
||||
DeleteStore(path);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegenerationReplacesUnreadableLegacyDerivedStoreBeforeOpen()
|
||||
{
|
||||
var path = TemporaryStorePath();
|
||||
var recordsPath = DirectoryMessagePackBackingStore.DefaultRecordDirectoryPath(path);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
Directory.CreateDirectory(recordsPath);
|
||||
await File.WriteAllBytesAsync(path, [0xc1]);
|
||||
await File.WriteAllBytesAsync(Path.Combine(recordsPath, "legacy.msgpack"), [0xc1]);
|
||||
|
||||
await YmirServicePublicationStore.RegenerateDerivedStoreAsync(path, DateTimeOffset.UtcNow);
|
||||
|
||||
using var cache = await CultCacheMessagePack.OpenAsync(path, new CultCacheOpenOptions
|
||||
{
|
||||
Registry = new CultDocumentRegistry(),
|
||||
UseDirectoryStore = true
|
||||
});
|
||||
Assert.NotNull(cache.Get<YmirOperatorStateDocument>(new CultRecordKey("ymir:operator:ymir.physics")));
|
||||
Assert.False(File.Exists(Path.Combine(recordsPath, "legacy.msgpack")));
|
||||
}
|
||||
finally
|
||||
{
|
||||
DeleteStore(path);
|
||||
}
|
||||
}
|
||||
|
||||
private static string TemporaryStorePath() =>
|
||||
Path.Combine(Path.GetTempPath(), "ymir-tests", Guid.NewGuid().ToString("N"), "service.cc");
|
||||
|
||||
private static void DeleteStore(string path)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(path);
|
||||
if (directory is not null && Directory.Exists(directory))
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,485 +0,0 @@
|
|||
using Ymir.Core;
|
||||
|
||||
namespace Ymir.Tests;
|
||||
|
||||
public sealed class YmirSessionTests
|
||||
{
|
||||
[Fact]
|
||||
public void RetainedBodyAdvancesWithoutSnapshotResubmission()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"retained-motion",
|
||||
[Body("ship", positionX: 0.0f, velocityX: 2.0f)]));
|
||||
|
||||
var first = session.Step(Step("step-1", 0, 0.25f));
|
||||
var second = session.Step(Step("step-2", 1, 0.25f));
|
||||
|
||||
Assert.Equal(YmirCommandOutcome.Accepted, first.Receipt.Outcome);
|
||||
Assert.Equal(1, first.Revision);
|
||||
Assert.Equal(2, second.Revision);
|
||||
Assert.Equal(2, second.StepIndex);
|
||||
Assert.True(second.World.Bodies.Single().Position.X > first.World.Bodies.Single().Position.X);
|
||||
Assert.Equal(2.0f, second.World.Bodies.Single().Velocity.X, 4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForceReceiptIsIdempotentAndForceIsConsumedByOneStep()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest("force-once", [Body("ship")]));
|
||||
var command = new YmirApplyForceCommand(Header("force", 0), "ship", new Vec2(10.0f, 0.0f));
|
||||
|
||||
var accepted = session.ApplyForce(command);
|
||||
var replay = session.ApplyForce(command);
|
||||
var conflict = session.ApplyForce(command with { Force = new Vec2(20.0f, 0.0f) });
|
||||
var revisionConflict = session.ApplyForce(command with { Header = Header("force", 1) });
|
||||
var forced = session.Step(Step("step-forced", 1, 0.1f));
|
||||
var unforced = session.Step(Step("step-unforced", 2, 0.1f));
|
||||
|
||||
Assert.Same(accepted, replay);
|
||||
Assert.Equal(1, accepted.AfterRevision);
|
||||
Assert.Equal(2, session.Info.StepIndex);
|
||||
Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Error);
|
||||
Assert.Equal(YmirCommandOutcome.Rejected, conflict.Outcome);
|
||||
Assert.NotEqual(accepted.ReceiptId, conflict.ReceiptId);
|
||||
Assert.Equal(YmirCommandError.CommandIdConflict, revisionConflict.Error);
|
||||
Assert.Equal(forced.World.Bodies.Single().Velocity.X, unforced.World.Bodies.Single().Velocity.X, 4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OmissionCannotRemoveBodyAndRemoveIsExplicit()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"explicit-remove",
|
||||
[Body("a"), Body("b", positionX: 10.0f)]));
|
||||
|
||||
var velocity = session.SetVelocity(new YmirSetBodyVelocityCommand(
|
||||
Header("set-a", 0), "a", new Vec2(1.0f, 0.0f), 0.0f));
|
||||
var stepped = session.Step(Step("step", 1, 0.1f));
|
||||
var removed = session.Remove(new YmirRemoveBodyCommand(Header("remove-b", 2), "b"));
|
||||
|
||||
Assert.Equal(YmirCommandOutcome.Accepted, velocity.Outcome);
|
||||
Assert.Equal(2, stepped.World.Bodies.Count);
|
||||
Assert.Equal(YmirCommandOutcome.Accepted, removed.Outcome);
|
||||
Assert.Equal(["a"], session.Snapshot().Bodies.Select(body => body.Id).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ContactEpisodeEmitsBeginThenEndThenNewBegin()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"contact-lifecycle",
|
||||
[
|
||||
Body("a", positionX: 0.0f, isStatic: true),
|
||||
Body("b", positionX: 1.5f)
|
||||
]));
|
||||
|
||||
var began = session.Step(Step("begin", 0, 0.01f));
|
||||
var persistent = session.Step(Step("persistent", 1, 0.01f));
|
||||
session.Teleport(new YmirTeleportBodyCommand(
|
||||
Header("separate", 2), "b", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f)));
|
||||
var ended = session.Step(Step("end", 3, 0.01f));
|
||||
session.Teleport(new YmirTeleportBodyCommand(
|
||||
Header("return", 4), "b", new Vec2(1.5f, 0.0f), new Vec2(0.0f, 1.0f)));
|
||||
var beganAgain = session.Step(Step("begin-again", 5, 0.01f));
|
||||
|
||||
var firstBegin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
var end = Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End);
|
||||
var secondBegin = Assert.Single(beganAgain.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
Assert.Equal(firstBegin.ContactId, end.ContactId);
|
||||
Assert.NotEqual(firstBegin.ContactId, secondBegin.ContactId);
|
||||
Assert.Equal("a", firstBegin.BodyA);
|
||||
Assert.Equal("b", firstBegin.BodyB);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReplayCheckpointPreservesContactLineageAndCommandLedger()
|
||||
{
|
||||
using var original = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"checkpoint-contact",
|
||||
[
|
||||
Body("ship", positionX: 0.0f, isStatic: true),
|
||||
Body("pickup", positionX: 1.5f)
|
||||
]));
|
||||
var began = original.Step(Step("begin", 0, 0.01f));
|
||||
var firstBegin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
var checkpoint = original.Checkpoint();
|
||||
var payload = YmirSessionCheckpointCodec.Encode(checkpoint);
|
||||
checkpoint = YmirSessionCheckpointCodec.Decode(payload);
|
||||
|
||||
using var restored = YmirSession.Restore(checkpoint);
|
||||
var duplicate = restored.Step(Step("begin", 0, 0.01f));
|
||||
Assert.Equal(began.Receipt.ReceiptId, duplicate.Receipt.ReceiptId);
|
||||
Assert.Equal(began.Receipt.Outcome, duplicate.Receipt.Outcome);
|
||||
Assert.Equal(began.Receipt.BeforeRevision, duplicate.Receipt.BeforeRevision);
|
||||
Assert.Equal(began.Receipt.AfterRevision, duplicate.Receipt.AfterRevision);
|
||||
Assert.Equal(began.Receipt.ProducedFactIds, duplicate.Receipt.ProducedFactIds);
|
||||
Assert.Equal(began.ContactFacts.Select(value => value.FactId), duplicate.ContactFacts.Select(value => value.FactId));
|
||||
Assert.Equal(checkpoint.SessionGeneration, restored.Info.SessionGeneration);
|
||||
|
||||
var conflict = restored.Step(Step("begin", 0, 0.02f));
|
||||
Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Receipt.Error);
|
||||
var persistent = restored.Step(Step("persistent", 1, 0.01f));
|
||||
Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
restored.Teleport(new YmirTeleportBodyCommand(
|
||||
Header("separate", 2), "pickup", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f)));
|
||||
var ended = restored.Step(Step("end", 3, 0.01f));
|
||||
var end = Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End);
|
||||
Assert.Equal(firstBegin.ContactId, end.ContactId);
|
||||
restored.Teleport(new YmirTeleportBodyCommand(
|
||||
Header("return", 4), "pickup", new Vec2(1.5f, 0.0f), new Vec2(0.0f, 1.0f)));
|
||||
var beganAgain = restored.Step(Step("begin-again", 5, 0.01f));
|
||||
var secondBegin = Assert.Single(beganAgain.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
Assert.NotEqual(firstBegin.ContactId, secondBegin.ContactId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReplayCheckpointRestoresPendingForceAndRejectsCorruptJournal()
|
||||
{
|
||||
using var original = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"checkpoint-force", [Body("ship")]));
|
||||
original.ApplyForce(new YmirApplyForceCommand(Header("force", 0), "ship", new Vec2(10.0f, 0.0f)));
|
||||
var checkpoint = original.Checkpoint();
|
||||
|
||||
using var restored = YmirSession.Restore(checkpoint);
|
||||
var stepped = restored.Step(Step("step", 1, 0.1f));
|
||||
Assert.True(stepped.World.Bodies.Single().Velocity.X > 0.0f);
|
||||
|
||||
var corrupt = checkpoint with { Journal = [] };
|
||||
Assert.Throws<InvalidOperationException>(() => YmirSession.Restore(corrupt));
|
||||
var wrongRuntime = checkpoint with { RuntimeFingerprint = "some-other-solver" };
|
||||
Assert.Throws<InvalidOperationException>(() => YmirSession.Restore(wrongRuntime));
|
||||
var corruptIdentity = YmirSessionCheckpointCodec.Encode(checkpoint);
|
||||
corruptIdentity[32] ^= 0xff;
|
||||
Assert.Throws<InvalidDataException>(() => YmirSessionCheckpointCodec.Decode(corruptIdentity));
|
||||
Assert.Throws<InvalidDataException>(() =>
|
||||
YmirSessionCheckpointCodec.Decode(YmirSessionCheckpointCodec.Encode(checkpoint).Concat(new byte[] { 1 }).ToArray()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IncrementalPersistenceWritesOnlyNewJournalEntriesAndRestoresBoundary()
|
||||
{
|
||||
using var original = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"incremental-contact",
|
||||
[Body("ship", positionX: 0.0f, isStatic: true), Body("pickup", positionX: 1.5f)]));
|
||||
var began = original.Step(Step("begin", 0, 0.01f));
|
||||
var begin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
|
||||
var first = original.CapturePersistence(0);
|
||||
var firstChunk = Assert.IsType<YmirSessionJournalChunk>(first.JournalChunk);
|
||||
Assert.Equal(0, firstChunk.FirstEntryIndex);
|
||||
Assert.Single(firstChunk.Entries);
|
||||
var firstChunkBytes = YmirSessionCheckpointCodec.Encode(firstChunk);
|
||||
var firstDescriptorBytes = YmirSessionCheckpointCodec.Encode(first.ResumeDescriptor);
|
||||
|
||||
var persistent = original.Step(Step("persistent", 1, 0.01f));
|
||||
Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
var second = original.CapturePersistence(first.ResumeDescriptor.JournalEntryCount);
|
||||
var secondChunk = Assert.IsType<YmirSessionJournalChunk>(second.JournalChunk);
|
||||
Assert.Equal(1, secondChunk.FirstEntryIndex);
|
||||
Assert.Single(secondChunk.Entries);
|
||||
|
||||
var chunks = new[]
|
||||
{
|
||||
YmirSessionCheckpointCodec.DecodeJournalChunk(firstChunkBytes),
|
||||
YmirSessionCheckpointCodec.DecodeJournalChunk(YmirSessionCheckpointCodec.Encode(secondChunk))
|
||||
};
|
||||
var descriptor = YmirSessionCheckpointCodec.DecodeResumeDescriptor(
|
||||
YmirSessionCheckpointCodec.Encode(second.ResumeDescriptor));
|
||||
using var restored = YmirSession.Restore(descriptor, chunks);
|
||||
restored.Teleport(new YmirTeleportBodyCommand(
|
||||
Header("separate", 2), "pickup", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f)));
|
||||
var ended = restored.Step(Step("end", 3, 0.01f));
|
||||
Assert.Equal(begin.ContactId, Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End).ContactId);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => YmirSession.Restore(descriptor, [chunks[1]]));
|
||||
var corruptDescriptor = firstDescriptorBytes.ToArray();
|
||||
corruptDescriptor[24] ^= 0xff;
|
||||
Assert.Throws<InvalidDataException>(() => YmirSessionCheckpointCodec.DecodeResumeDescriptor(corruptDescriptor));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QuiescentSessionCanRollToAnEmptyPersistenceGeneration()
|
||||
{
|
||||
using var original = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"compact-quiescent", [Body("ship", velocityX: 2.0f)]));
|
||||
original.Step(Step("step-1", 0, 0.1f));
|
||||
original.Step(Step("step-2", 1, 0.1f));
|
||||
var expectedWorld = original.Snapshot();
|
||||
|
||||
Assert.True(original.TryReplaceWithCompactedPersistenceBaseline(out var compacted));
|
||||
using (compacted!)
|
||||
{
|
||||
var baseline = compacted!;
|
||||
Assert.NotEqual(original.Info.SessionGeneration, baseline.Info.SessionGeneration);
|
||||
Assert.True(original.Info.IsDisposed);
|
||||
Assert.Equal(0, baseline.Info.Revision);
|
||||
Assert.Equal(0, baseline.PersistenceJournalEntryCount);
|
||||
AssertWorldEqual(expectedWorld, baseline.Snapshot());
|
||||
|
||||
var capture = baseline.CapturePersistence(0);
|
||||
Assert.Null(capture.JournalChunk);
|
||||
Assert.Equal(0, capture.ResumeDescriptor.JournalEntryCount);
|
||||
using var restored = YmirSession.Restore(capture.ResumeDescriptor, []);
|
||||
AssertWorldEqual(baseline.Snapshot(), restored.Snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PersistenceRolloverRefusesActiveContactsAndUnsteppedMutations()
|
||||
{
|
||||
using var touching = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"compact-contact",
|
||||
[Body("ship", positionX: 0.0f, isStatic: true), Body("pickup", positionX: 1.5f)]));
|
||||
touching.Step(Step("begin", 0, 0.01f));
|
||||
Assert.False(touching.TryReplaceWithCompactedPersistenceBaseline(out var contactBaseline));
|
||||
Assert.Null(contactBaseline);
|
||||
|
||||
using var pendingForce = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"compact-force", [Body("ship")]));
|
||||
pendingForce.ApplyForce(new YmirApplyForceCommand(
|
||||
Header("force", 0), "ship", new Vec2(10.0f, 0.0f)));
|
||||
Assert.False(pendingForce.TryReplaceWithCompactedPersistenceBaseline(out var forceBaseline));
|
||||
Assert.Null(forceBaseline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveAndRecreateChangesBodyGeneration()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"body-generation",
|
||||
[Body("wall", isStatic: true), Body("pickup", positionX: 1.5f)]));
|
||||
var first = session.Step(Step("begin-1", 0, 0.01f));
|
||||
var firstFact = Assert.Single(first.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
session.Remove(new YmirRemoveBodyCommand(Header("remove", 1), "pickup"));
|
||||
var removed = session.Step(Step("removed", 2, 0.01f));
|
||||
session.Spawn(new YmirSpawnBodyCommand(Header("spawn", 3), Body("pickup", positionX: 1.5f)));
|
||||
var second = session.Step(Step("begin-2", 4, 0.01f));
|
||||
var secondFact = Assert.Single(second.ContactFacts, fact =>
|
||||
fact.Kind == YmirContactFactKind.Begin &&
|
||||
(fact.BodyA == "pickup" || fact.BodyB == "pickup"));
|
||||
|
||||
var firstGeneration = BodyGeneration(firstFact, "pickup");
|
||||
Assert.Contains(removed.ContactFacts, fact =>
|
||||
fact.Kind == YmirContactFactKind.End && fact.ContactId == firstFact.ContactId);
|
||||
Assert.True(BodyGeneration(secondFact, "pickup") > firstGeneration);
|
||||
Assert.NotEqual(firstFact.ContactId, secondFact.ContactId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotImmediatelyReflectsCanonicalNativeMutationState()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"canonical-snapshot",
|
||||
[Body("ship") with { Direction = new Vec2(0.0f, 2.0f) }]));
|
||||
|
||||
Assert.Equal(new Vec2(0.0f, 1.0f), session.Snapshot().Bodies.Single().Direction);
|
||||
session.Teleport(new YmirTeleportBodyCommand(
|
||||
Header("teleport", 0), "ship", new Vec2(3.0f, 4.0f), new Vec2(2.0f, 0.0f)));
|
||||
var teleported = session.Snapshot().Bodies.Single();
|
||||
Assert.Equal(1.0f, teleported.Direction!.Value.X, 5);
|
||||
Assert.Equal(0.0f, teleported.Direction.Value.Y, 5);
|
||||
Assert.Equal(new Vec2(3.0f, 4.0f), teleported.Position);
|
||||
|
||||
session.Configure(new YmirConfigureBodyCommand(
|
||||
Header("static", 1), "ship", 2.0f, 1.0f, true, 0.5f));
|
||||
var configured = session.Snapshot().Bodies.Single();
|
||||
Assert.True(configured.IsStatic);
|
||||
Assert.Equal(2.0f, configured.Radius);
|
||||
Assert.Equal(0.5f, configured.Restitution);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaleAndDisposedCommandsFailClosedWithoutMutation()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest("stale", [Body("ship")]));
|
||||
var accepted = session.SetVelocity(new YmirSetBodyVelocityCommand(
|
||||
Header("accepted", 0), "ship", new Vec2(1.0f, 0.0f), 0.0f));
|
||||
var stale = session.SetVelocity(new YmirSetBodyVelocityCommand(
|
||||
Header("stale", 0), "ship", new Vec2(100.0f, 0.0f), 0.0f));
|
||||
var disposed = session.Dispose(new YmirDisposeSessionCommand(Header("dispose", 1)));
|
||||
var afterDispose = session.Remove(new YmirRemoveBodyCommand(Header("late", 2), "ship"));
|
||||
|
||||
Assert.Equal(YmirCommandOutcome.Accepted, accepted.Outcome);
|
||||
Assert.Equal(YmirCommandError.StaleRevision, stale.Error);
|
||||
Assert.Equal(YmirCommandOutcome.Accepted, disposed.Outcome);
|
||||
Assert.Equal(YmirCommandError.SessionDisposed, afterDispose.Error);
|
||||
Assert.Equal(2, afterDispose.BeforeRevision);
|
||||
Assert.Equal(afterDispose.BeforeRevision, afterDispose.AfterRevision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TypedFingerprintRejectsDelimiterCollisionsAndNullPayloads()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest("fingerprints", []));
|
||||
var accepted = session.Spawn(new YmirSpawnBodyCommand(
|
||||
Header("spawn", 0), Body("body|with|delimiters")));
|
||||
var conflict = session.Spawn(new YmirSpawnBodyCommand(
|
||||
Header("spawn", 0), Body("body") with { Position = new Vec2(1.0f, 2.0f) }));
|
||||
var nullBody = session.Spawn(new YmirSpawnBodyCommand(Header("null-body", 1), null!));
|
||||
var nullFields = session.Step(new YmirStepSessionCommand(Header("null-fields", 1), 0.1f, null!));
|
||||
|
||||
Assert.Equal(YmirCommandOutcome.Accepted, accepted.Outcome);
|
||||
Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Error);
|
||||
Assert.Equal(YmirCommandError.InvalidCommand, nullBody.Error);
|
||||
Assert.Equal(YmirCommandError.InvalidCommand, nullFields.Receipt.Error);
|
||||
Assert.Equal(1, session.Info.Revision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaticBodyVelocityCommandIsRejectedWithoutARevisionLie()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"static-velocity", [Body("wall", isStatic: true)]));
|
||||
|
||||
var receipt = session.SetVelocity(new YmirSetBodyVelocityCommand(
|
||||
Header("move-wall", 0), "wall", new Vec2(10.0f, 0.0f), 2.0f));
|
||||
|
||||
Assert.Equal(YmirCommandOutcome.Rejected, receipt.Outcome);
|
||||
Assert.Equal(YmirCommandError.StaticBody, receipt.Error);
|
||||
Assert.Equal(0, session.Info.Revision);
|
||||
Assert.Equal(Vec2.Zero, session.Snapshot().Bodies.Single().Velocity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CollisionProfilesExcludeOwnGroupAndPayloadPeers()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"collision-profile",
|
||||
[
|
||||
Body("source") with
|
||||
{
|
||||
CollisionCategoryBits = 1,
|
||||
CollisionMaskBits = 2,
|
||||
CollisionGroupIndex = -7
|
||||
},
|
||||
Body("own-payload") with
|
||||
{
|
||||
CollisionCategoryBits = 2,
|
||||
CollisionMaskBits = 1,
|
||||
CollisionGroupIndex = -7
|
||||
},
|
||||
Body("other-payload") with
|
||||
{
|
||||
CollisionCategoryBits = 2,
|
||||
CollisionMaskBits = 1,
|
||||
CollisionGroupIndex = -8
|
||||
}
|
||||
]));
|
||||
|
||||
var result = session.Step(Step("profile-step", 0, 1.0f / 60.0f));
|
||||
var begin = Assert.Single(result.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin);
|
||||
|
||||
Assert.Equal(new HashSet<string> { "source", "other-payload" }, new HashSet<string> { begin.BodyA, begin.BodyB });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BodyCanOptOutOfRadialFields()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"field-profile",
|
||||
[Body("affected", positionX: 1.0f), Body("ignored", positionX: -5.0f) with { ParticipatesInFields = false }]));
|
||||
|
||||
var result = session.Step(new YmirStepSessionCommand(
|
||||
Header("field-step", 0),
|
||||
0.1f,
|
||||
[new RadialField("gravity", Vec2.Zero, 10.0f, 10.0f)]));
|
||||
|
||||
Assert.NotEqual(0.0f, result.World.Bodies.Single(body => body.Id == "affected").Velocity.X);
|
||||
Assert.Equal(0.0f, result.World.Bodies.Single(body => body.Id == "ignored").Velocity.X, 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KinematicTargetDoesNotAcceptBulletImpulse()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"bullet-kinematic",
|
||||
[
|
||||
Body("bullet", positionX: -10.0f, velocityX: 100.0f) with { IsBullet = true },
|
||||
Body("target") with { IsKinematic = true }
|
||||
]));
|
||||
|
||||
var ccdStep = session.Step(Step("ccd", 0, 0.2f));
|
||||
var eventStep = session.Step(Step("event", 1, 1.0f / 60.0f));
|
||||
|
||||
Assert.Empty(ccdStep.ContactFacts);
|
||||
Assert.Contains(eventStep.ContactFacts, fact => fact.Kind is YmirContactFactKind.Begin or YmirContactFactKind.Hit);
|
||||
var target = eventStep.World.Bodies.Single(body => body.Id == "target");
|
||||
Assert.Equal(Vec2.Zero, target.Velocity);
|
||||
Assert.Equal(Vec2.Zero, target.Position);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RetainedCastObservesNamedRevisionAndExplicitCandidates()
|
||||
{
|
||||
using var session = YmirSession.Create(new YmirSessionCreateRequest(
|
||||
"retained-cast",
|
||||
[Body("source", positionX: -2.0f), Body("target", positionX: 2.0f), Body("ignored", positionX: 0.0f)]));
|
||||
|
||||
var result = session.CastCircle(new YmirSessionCircleCastQuery(
|
||||
"payload-sweep",
|
||||
0,
|
||||
new Vec2(-5.0f, 0.0f),
|
||||
new Vec2(1.0f, 0.0f),
|
||||
10.0f,
|
||||
0.25f,
|
||||
["target"]));
|
||||
|
||||
Assert.Equal(YmirQueryError.None, result.Error);
|
||||
Assert.Equal(0, result.ObservedRevision);
|
||||
Assert.Equal(0, result.ObservedStepIndex);
|
||||
Assert.Equal("target", Assert.Single(result.Hits).BodyId);
|
||||
Assert.Equal(0, session.Info.Revision);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RetainedQueriesFailClosedForStaleUnknownAndDisposedSessions()
|
||||
{
|
||||
var session = YmirSession.Create(new YmirSessionCreateRequest("query-failures", [Body("target")]));
|
||||
|
||||
var stale = session.OverlapCircle(new YmirSessionCircleOverlapQuery(
|
||||
"stale", 1, Vec2.Zero, 1.0f, ["target"]));
|
||||
var unknown = session.OverlapCircle(new YmirSessionCircleOverlapQuery(
|
||||
"unknown", 0, Vec2.Zero, 1.0f, ["missing"]));
|
||||
session.Dispose();
|
||||
var disposed = session.OverlapCircle(new YmirSessionCircleOverlapQuery(
|
||||
"disposed", 0, Vec2.Zero, 1.0f, ["target"]));
|
||||
|
||||
Assert.Equal(YmirQueryError.StaleRevision, stale.Error);
|
||||
Assert.Equal(YmirQueryError.UnknownBody, unknown.Error);
|
||||
Assert.Equal(YmirQueryError.SessionDisposed, disposed.Error);
|
||||
Assert.Empty(stale.Hits);
|
||||
Assert.Empty(unknown.Hits);
|
||||
Assert.Empty(disposed.Hits);
|
||||
}
|
||||
|
||||
private static YmirCommandHeader Header(string id, long revision) => new(id, revision);
|
||||
|
||||
private static long BodyGeneration(YmirContactFact fact, string bodyId) =>
|
||||
fact.BodyA == bodyId ? fact.BodyAGeneration : fact.BodyBGeneration;
|
||||
|
||||
private static YmirStepSessionCommand Step(string id, long revision, float deltaTime) =>
|
||||
new(Header(id, revision), deltaTime, []);
|
||||
|
||||
private static PhysicsBody Body(
|
||||
string id,
|
||||
float positionX = 0.0f,
|
||||
float velocityX = 0.0f,
|
||||
bool isStatic = false) =>
|
||||
new(
|
||||
id,
|
||||
new Vec2(positionX, 0.0f),
|
||||
new Vec2(velocityX, 0.0f),
|
||||
1.0f,
|
||||
1.0f,
|
||||
isStatic,
|
||||
0.0f,
|
||||
new Vec2(0.0f, 1.0f));
|
||||
|
||||
private static void AssertWorldEqual(YmirWorld expected, YmirWorld actual)
|
||||
{
|
||||
Assert.Equal(expected.Time, actual.Time);
|
||||
Assert.Equal(expected.Bodies, actual.Bodies);
|
||||
Assert.Equal(expected.Fields, actual.Fields);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,300 +0,0 @@
|
|||
using Ymir.Core;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
|
||||
namespace Ymir.Tests;
|
||||
|
||||
public sealed class YmirSimulatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void StepIntegratesDynamicBodies()
|
||||
{
|
||||
var result = Step(new PhysicsBody("projectile", Vec2.Zero, new Vec2(10.0f, 0.0f), 0.1f, 1.0f));
|
||||
|
||||
Assert.Equal(1.0f, result.World.Bodies[0].Position.X, precision: 5);
|
||||
Assert.Equal(0.0f, result.World.Bodies[0].Position.Y, precision: 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RadialFieldAcceleratesBodyTowardWell()
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
var request = new SimulationStepRequest(
|
||||
1.0f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
new[] { new PhysicsBody("ship", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f) },
|
||||
new[] { new RadialField("well", new Vec2(10.0f, 0.0f), 10.0f, 20.0f) }));
|
||||
|
||||
var result = simulator.Step(request);
|
||||
|
||||
Assert.True(result.World.Bodies[0].Velocity.X > 0.0f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OverlappingCirclesEmitContactAndSeparate()
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
var request = new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
new[]
|
||||
{
|
||||
new PhysicsBody("a", new Vec2(0.0f, 0.0f), new Vec2(1.0f, 0.0f), 1.0f, 1.0f),
|
||||
new PhysicsBody("b", new Vec2(1.5f, 0.0f), new Vec2(-1.0f, 0.0f), 1.0f, 1.0f)
|
||||
},
|
||||
Array.Empty<RadialField>()));
|
||||
|
||||
var result = simulator.Step(request);
|
||||
|
||||
var contact = Assert.Single(result.Contacts);
|
||||
Assert.Equal("a", contact.BodyA);
|
||||
Assert.Equal("b", contact.BodyB);
|
||||
Assert.True(contact.Penetration > 0.0f);
|
||||
Assert.True(result.World.Bodies[0].Position.X < 0.1f);
|
||||
Assert.True(result.World.Bodies[1].Position.X > 1.4f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ContactOrderingIsStableByBodyId()
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
var request = new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
new[]
|
||||
{
|
||||
new PhysicsBody("zeta", new Vec2(0.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f),
|
||||
new PhysicsBody("alpha", new Vec2(1.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f)
|
||||
},
|
||||
Array.Empty<RadialField>()));
|
||||
|
||||
var contact = Assert.Single(simulator.Step(request).Contacts);
|
||||
|
||||
Assert.Equal("alpha", contact.BodyA);
|
||||
Assert.Equal("zeta", contact.BodyB);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExplicitWorldSessionRetainsBox3DStateAcrossSteps()
|
||||
{
|
||||
using var session = new YmirWorldSession();
|
||||
var first = session.Step(new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
[new PhysicsBody("ship", Vec2.Zero, new Vec2(10.0f, 0.0f), 0.5f, 1.0f)],
|
||||
[])));
|
||||
|
||||
var second = session.Step(new SimulationStepRequest(0.1f, first.World));
|
||||
|
||||
Assert.Equal(2.0f, second.World.Bodies[0].Position.X, precision: 5);
|
||||
Assert.Equal(0.2f, second.World.Time, precision: 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Box3DOwnsPlanarOrientationAndConsumesTorqueOnce()
|
||||
{
|
||||
using var session = new YmirWorldSession();
|
||||
var first = session.Step(new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(
|
||||
0.0f,
|
||||
[new PhysicsBody(
|
||||
"ship",
|
||||
Vec2.Zero,
|
||||
Vec2.Zero,
|
||||
0.5f,
|
||||
1.0f,
|
||||
Direction: new Vec2(0.0f, 1.0f),
|
||||
Torque: 1.0f)],
|
||||
[])));
|
||||
|
||||
var firstBody = first.World.Bodies[0];
|
||||
Assert.NotNull(firstBody.Direction);
|
||||
Assert.NotEqual(0.0f, firstBody.AngularVelocity);
|
||||
Assert.Equal(0.0f, firstBody.Torque);
|
||||
|
||||
var second = session.Step(new SimulationStepRequest(0.1f, first.World));
|
||||
Assert.Equal(firstBody.AngularVelocity, second.World.Bodies[0].AngularVelocity, precision: 4);
|
||||
Assert.NotEqual(firstBody.Direction, second.World.Bodies[0].Direction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CircleCastUsesPinnedBox3DEdgeSemantics()
|
||||
{
|
||||
var result = YmirQueries.CastCircle(new CircleCastQueryRequest(
|
||||
Vec2.Zero,
|
||||
new Vec2(1.0f, 0.0f),
|
||||
10.0f,
|
||||
1.0f,
|
||||
[new PhysicsBody("target", new Vec2(30.0f, 0.0f), Vec2.Zero, 20.0f, 1.0f, IsStatic: true)]));
|
||||
|
||||
var hit = Assert.Single(result.Hits);
|
||||
Assert.Equal("target", hit.BodyId);
|
||||
Assert.InRange(hit.Distance, 8.99f, 9.01f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CircleOverlapUsesPinnedBox3DTangentSemantics()
|
||||
{
|
||||
var result = YmirQueries.OverlapCircle(new CircleOverlapQueryRequest(
|
||||
Vec2.Zero,
|
||||
1.0f,
|
||||
[new PhysicsBody("target", new Vec2(2.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f, IsStatic: true)]));
|
||||
|
||||
Assert.Equal("target", Assert.Single(result.Hits).BodyId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SoAStepProjectsBox3DStateIntoContractBuffers()
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
var world = new YmirSoAWorld
|
||||
{
|
||||
BodyIds = ["ship", "anchor"],
|
||||
PositionX = [0.0f, 10.0f],
|
||||
PositionY = [0.0f, 0.0f],
|
||||
VelocityX = [1.0f, 0.0f],
|
||||
VelocityY = [0.0f, 0.0f],
|
||||
Radius = [0.5f, 0.5f],
|
||||
Mass = [1.0f, 1.0f],
|
||||
DynamicMask = [1.0f, 0.0f],
|
||||
Restitution = [0.2f, 0.2f],
|
||||
FieldIds = ["well"],
|
||||
FieldPositionX = [10.0f],
|
||||
FieldPositionY = [0.0f],
|
||||
FieldStrength = [10.0f],
|
||||
FieldRadius = [20.0f]
|
||||
};
|
||||
|
||||
var result = simulator.Step(new SoASimulationStepRequest(1.0f, world));
|
||||
|
||||
Assert.True(result.World.PositionX[0] > 1.0f);
|
||||
Assert.Equal(10.0f, result.World.PositionX[1], precision: 5);
|
||||
Assert.Equal(1.0f, result.World.Time, precision: 5);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CultCacheStoreRoundTripsSoAWorldState()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"ymir-tests-{Guid.NewGuid():N}.cc");
|
||||
var recordsPath = $"{path}.records";
|
||||
|
||||
try
|
||||
{
|
||||
var world = YmirSoAWorld.FromWorld(new YmirWorld(
|
||||
2.0f,
|
||||
new[] { new PhysicsBody("ship", new Vec2(1.0f, 2.0f), new Vec2(3.0f, 4.0f), 0.5f, 1.0f, Direction: new Vec2(1.0f, 0.0f), AngularVelocity: 2.0f) },
|
||||
new[] { new RadialField("well", new Vec2(5.0f, 6.0f), 7.0f, 8.0f) }));
|
||||
|
||||
await YmirCultCacheStore.SaveWorldAsync(path, "test", world);
|
||||
var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test");
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
Assert.Equal(["ship"], loaded!.BodyIds);
|
||||
Assert.Equal(1.0f, loaded.PositionX[0], precision: 5);
|
||||
Assert.Equal(7.0f, loaded.FieldStrength[0], precision: 5);
|
||||
Assert.Equal(1.0f, loaded.DirectionX[0], precision: 5);
|
||||
Assert.Equal(2.0f, loaded.AngularVelocity[0], precision: 5);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
if (Directory.Exists(recordsPath))
|
||||
{
|
||||
Directory.Delete(recordsPath, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CultCacheStoreReadsV0WithDefaultAngularState()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"ymir-v0-tests-{Guid.NewGuid():N}.cc");
|
||||
var recordsPath = $"{path}.records";
|
||||
try
|
||||
{
|
||||
var world = YmirSoAWorld.FromWorld(new YmirWorld(
|
||||
2.0f,
|
||||
[new PhysicsBody("ship", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f)],
|
||||
[]));
|
||||
using (var cache = await CultCacheMessagePack.OpenAsync(
|
||||
path,
|
||||
new CultCacheOpenOptions { UseDirectoryStore = true, FlushOnDispose = true, StoreFlushOnDispose = true }))
|
||||
{
|
||||
await cache.UpsertAsync(
|
||||
YmirWorldStateDocumentV0.FromSoA("test", world),
|
||||
new CultRecordHandle<YmirWorldStateDocumentV0>(new CultRecordKey("ymir:world:test")));
|
||||
await cache.FlushAsync();
|
||||
}
|
||||
|
||||
var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test");
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
loaded!.Validate();
|
||||
Assert.Equal(0.0f, loaded.DirectionX[0]);
|
||||
Assert.Equal(1.0f, loaded.DirectionY[0]);
|
||||
Assert.Equal(0.0f, loaded.AngularVelocity[0]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
if (Directory.Exists(recordsPath)) Directory.Delete(recordsPath, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CultCacheV2PreservesBox3DBodyProfile()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"ymir-v2-tests-{Guid.NewGuid():N}.cc");
|
||||
var recordsPath = $"{path}.records";
|
||||
try
|
||||
{
|
||||
var world = YmirSoAWorld.FromWorld(new YmirWorld(
|
||||
3.0f,
|
||||
[new PhysicsBody("payload", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f) with
|
||||
{
|
||||
IsKinematic = true,
|
||||
IsBullet = true,
|
||||
ParticipatesInFields = false,
|
||||
CollisionCategoryBits = 4,
|
||||
CollisionMaskBits = 2,
|
||||
CollisionGroupIndex = -11
|
||||
}],
|
||||
[]));
|
||||
|
||||
await YmirCultCacheStore.SaveWorldAsync(path, "test", world);
|
||||
var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test");
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
loaded!.Validate();
|
||||
var body = Assert.Single(loaded.ToWorld().Bodies);
|
||||
Assert.True(body.IsKinematic);
|
||||
Assert.True(body.IsBullet);
|
||||
Assert.False(body.ParticipatesInFields);
|
||||
Assert.Equal(4UL, body.CollisionCategoryBits);
|
||||
Assert.Equal(2UL, body.CollisionMaskBits);
|
||||
Assert.Equal(-11, body.CollisionGroupIndex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
if (Directory.Exists(recordsPath)) Directory.Delete(recordsPath, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static SimulationStepResult Step(params PhysicsBody[] bodies)
|
||||
{
|
||||
var simulator = new YmirSimulator();
|
||||
return simulator.Step(new SimulationStepRequest(
|
||||
0.1f,
|
||||
new YmirWorld(0.0f, bodies, Array.Empty<RadialField>())));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
param(
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Summary,
|
||||
|
||||
[string]$Claim,
|
||||
[string]$Question,
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$Tension,
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$ActionImplication,
|
||||
[string[]]$Tags = @("ymir", "repo-persona"),
|
||||
[string]$Kind = "project_seam",
|
||||
[string]$TargetKind = "repo",
|
||||
[string]$TargetId = "Ymir",
|
||||
[string]$TargetLabel = "Ymir",
|
||||
[string]$AnchorRef = "repo:Ymir",
|
||||
[string]$AnchorKind = "repo",
|
||||
[string]$AnchorSummary = "Ymir repository Persona state",
|
||||
[string]$StatePath = ".\.voidbot\state\ymir.cc"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Claim) -and [string]::IsNullOrWhiteSpace($Question)) {
|
||||
throw "Memory writes must include either -Claim or -Question."
|
||||
}
|
||||
|
||||
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
|
||||
$voidBotRoot = "E:\Projects\VoidBot"
|
||||
$coreDistPath = Join-Path $voidBotRoot "packages\core\dist\index.js"
|
||||
$identityPath = Join-Path $repoRoot ".voidbot\voice\identity.json"
|
||||
$resolvedStatePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $repoRoot $StatePath))
|
||||
|
||||
if (!(Test-Path $coreDistPath)) {
|
||||
throw "Missing VoidBot built core at $coreDistPath. Build VoidBot before mutating Persona state."
|
||||
}
|
||||
|
||||
$now = (Get-Date).ToUniversalTime().ToString("o")
|
||||
$memoryId = "ymir-" + ([guid]::NewGuid().ToString())
|
||||
$operation = @{
|
||||
operation = "record_short_term_memory"
|
||||
memory = @{
|
||||
memoryId = $memoryId
|
||||
kind = $Kind
|
||||
target = @{
|
||||
kind = $TargetKind
|
||||
id = $TargetId
|
||||
label = $TargetLabel
|
||||
}
|
||||
summary = $Summary
|
||||
createdAt = $now
|
||||
updatedAt = $now
|
||||
tags = $Tags
|
||||
anchorRefs = @(
|
||||
@{
|
||||
ref = $AnchorRef
|
||||
kind = $AnchorKind
|
||||
summary = $AnchorSummary
|
||||
}
|
||||
)
|
||||
evidenceRefs = @()
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($field in @("Claim", "Question", "Tension", "ActionImplication")) {
|
||||
$value = Get-Variable -Name $field -ValueOnly
|
||||
if (![string]::IsNullOrWhiteSpace($value)) {
|
||||
$operation.memory[$field.Substring(0, 1).ToLowerInvariant() + $field.Substring(1)] = $value
|
||||
}
|
||||
}
|
||||
|
||||
$operationJson = $operation | ConvertTo-Json -Depth 12 -Compress
|
||||
$operationJsonBase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($operationJson))
|
||||
|
||||
node -e @"
|
||||
const core = require(process.argv[1]);
|
||||
const fs = require('fs');
|
||||
const identity = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
const statePath = process.argv[3];
|
||||
const operation = JSON.parse(Buffer.from(process.argv[4], 'base64').toString('utf8'));
|
||||
|
||||
(async () => {
|
||||
await core.ensureVoidSelfStateIdentityProfile({
|
||||
canonicalPath: statePath,
|
||||
identity: {
|
||||
agentId: identity.id,
|
||||
publicName: identity.displayName,
|
||||
publicDescription: identity.description
|
||||
}
|
||||
});
|
||||
const result = await core.applyVoidSelfStateOperation({
|
||||
canonicalPath: statePath,
|
||||
identity: {
|
||||
agentId: identity.id,
|
||||
publicName: identity.displayName,
|
||||
publicDescription: identity.description
|
||||
}
|
||||
}, operation);
|
||||
console.log(JSON.stringify({ ok: true, memoryId: operation.memory.memoryId, result }, null, 2));
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
"@ $coreDistPath $identityPath $resolvedStatePath $operationJsonBase64
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
param(
|
||||
[string]$StatePath = ".\.voidbot\state\ymir.cc",
|
||||
[switch]$Json
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
|
||||
$voidBotRoot = "E:\Projects\VoidBot"
|
||||
$coreDistPath = Join-Path $voidBotRoot "packages\core\dist\index.js"
|
||||
$identityPath = Join-Path $repoRoot ".voidbot\voice\identity.json"
|
||||
$resolvedStatePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $repoRoot $StatePath))
|
||||
|
||||
if (!(Test-Path $coreDistPath)) {
|
||||
throw "Missing VoidBot built core at $coreDistPath. Build VoidBot before reading Persona state."
|
||||
}
|
||||
|
||||
node -e @"
|
||||
const core = require(process.argv[1]);
|
||||
const fs = require('fs');
|
||||
const identity = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
const statePath = process.argv[3];
|
||||
core.loadVoidSelfStateTypedDocuments({
|
||||
canonicalPath: statePath,
|
||||
identity: {
|
||||
agentId: identity.id,
|
||||
publicName: identity.displayName,
|
||||
publicDescription: identity.description
|
||||
}
|
||||
}).then((state) => {
|
||||
if (process.argv[4] === '--json') {
|
||||
console.log(JSON.stringify(state, null, 2));
|
||||
return;
|
||||
}
|
||||
console.log(core.renderVoidSelfStateSummary(state));
|
||||
}).catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
"@ $coreDistPath $identityPath $resolvedStatePath $(if ($Json) { "--json" } else { "" })
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
param(
|
||||
[string] $AetheriaRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..\Aetheria")).Path
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Read-Text([string] $relativePath) {
|
||||
$path = Join-Path $AetheriaRoot $relativePath
|
||||
if (-not (Test-Path -LiteralPath $path)) {
|
||||
throw "Required Aetheria file is missing: $relativePath"
|
||||
}
|
||||
|
||||
Get-Content -Raw -LiteralPath $path
|
||||
}
|
||||
|
||||
function Assert-Contains([string] $text, [string] $needle, [string] $message) {
|
||||
if (-not $text.Contains($needle)) {
|
||||
throw $message
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-NotContains([string] $text, [string] $needle, [string] $message) {
|
||||
if ($text.Contains($needle)) {
|
||||
throw $message
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $AetheriaRoot)) {
|
||||
throw "Aetheria root does not exist: $AetheriaRoot"
|
||||
}
|
||||
|
||||
$shieldManager = Read-Text "Assets\Scripts\Gameplay\ShieldManager.cs"
|
||||
$hullCollider = Read-Text "Assets\Scripts\Gameplay\HullCollider.cs"
|
||||
$projectile = Read-Text "Assets\Scripts\Gameplay\Weapons\Projectile.cs"
|
||||
$bridge = Read-Text "Assets\Scripts\Gameplay\Physics\AetheriaYmirPhysicsBridge.cs"
|
||||
|
||||
Assert-NotContains $shieldManager "OnCollisionEnter" "ShieldManager must not decide gameplay from Unity collision callbacks."
|
||||
Assert-NotContains $shieldManager "TakeHit(" "ShieldManager must not apply damage directly; damage policy is downstream of Ymir contact truth."
|
||||
Assert-NotContains $hullCollider "OnCollisionEnter" "HullCollider must not mutate entity physics from Unity collision callbacks."
|
||||
Assert-NotContains $hullCollider "SendHit(" "HullCollider must not expose a Unity-callback hit publisher as damage authority."
|
||||
|
||||
Assert-Contains $projectile "AetheriaYmirPhysicsBridge.Instance.TryStepProjectile" "Projectile travel and direct-hit discovery must route through the Ymir bridge."
|
||||
Assert-Contains $projectile "projectile killed instead of falling back to Unity physics" "Projectile must fail closed when Ymir stepping is unavailable."
|
||||
Assert-NotContains $projectile "OnCollisionEnter" "Projectile must not use Unity collision callbacks for hit discovery."
|
||||
Assert-NotContains $projectile "Physics." "Projectile must not use UnityEngine.Physics as hit-discovery authority."
|
||||
|
||||
Assert-Contains $bridge "public bool EnableProjectileCutover = true;" "Ymir projectile cutover must be enabled by default."
|
||||
Assert-Contains $bridge "YmirPhysicsQueries.Step(request)" "The Aetheria bridge must step projectiles through Ymir physics queries."
|
||||
Assert-Contains $bridge "result.contacts" "The Aetheria bridge must derive projectile hits from Ymir contact events."
|
||||
Assert-Contains $bridge "TryResolveTargetDaemonHull" "Ymir contact body ids must resolve to Aetheria hulls through the bridge seam."
|
||||
|
||||
$weaponAuthorityFiles = Get-ChildItem -LiteralPath (Join-Path $AetheriaRoot "Assets\Scripts\Gameplay\Weapons") -Filter "*.cs" -File
|
||||
foreach ($file in $weaponAuthorityFiles) {
|
||||
$text = Get-Content -Raw -LiteralPath $file.FullName
|
||||
if ($text.Contains("Physics.")) {
|
||||
throw "Weapon gameplay file still uses UnityEngine.Physics directly: $($file.FullName)"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Aetheria/Ymir cutover proof passed for $AetheriaRoot"
|
||||
Loading…
Reference in a new issue