DetPhysDocs日本語

Determinism rules (keeping game code deterministic)

The DetPhys core gives the same results on every device. A desync almost always comes from game code feeding device-dependent values into the simulation. Follow the rules below. When a desync happens, the desync debugger tells you which kind it is: input, rule state, setup, or physics.

1. Quantize inputs before passing them in

  • Turn engine floats (mouse, stick, touch positions) into integers (mm, mrad, −100..100, …) once, on the device that produces the input. Only integers travel, so both devices get the same value.
  • Examples (Unity): DetPhysStack.MetersToMm(x), DetPhysStack.RadiansToMrad(angle), DetPhysPush.QuantizeMove(axis). Godot: DetPhysRtMatch.quantize_move(axis).
  • Keep a button press until it is accepted (ADVANCED or DELAY_WAIT returned), so a short press is never lost.

2. Never put floats into the simulation

  • Core functions take integers only: lengths in mm, angles in mrad, speeds in mm/s, forces in mN, materials × 1000. There is deliberately no float entry point.
  • Do not feed frame times such as Time.deltaTime into the simulation. The tick length is fixed by tick_hz (in Unity, DetPhysRtDriver paces ticks with a monotonic clock).
  • The floats in the body readback (detphys_body_view, 3D detphys3d_body_view: position, angle, quaternion, velocity) are for drawing.
  • Pass 3D orientations as integer quaternions (multiply the engine's float quaternion by DETPHYS3D_QUAT_ONE and round, once, on the device that produces the input). Do the trigonometry that turns Euler angles into a quaternion outside the simulation (where the input is made).

3. Write rules with integers only

  • For rule decisions use the integer fields of the readback (x_mm, y_mm, angle_mrad; in 3D x_mm, y_mm, z_mm; identical on every target). If you must use a float, convert it to an integer once (in Unity, DetPhysFixed.FloorMilli).
  • If you write a rule in C / C++ and use floats, build it with the core's settings (MSVC /fp:precise; clang / gcc -ffp-contract=off -fno-fast-math; never /fp:fast, -ffast-math or -Ofast). Do not use trigonometry such as std::sin (results can differ between devices). Integers only is safest.
  • Do not compute with floats inside a C# rule (Unity): the result can change between Mono and IL2CPP and between CPUs.

4. Never put calls with side effects side by side in function arguments

make_box(rng_next(&r), rng_next(&r));   // wrong: argument evaluation order differs between compilers
int32_t w = rng_next(&r);               // right: one call per statement
int32_t h = rng_next(&r);
make_box(w, h);

C and C++ do not fix the order in which arguments are evaluated. It really happened that only Android's clang swapped a box's width and height. Call functions that change state (like a random generator) once per statement.

5. Use only your own seeded random numbers

  • Do not use UnityEngine.Random, System.Random, rand(), Godot's randi() and the like for results: implementations and seeds differ between devices and runtimes.
  • Use a seeded generator of your own (in Unity and Godot, DetPhysRandom [splitmix64]). Both peers must use the same seed before the match starts (the host picks it and shares it in the lobby before connecting).
  • The stacking rule's "next shape" depends only on the seed, the match number and the turn number (no state, so the same shape comes after a rollback or resync).

6. Do not depend on collection iteration order

  • Do not build results by iterating a Dictionary, HashSet, unordered_map and the like: their order depends on hash values or memory addresses and differs between devices.
  • Iterate in ID order (body IDs are creation-order serial numbers) or array order. When sorting, use a key that also orders equal values (such as the ID).
  • Never use pointer values, object hash codes or thread completion order for ordering or results.

7. Never use device-dependent values for results

  • Clocks, frame counts, thread IDs, pointers, files, device information, ctx->local_peer (your own peer number) and ctx->resimulating (whether this is a re-simulation) must not affect results (use them for logs, sounds and visuals only).
  • Do not call session functions (detphys_turn_*, detphys_rt_*) from rule callbacks. Use only the ctx values, detphys_body.h functions on ctx->world (detphys3d.h functions in 3D rules), your params and your state words.

8. Keep game state only in the world and the state words (real time)

  • Callbacks run again for the same tick on every rollback. Only the world and the state words are rolled back.
  • Do not keep scores, timers or cooldowns in fields of the rule object or in static variables (they are not rolled back and the peers desync).
  • There are 0–64 int32 state words (state_words).

9. Use the same settings, shapes and shape order on both peers

  • Session id, rule settings (params), shapes (.dnshape) and their registration order, and world settings (tick rate, substeps, gravity) must be the same on both peers. Peers that differ do not connect (a match never starts by mistake).
  • Build params from fixed-width integers only (no padding, no pointers).
  • In 3D, register convex hulls (detphys3d_world_add_hull) in begin / begin_match with the same points in the same order on both peers (their contents are part of the config check). Shapes created only during prediction are allowed (the state sent on a resync carries the registry), but registering hulls at the start of the match is the safest.
  • The worker count may differ between peers (the hash does not change).

10. Do not crush bodies with moving concave shapes

  • Kinematic bodies cannot be stopped. A moving shape that presses a pile of bodies against the floor or a wall pushes the squeezed bodies into it (crushing).
  • Placement:
    • Move descending gears and lifts above the piles (so they never reach them).
    • Do not sweep platforms just above the floor. Where a sideways motion pushes a pile, keep the pushing speed under about 3 m/s (the speed at which Box2D can push bodies out).
    • Leave no trap within the moving range (no place where bodies are shut in between the moving shape and the floor or a wall).
  • In 3D, if bodies stay on a spinning platform (a gear, a turntable), give it rims or dividers (resting bodies slowly slide outward; see 3. Concepts).
  • The built-in push rule's moving field follows these rules and had no tunneling in 1800-tick automatic matches. A notification for crushed bodies is (planned; to be decided in the usability review before release).

11. Set bullet on small bodies that fall fast from above

  • Small bodies that fall fast onto spinning gears and the like sink in less with DETPHYS_BODY_FLAG_BULLET (the body flags in Unity): 28 mm → 5.5 mm on a gear.
  • When the moving shape itself is so fast that bodies tunnel through it, use splitting (max_subticks, subtick_move_mm in 3. Concepts), not bullet.

12. Bodies on moving platforms never sleep — end turns by tick count

  • A body riding a moving kinematic body never falls asleep. A turn-based rule that ends the turn "when everything has settled" then runs until the limit (max_ticks_per_turn, default 900).
  • Turn-based games with moving platforms should end the turn in after_tick after a fixed number of ticks, using ctx->tick (the ticks run in this turn).
  • The same holds in 3D (detphys_turn_create_rule3d_kinematic). A moving kinematic body counts as awake, so the world never settles.

13. Change the kinematic table only in begin

  • The table (add / bind / unbind / clear) is not rolled back, so change it only inside the rule's begin (begin_match in turn-based play).
  • To change a motion during a match (a switch that starts a gear), make the motion itself a function of the tick: stops with POINTS, or CALLBACK computing from the tick. Passing the game state (state words) to motion callbacks is (planned).
  • A CALLBACK must compute with integers only and always return the same pose for the same tick (it is called again on rollbacks).
  • The same applies to 3D tables (detphys3d_kinematic_add / bind / unbind / clear). A 3D CALLBACK returns a position [µm] and an integer quaternion; for a continuing rotation, return the quaternion on the same side as the previous tick (the rotation between ticks takes the shorter way).

14. Use one world or session from one thread at a time

The core does not expect one world (or session) to be called from several threads at once. Workers are managed by the core itself.

How to check

  • Run two players on one device (loopback) for a long time with a test transport adding delay and loss, and see that both peers have the same hashes for confirmed ticks.
  • The test functions detphys_rt_debug_nudge_at / detphys_turn_debug_nudge_at shift the state by 1 ULP on purpose, to check that the hash check and resync work (never use them in real play).
  • Turn the desync debugger on, play between a PC and an Android device and see that no report appears (5. Troubleshooting desyncs).

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