DetPhysDocs日本語

Concepts

Deterministic synchronization

A DetPhys match does not send body positions to the other peer. Instead, both devices apply the same inputs in the same order and run the same computation. The physics (Box2D v3 for 2D, Box3D for 3D) gives bit-identical results on x64 and arm64 and with MSVC, clang and gcc — even with floating point — as long as the build settings are fixed (no fast-math, no automatic FMA contraction, its own trigonometry). DetPhys keeps this across engines: Unity, Godot and Unreal all call the same prebuilt core.

For this to hold, game code has to follow a few rules (4. Determinism rules). The most important one: everything that enters the simulation is an integer.

Ticks

  • The simulation advances one tick at a time. Defaults: 60 Hz (tick_hz 60), 4 substeps per tick, gravity (0, −10000) mm/s².
  • The state hash of a tick (64-bit FNV-1a) covers the tick number, the body count and, in body creation order, the raw float bits of position (x, y), rotation (cos, sin), velocity (vx, vy) and angular velocity w (detphys_world_hash; in 3D position 3, quaternion 4, velocity 3 and angular velocity 3 with detphys3d_world_hash). If two peers have the same hash, they have the same state.
  • Body IDs are serial numbers in creation order (from 0) within a world. Removed bodies keep their ID; IDs are never reused.

Inputs and game state

  • An input is a fixed-length list of int32 words decided by the game: 1–64 words per turn in turn-based play, 1–16 words per peer per tick in real time. Examples: stacking uses [drop x (mm), angle (mrad)]; push uses [move −100..100, button bits].
  • Engine floats (mouse position, stick values) are turned into integers once, on the device that produces the input, before they are passed in. Both devices receive the integers, so the quantization error is the same on both.
  • The game state (state words) is a list of int32 words owned by the rule (0–64 words): score, timers, turn counters. It is hashed and rolled back.
  • The rule's settings (params) are copied when the session is created and checked against the other peer when connecting. Peers with different settings, shapes, shape order or session id do not connect (since rt version 7 / turn version 9 you can tell which part differs; see 5. Troubleshooting desyncs).

Rules

A rule is the game code that applies inputs to the world: a set of callbacks. The core calls them in the same order and the same number of times on every peer.

Turn-based (detphys_turn_rule)Real-time (detphys_rt_rule)
Startbegin_match (each match, on an empty world)begin (once)
Inputcheck_input (optional) → apply_inputapply_inputs (both peers' inputs side by side)
Every tickafter_tick (continue / end the turn / end the match)after_tick
Endend_turn (decides the next mover)–
Prediction–predict (optional; by default the last received input is repeated)

There are built-in rules (both inside the core; you create a session without writing callbacks):

  • Turn-based stacking (detphys_turn_create_stack_ex): players take turns dropping shapes onto a pile. The rule picks the next shape from the seed, match and turn numbers.
  • Real-time push (detphys_rt_create_push): two players push boxes and concave shapes. A moving field (spinning gear, sliding platform, lift) can be added; the session owns its kinematic table. Unity (DetPhysRtSession.CreatePush) and Godot (DetPhysRtSession.create_push) call this same rule, so Unity and Godot can play each other. Body IDs come from detphys_rule_push_get_layout.

In Unity, rules can be written in C# (DetPhysRtRule, works on Mono and IL2CPP; the sample's CSharpPushRule is the push rule written in C#, gives the same results as the core's rule and connects to it). In C++, detphys::make_rule in detphys_rule.hpp makes a turn-based rule from member functions.

Turn-based

One turn:

  1. The mover submits an input (detphys_turn_submit_words). It is sent to the other peer.
  2. Both peers simulate with the same input. The rule's after_tick decides when the turn ends (without it: when all dynamic bodies sleep). The limit is max_ticks_per_turn (default 900 ticks = 15 s at 60 Hz).
  3. The peers exchange the state hash at the end of the turn (hash check).
  4. On a mismatch the host (peer 0) is the reference: it sends a full snapshot and the guest's state is replaced (resync).
  • Rejoin: if the guest app crashes, create the session again with the same settings and poll. The host sends its current state and the match continues from the same turn.
  • Host restart: the guest keeps the state from the start of every turn and sends it to the host's new session; both continue from the start of that turn. If the host crashed during its own turn, the host plays that turn again.
  • After peer_timeout_ms (default 5000) without packets the session reports PEER_LOST but keeps waiting. The app decides whether to give up.
  • Traffic: about 150–190 bytes per turn for both peers together (stacking).

From an engine (built-in stacking):

using DetPhys;

// Both devices: the same settings, rule and shapes (in the same order)
var settings = DetPhysTurnSettings.Default;
settings.sessionId = 0x7E57;
var rules = DetPhysStackRules.Default;
rules.nextSeed = matchSeed;
var link = isHost ? DetPhysUdpLink.Connect("192.168.1.7", 47200) : DetPhysUdpLink.Listen(47200);
// 0 = host (the reference on a desync), 1 = guest
var session = DetPhysTurnSession.CreateStack(settings, rules, shapes, isHost ? 0 : 1, link.Endpoint);

// Every frame (Update)
var state = session.Poll(ticksToShowThisFrame);
// Your turn
if (state == DetPhysTurnState.WaitLocalInput && dropped)
{
    // Send integers: x in mm, angle in mrad
    session.Submit(DetPhysStack.Input(DetPhysStack.MetersToMm(x), DetPhysStack.RadiansToMrad(angle)));
}
// The turn's result (the same hash on both peers)
while (session.TryGetResult(out var r))
    Debug.Log($"turn {r.Turn} hash {DetPhysHash.ToHex(r.AgreedHash)}");
var m := DetPhysStackMatch.new()
# Both devices: the same settings, rule and shapes (in the same order)
m.settings = DetPhysTurnSettings.new()
m.settings.session_id = 0x7E57
m.rules = DetPhysStackRules.new()
m.rules.seed = match_seed
m.shape_files = shape_files
add_child(m)
# Your turn
m.local_turn.connect(func(turn, shape):
	# Send integers: x in mm, angle in mrad
	m.submit(PackedInt32Array([roundi(aim_x * 1000.0), roundi(aim_angle * 1000.0)]))
)
# The turn's result (the same hash on both peers)
m.turn_finished.connect(func(r): print(DetPhys.hash_hex(r["agreed_hash"])))
# 0 = host (the reference on a desync), 1 = guest
m.start(0, DetPhysLink.udp_connect("192.168.1.7", 47200))
using DetPhys;
using Godot;

// Both devices: the same settings, rule and shapes (in the same order)
DetPhysTurnSession.SampleRules(matchSeed, false, out var desc, out var next);
var link = isHost ? DetPhysUdpLink.Connect("192.168.1.7", 47200) : DetPhysUdpLink.Listen(47200);
// 0 = host (the reference on a desync), 1 = guest
var session = DetPhysTurnSession.CreateStack(0x7E57, isHost ? 0 : 1, desc, next, shapes, link.Transport, link);

// Every frame (_Process)
int state = session.Poll(4);
// 1 = waiting for this peer's input
if (state == 1 && dropped)
{
    // Send integers: x in mm, angle in mrad
    session.Submit(new[] { Mathf.RoundToInt(aimX * 1000f), Mathf.RoundToInt(aimAngle * 1000f) });
}
// The turn's result (the same hash on both peers)
while (session.TryGetResult(out var r))
    GD.Print($"turn {r.Native.turn} hash {DetPhysHash.Hex(r.Native.agreedHash)}");
#include "DetPhysMatchComponents.h"
#include "DetPhysLibrary.h"
#include "DetPhysLink.h"

// Header: UPROPERTY() TObjectPtr<UDetPhysStackMatchComponent> Stack;
//         UFUNCTION() void HandleLocalTurn(int32 Turn, int32 Shape);
AMyStackActor::AMyStackActor()
{
    Stack = CreateDefaultSubobject<UDetPhysStackMatchComponent>(TEXT("Stack"));
}

void AMyStackActor::BeginPlay()
{
    Super::BeginPlay();
    // Both devices: the same settings, rule and shapes (in the same order)
    Stack->Settings.SessionId = 0x7E57;
    Stack->Rules.Seed = MatchSeed;
    Stack->ShapeFiles = ShapeFiles;
    Stack->OnLocalTurn.AddDynamic(this, &AMyStackActor::HandleLocalTurn);
    // 0 = host (the reference on a desync), 1 = guest
    Stack->StartWithLink(0, UDetPhysLink::UdpConnect(this, TEXT("192.168.1.7"), 47200));
}

// Your turn
void AMyStackActor::HandleLocalTurn(int32 Turn, int32 Shape)
{
    // Send integers: x in mm, angle in mrad
    Stack->Submit({ UDetPhysLibrary::QuantizeMm(AimX), UDetPhysLibrary::QuantizeMrad(AimAngle) });
}
Add a DetPhys Stack Match component to an actor (set Settings, Rules and Shape Files the same on both peers)
Event BeginPlay → Udp Connect → Start With Link (Local Peer 0, Link)
On Local Turn (Turn, Shape)
  → Make Array (Quantize Mm (aim x), Quantize Mrad (angle)) → Submit
On Turn Finished (Result) → show the Result's Agreed Hash

Real time (rollback)

Rollback (zero input delay)12345678910tickYour inputPeer inputWorldArrivedPredicted (repeats the last input that arrived)At tick 10 the input for tick 6 arrives and differsConfirmedRecompute ticks 6 to 10Restore the state of tick 5

Every frame, pass your input and call detphys_rt_advance once. Ticks whose remote input has not arrived yet are run with a prediction.

  • When the real input differs from the prediction, the session rolls back to the state before that tick and re-simulates up to the current tick. That is why your own actions show at once even with zero input delay.
  • A tick computed with both peers' real inputs is confirmed. The hash (lower 32 bits) of confirmed ticks is sent to the other peer and checked (by default every tick, each hash carried in two packets).
  • On a mismatch the host sends a full snapshot and the guest's state is replaced (the epoch goes up by one; hashes are only compared within the same epoch).
  • The session runs ahead on predictions by at most the prediction window N (max_prediction, default 10, 0–60) ticks. Beyond that it waits (DETPHYS_RT_STALLED).
  • A peer that is one tick or more ahead of the other waits one frame (time sync, DETPHYS_RT_SYNC_WAIT).
  • Draw from detphys_rt_world (the current, predicted state). Positions can jump on a rollback; smoothing the visuals is fine (it does not affect results).
  • Rule callbacks run again for the same tick on every rollback. Keep the game state in the world and in the state words only (anything else is not rolled back). Do not play sounds or effects while ctx->resimulating is 1.
  • Traffic: 32–48 bytes per tick one way (without UDP / IP headers). Unconfirmed inputs are repeated in each packet, which makes losses harmless.

Return values of detphys_rt_advance:

ValueMeaningYour input
DETPHYS_RT_ADVANCEDAdvanced one tickAccepted
DETPHYS_RT_STALLEDWaiting: the prediction window would be exceededNot accepted (pass the input for the same tick next frame)
DETPHYS_RT_SYNC_WAITToo far ahead of the other peer; resting one frameNot accepted
DETPHYS_RT_DELAY_WAITAutomatic input delay raised the delay by one (the tick did not advance)Accepted

Always pass the input for the tick given by detphys_rt_next_input_tick.

From an engine (built-in push; the engine layer handles the detphys_rt_advance results and the clock):

using DetPhys;

// Both devices: the same settings, rule and shapes (in the same order)
var settings = DetPhysRtSettings.Default;   // input delay 0, prediction 10
settings.sessionId = 0x16;
var push = new DetPhysPushSettings { seed = matchSeed };
var link = isHost ? DetPhysUdpLink.Connect("192.168.1.7", 47500) : DetPhysUdpLink.Listen(47500);
// 0 = host (the reference on a desync), 1 = guest
var session = DetPhysRtSession.CreatePush(settings, push, shapes, isHost ? 0 : 1, link.Endpoint);
var driver = new DetPhysRtDriver(settings.world.tickHz);
var input = new int[DetPhysPush.InputWords];

// Every frame (Update)
session.Poll();
for (int k = driver.Due(DetPhysRtSession.NowUs); k > 0; k--)
{
    // Inputs are integers before they go in
    input[0] = DetPhysPush.QuantizeMove(Input.GetAxisRaw("Horizontal"));
    input[1] = jump ? DetPhysPush.ButtonJump : 0;
    session.Advance(input, out var frame);
}
while (session.TryGetConfirmed(out var c))
{
    // Confirmed ticks (the same hash on both peers): c.tick, c.hash
}
// Draw (the current state, predictions included)
int n = session.World.ReadBodies(views);
# The real-time push node
var rt := DetPhysRtMatch.new()
# Both devices: the same settings, rule and shapes (in the same order)
rt.shape_files = shape_files
rt.rules = DetPhysPushRules.new()
add_child(rt)
# Inputs are integers before they go in
rt.input_source = func(tick: int) -> PackedInt32Array:
	var move := DetPhysRtMatch.quantize_move(Input.get_axis("left", "right"))
	var jump := 1 if Input.is_action_pressed("jump") else 0
	return PackedInt32Array([move, jump])
# Confirmed ticks (the same hash on both peers)
rt.tick_confirmed.connect(func(tick, hash, flags): print(tick, " ", DetPhys.hash_hex(hash)))
# 0 = host (the reference on a desync), 1 = guest
rt.start(0, DetPhysLink.udp_connect("192.168.1.7", 47500))
using DetPhys;
using Godot;

// Both devices: the same settings, rule and shapes (in the same order)
var push = DetPhysPush.Desc(seed: matchSeed);
var link = isHost ? DetPhysUdpLink.Connect("192.168.1.7", 47500) : DetPhysUdpLink.Listen(47500);
// 0 = host (the reference on a desync), 1 = guest
var session = DetPhysRtSession.CreatePush(push, isHost ? 0 : 1, shapes, link.Transport, link);
var input = new int[DetPhysPush.InputWords];
ulong nextUs = DetPhysTurnSession.NowUs;

// Every frame (_Process)
ulong now = DetPhysTurnSession.NowUs;
session.PollAt(now);
// Once per tick of a 60 Hz clock (at most 3 per frame when behind)
for (int k = 0; k < 3 && now >= nextUs; k++, nextUs += 1_000_000 / 60)
{
    // Inputs are integers before they go in
    input[0] = Mathf.Clamp(Mathf.RoundToInt(Input.GetAxis("left", "right") * 100f), -100, 100);
    input[1] = Input.IsActionPressed("jump") ? 1 : 0;
    session.AdvanceAt(now, input);
}
while (session.TryGetConfirmed(out var c))
{
    // Confirmed ticks (the same hash on both peers): c.tick, c.hash
}
#include "DetPhysMatchComponents.h"
#include "DetPhysLibrary.h"
#include "DetPhysLink.h"

// Header: UPROPERTY() TObjectPtr<UDetPhysRtMatchComponent> Match;
//         UFUNCTION() void HandleTick(int64 Tick, int64 Hash, int32 Flags);
AMyMatchActor::AMyMatchActor()
{
    Match = CreateDefaultSubobject<UDetPhysRtMatchComponent>(TEXT("Match"));
}

void AMyMatchActor::BeginPlay()
{
    Super::BeginPlay();
    // Both devices: the same settings, rule and shapes (in the same order)
    Match->Settings.SessionId = 0x16;
    Match->Rules.Seed = MatchSeed;
    Match->ShapeFiles = ShapeFiles;
    // Inputs are integers before they go in
    Match->InputSource = [this](int64 InTick, TArray<int32>& Out)
    {
        Out = UDetPhysLibrary::MakePushInput(UDetPhysLibrary::QuantizeMove(MoveAxis), bJump, bDash);
    };
    Match->OnTickConfirmed.AddDynamic(this, &AMyMatchActor::HandleTick);
    // 0 = host (the reference on a desync), 1 = guest
    Match->StartWithLink(0, UDetPhysLink::UdpConnect(this, TEXT("192.168.1.7"), 47500));
}

// Confirmed ticks (the same hash on both peers)
void AMyMatchActor::HandleTick(int64 Tick, int64 Hash, int32 Flags)
{
    UE_LOG(LogTemp, Log, TEXT("tick %lld hash %llx"), Tick, Hash);
}
Add a DetPhys Rt Match component to an actor (set Settings, Rules and Shape Files the same on both peers)
Event BeginPlay
  → Udp Connect (Address 192.168.1.7, Port 47500) → Start With Link (Local Peer 0, Link)
Event Tick
  → Make Push Input (Quantize Move (horizontal axis), Jump, Dash) → Set Local Input
On Tick Confirmed (Tick, Hash, Flags) → Print String

Zero input delay and automatic input delay

  • With an input delay (input_delay, 0–30, default 0) of d, the input passed in a frame is applied at tick "current + 1 + d". A larger d means fewer mispredictions and rollbacks, but actions show d ticks later.
  • With a distant peer, zero delay means more waiting (STALLED). Measured example (two peers in one process, 135±15 ms one way, 20% loss, 3600 ticks): 235 waits with delay 0, 8 with delay 2, none with delay 4.
  • With automatic input delay (detphys_rt_set_auto_delay, off by default) the host chooses a delay D from the round trip time and both peers switch to it at an agreed tick X.
    • How D is chosen: one way = RTT / 2 + jitter × 1 (jitter_weight_milli 1000). D = ceil(one way / tick length) − rollback_ticks (default N/2 + 1 = 6), clamped to 0–6.
    • It switches after wanting to raise for 500 ms or to lower for 3000 ms. Raising accepts inputs without advancing (DELAY_WAIT); lowering advances two ticks in one frame.
    • No input is ever dropped, so confirmed results do not depend on the delay. The guest follows the host only if it has turned the feature on too.
    • Measured example: between a PC and a Galaxy S9 (120–150 ms one way injected) both peers went to delay 3, and waits dropped from 75 / 76 to 8 / 6.

Rejoin (real time)

Each peer has a link id. When the other peer's link id changes (it restarted), the surviving peer sends its state at its confirmed tick T together with both peers' inputs for T. The restarted peer replaces its state and continues from T. The app only has to create the session again, with the same settings, on the side that crashed. The frame where the state is replaced has DETPHYS_RT_FRAME_REJOIN set; rebuild visuals and sounds from the current state there. If both peers crash at once, the match starts again at tick 0.

Snapshots

For rollback, resync and rejoin, the world state is copied into a buffer owned by the caller (the core does not allocate images).

KindContentsCan be restored intoUsed by default for
dyn (DETPHYS_SNAPSHOT_DYNAMIC)Only the state that a step changes. Shapes and static bodies come from a base (a full image) the world keepsThe same world onlyThe real-time snapshot ring (N + 1 entries)
full (DETPHYS_SNAPSHOT_FULL)EverythingAnother world with the same shapes registered in the same order (also between x64 and arm64 as is)The state sent on resync and rejoin; the guest's per-turn checkpoint in turn-based play
  • The core takes a new base by itself (on the first dyn after bodies or shapes are created or removed, or a pose is set directly). It keeps 4 bases by default (snapshot_base_slots). When a base is missing, the real-time ring falls back to full automatically.
  • In turn-based play shapes are added every turn, so the guest's per-turn checkpoint is full by default (detphys_turn_set_checkpoint_kind selects dyn; that is lighter for games that only move the same bodies).
  • Sizes (2D, 200 concave dynamic bodies all awake): dyn about 0.55–0.7 MB, full about 1 MB (with baked shapes dyn 1.5 MB, full 2.1 MB).

Concave shapes and the baker

A Box2D shape is a convex polygon of up to 8 vertices. DetPhys represents a concave shape as a set of convex polygons all attached to one body. The decomposition is done ahead of time by the baker and shipped as integer-mm vertex data (.dnshape), so nothing is decomposed at run time on each device, and every device has the same data.

Bake shapes in the editor:

EngineHowResultUse it
UnityWindow > DetPhys > Shape Baker (pick a texture or a sprite, adjust the settings while watching the preview, then save), or right-click images > DetPhys > Bake Concave Shapea .dnshape.bytes assetthe Shapes of a match component
Godotthe DetPhys Shapes dock (pick an image or press Use Selected, adjust the settings while watching the preview, then Save or Add to Selected Node), right-click images in the FileSystem dock > Bake DetPhys Shape (Godot 4.4 or newer), or Project > Tools > DetPhys: Bake Selected Imagesa .dnshape file next to the image (shown in the FileSystem dock, included in exports, load() gives a DetPhysShape)the shape_files of DetPhysStackMatch / DetPhysRtMatch
Unrealright-click textures in the Content Browser > Bake DetPhys Shapea DetPhys Shape asset <Texture>_Shape next to the texture. Change Bake Settings or Source Texture in its Details panel and it is baked again; reimporting the texture also bakes it againthe Shape Assets of a match component, or Asset->Shape for a session

Nothing needs to be enabled: the baker is part of the editor integration. The same image and settings give the same bytes in all three editors. The baker:

  1. Traces the outline from the image's alpha (inside = 128 or more by default; 128 px per m by default, or the sprite's Pixels Per Unit).
  2. Simplifies it with Douglas-Peucker (tolerance Simplify, default 1 px). Vertices that Box2D would drop (closer than 11 mm to the line through their neighbours) are removed first.
  3. Splits it into convex polygons: Steiner (default; adds points on long straight edges to need fewer pieces) or Hertel-Mehlhorn (never adds vertices). Neither leaves gaps or overlaps.
  4. Writes integer mm into a .dnshape (v1, with a checksum). The origin is the centre of the image.

The baker runs in the native core and uses only integer arithmetic, so the same image and settings give the same bytes on every machine. PNG files are read from disk (Unity: Read/Write, compression and Max Size; Godot: the import settings; Unreal: compression and size settings of the texture do not change the shape). In Unreal, when the PNG file has changed or moved since the import, the texture's own pixels are used.

  • Use: register the .dnshape bytes in the session settings' meshes (numbered 0, 1, … in order) or with detphys_world_add_mesh, then attach them with the shape kind DETPHYS_SHAPE_MESH and the number. Register the same shapes in the same order on both peers.
  • Accuracy: 4–11 mm maximum distance from the outline (the 8 sample shapes, 128 px per m, 1 px). Details finer than about 1 cm disappear; holes are filled.
  • The cost grows almost linearly with the number of convex polygons. The 8 sample shapes average 9.4 per shape (steiner). A larger tolerance gives fewer pieces (67 for the 8 shapes at 2 px).

Moving concave shapes

Spinning gears, platforms going back and forth, lifts and the like are kinematic bodies that move as functions of the tick (detphys_kinematic.h).

  • Motions carry no state, so after a rollback they are rebuilt from the tick (the snapshot values and the rebuilt values are bit-identical).
  • Every tick the body is snapped to the function's pose and given the velocity that reaches the next tick's pose. Box2D carries riders with that velocity, so they do not slide or jitter.
  • Motions (detphys_motion_desc, integers in mm, mrad, mrad/s and ticks):
PathMotion
DETPHYS_PATH_FIXEDDoes not move (only its own spin spin_mrad_s: gears, fans)
DETPHYS_PATH_PINGPONGBack and forth between A and B (one way takes period_ticks)
DETPHYS_PATH_ORBITAround a circle
DETPHYS_PATH_POINTSFollows points (with an angle per point; loop or back and forth; the same point twice in a row = a stop)
DETPHYS_PATH_CALLBACKYour callback computes the pose from the tick (with integers only)

Every path can add its own spin spin_mrad_s and a time offset phase_ticks. By default each segment eases to speed 0 at its ends (DETPHYS_EASE_SMOOTH), so riders are not thrown off.

  • Fast motion: Box2D looks for contacts between moving bodies once at the start of a tick (about 2 cm ahead). Only on ticks where the fastest point moves more than subtick_move_mm (default 20 mm), the world is stepped in up to max_subticks (default 4) pieces (split). With the defaults, small bodies (4–15 cm) did not tunnel up to 34 m/s (gear), 180 m/s (platform), 43 m/s (fan) and 18 m/s (lift) at the fastest point. A split tick costs that many steps.
  • In a session, pass the table to the session (detphys_rt_create_kinematic, detphys_turn_create_rule_kinematic; in Unity, return UsesKinematic => true from the rule). The order inside a tick is "update → apply_inputs → step with splitting → after_tick", the same during re-simulation.
  • Moving concave shapes in 3D worlds are described in Moving concave shapes (3D) (detphys3d_kinematic.h).

3D

3D worlds (detphys3d.h, Box3D) run in the same sessions as 2D. The concepts (ticks, inputs, prediction, rollback, hash checks, resync, rejoin, automatic delay) are all the same.

detphys_rt_config c; detphys3d_world_desc w;
detphys_rt_config_default3d(&c, &w);          // snapshots FULL, default world (60 Hz, 4 substeps, gravity −10000 mm/s²)
c.local_peer = 0;                            // other settings as in 2D
detphys_rt_rule3d r = { sizeof r, 3, 0 };     // 3 input words, 0 state words
r.begin = my_begin;                          // register hulls, create the floor and players (with detphys3d_world_*)
r.apply_inputs = my_apply;
detphys_rt_session* s = detphys_rt_create3d(&c, &w, &r, &transport);   // turn-based: detphys_turn_create_rule3d
// every frame: poll → advance → next_confirmed as in 2D; draw with detphys3d_world_read_transforms(detphys_rt_world3d(s), ...)
  • Shapes: boxes, spheres, capsules, convex hulls. A hull is built from integer points and registered with detphys3d_world_add_hull, then attached by index (the same contents give the same index). Register hulls in begin (turn-based: begin_match) in the same order on both peers; their contents are part of the config check.
  • Orientations are integer quaternions (qx, qy, qz, qw). Any length works; the core normalizes them. Pass an engine float quaternion multiplied by DETPHYS3D_QUAT_ONE (2^30) and rounded. No trigonometry is used.
  • Snapshots default to full (in 3D a dyn snapshot is only 6–9% smaller).
  • State sent to the other peer (resync, rejoin) is a transfer (detphys3d_world_transfer_*): the full image plus the shape registry contents and the hull table. If the registry order differs, the receiver rebuilds it before restoring. 190–260 KB for 115 bodies.
  • 1–32 workers (default 1). The pool can be the core's own (default; faster than Box3D's built-in one on Android), Box3D's built-in one, or the engine's job system. The count does not change the hash.
  • The desync debugger turns on with the same settings as in 2D. Reports use the 3D fields (x y z, qx–qw, vx vy vz, wx–wz) (5. Troubleshooting desyncs).
  • Not available yet: joints, sensors, contact events, ray queries. What each engine offers in 3D is in 1. Overview.

In Godot, 3D rules can also be written in GDScript. Derive from DetPhysRtRule3D (turn based: DetPhysTurnRule3D), write the callbacks and pass the rule to DetPhysRtSession.create3d (DetPhysTurnSession.create3d). Values passed to the world are Dictionaries of integers (see the Godot section of 7. API reference).

extends DetPhysRtRule3D   # two players roll balls

func _init() -> void:
	input_words = 2          # [x -100..100, z -100..100]
	state_words = 0
	rule_id = 0x42414C4C00000001
	params = PackedInt32Array([300])   # ball radius in mm

func _begin(c: DetPhysRtContext3D) -> void:
	var w := c.world
	w.add_body({"type": DetPhysRuleWorld3D.DETPHYS3D_BODY_STATIC, "y_mm": -500,
		"shape": {"kind": DetPhysRuleWorld3D.DETPHYS3D_SHAPE_BOX, "half_x_mm": 8000, "half_y_mm": 500, "half_z_mm": 8000}})
	for p in 2:
		w.add_body({"x_mm": -3000 + 6000 * p, "y_mm": params[0],
			"shape": {"kind": DetPhysRuleWorld3D.DETPHYS3D_SHAPE_SPHERE, "radius_mm": params[0]}})

func _apply_inputs(c: DetPhysRtContext3D, inputs: PackedInt32Array) -> void:
	for p in 2:
		c.world.apply_force(1 + p, inputs[p * 2] * 2000, 0, inputs[p * 2 + 1] * 2000)

Moving concave shapes (3D)

In 3D too, spinning gears, turntables, platforms that go back and forth with holds, lifts, orbiting platforms and swaying platforms can be kinematic bodies that move as functions of the tick (detphys3d_kinematic.h, version 1). The ideas are the same as for 2D moving concave shapes. Motions carry no state, so after a rollback they are rebuilt from the tick. Every tick the body is snapped to the function's pose and given the velocity and angular velocity that reach the next tick's pose. Only fast ticks are split.

  • Motions (detphys3d_motion_desc, integers in mm, mrad, mrad/s and ticks; orientations are integer quaternions):
PathMotion
DETPHYS3D_PATH_FIXEDDoes not move (only its spin spin_mrad_s around the spin axis: gears, turntables)
DETPHYS3D_PATH_PINGPONGBack and forth between A and B (one way takes period_ticks). Stops for hold_a_ticks at A and hold_b_ticks at B. Move it up and down for a lift
DETPHYS3D_PATH_ORBITGoes around a center, around the spin axis, at orbit_mrad_s. The orientation comes from the spin only (with spin 0 it circles without turning)
DETPHYS3D_PATH_POINTSFollows points (with an angle around the spin axis per point; loop or back and forth; the same point twice in a row = a stop; e.g. a lift with three or more floors)
DETPHYS3D_PATH_CALLBACKYour callback computes the position [µm] and an integer quaternion from the tick (with integers only)
  • Orientation is the initial orientation (qx–qw) turned by a(t) around the spin axis (axis_x–axis_z; 0, 0, 0 = the y axis). a(t) is spin × time; POINTS adds the point angles.
  • Every path except CALLBACK can add a spin and a time offset phase_ticks. Segments ease to speed 0 at their ends by default (DETPHYS_EASE_SMOOTH).
  • Shapes: create the body with detphys3d_kinematic_add, then add hulls and boxes with detphys3d_world_add_shape to build a convex compound. Nothing is approximated.
  • Fast rotation still ends each tick at the function's orientation: Box3D's angular speed limit is lifted and the angular velocity is corrected to its integration (2.0e-6 rad after 120 ticks at 40 rad/s).
  • Splitting uses the same settings as 2D (subtick_move_mm 20 mm, max_subticks 4). The fastest point is measured with the bounding radius, so a large turntable with rim walls splits more often.
  • Sessions: pass the table with detphys_rt_create3d_kinematic or detphys_turn_create_rule3d_kinematic, and add / bind inside the rule's begin (begin_match). The table's contents are part of the config check.
  • In turn-based play a moving kinematic body keeps the world from settling, so end the turn in after_tick by tick count or similar (4. Determinism rules, rule 12).
  • Verified: a spinning concave gear and a scene with back-and-forth, lift, orbiting and swaying platforms (900 ticks each) matched on every tick on five PC builds and a Galaxy S9, with no tunneling. Bodies on stopped platforms do not jitter.
  • The costs are in 6. Performance.

Bodies on a spinning platform slide outward

In 3D, bodies on a spinning kinematic body (a gear, a turntable) slowly slide outward even with enough friction (about 0.2 m in 10 s at 0.3 rad/s). This comes from how Box3D solves contacts. It slides the same way on every device, so determinism is not affected.

  • Give platforms that spin with bodies on them rims or dividers.
  • For platforms the player rides, add the platform's velocity at that spot (angular velocity × distance from the axis) in the movement code (the rule's apply_inputs).
  • Back-and-forth platforms, lifts and platforms circling without turning are not affected.

Transports

  • A session only uses a transport that carries datagrams (up to 1200 bytes each): detphys_transport with two functions, send and recv. Datagrams may be lost, reordered or duplicated; the session resends and reorders. Steam, EOS or your own relay plug in here.
  • Transports that come with DetPhys:
    • UDP (detphys_udp.h, IPv4, for LAN and tests): listen (LISTEN; replies go to the sender of the last datagram) or connect (CONNECT). Either can be the host; a device behind a firewall should connect.
    • Loopback (detphys_loopback_*): two peers in one process. Delay, reordering, loss and duplication can be injected with a seed (for tests).
    • Unity's DetPhysFaultyLink, Godot's DetPhysLink.set_faults: add delay, jitter, loss and duplication in wall-clock ms to UDP or the loopback (for tests).
  • Connection interface (detphys_link.h): a layer on top of the transport with the same steps for every transport: create a room (host), join with a six-digit room code (guest), poll every frame, state and reason. It comes with UDP, the loopback and a test lobby that runs the room flow inside one process; EOS, Steam and your own relay go on the same interface. See 8. Transports and room codes.
  • Over the internet: the built-in UDP takes an IP address directly and is for LANs; it cannot cross NAT or mobile networks (CGNAT). Over the internet, use EOS P2P (EOS P2P), a relay on your own server (8. Transports and room codes) or plug your own transport into detphys_transport.
  • Clock: on a real network pass the engine's monotonic clock in microseconds (detphys_turn_poll_at, detphys_rt_poll / advance). The clock only drives resends and tick pacing; it never enters the hash.

Workers (threads)

worker_count (1–64, default 1) sets how many threads help a step. The hash does not depend on the count or the pool type (peers may use different values). With about 200 concave dynamic bodies, 4 workers make the step faster; with few simple shapes, 1 worker can be faster. The pool can be the core's own (default), Box2D's built-in scheduler, or the engine's job system (enqueue_task / finish_task).

DetPhys is not affiliated with Box2D or Box3D and is not endorsed or recommended by Box2D, Box3D or their author. It uses Box2D v3 and Box3D, both under the MIT license, as its physics.

LicensesMatches the current versions (2026-11)

© 2026 PetafProductsContactPrivacy

This site uses no analytics or tracking.

↑↓ to choose, Enter to open, Esc to close