Engine layer names
Engine
Unity (package 1.0.0, DetPhys namespace)
- World (detphys.h):
DetPhysWorld,DetPhysWorldSettings,DetPhysHashChain,DetPhysHash - Body readback (detphys_body.h):
DetPhysWorldView(ReadBodies,GetShapes,ReadMesh),DetPhysBodyView - Turn-based (detphys_turn.h):
DetPhysTurnSession,DetPhysTurnSettings,DetPhysStackRules(ToParams),DetPhysStack(RuleId),DetPhysTurnSession.,Create DetPhysTurnRule(rules in C#),DetPhysTurnContext,DetPhysRuleWorld - Real time (detphys_rt.h):
DetPhysRtSession,DetPhysRtSettings,DetPhysRtDriver,DetPhysRtRule(rules in C#) - Built-in push (detphys_rt.h version 5):
DetPhysRtSession.,CreatePush DetPhysPushSettings,DetPhysPushField,DetPhysPush(QuantizeMove,GetLayout),DetPhysPushLayout - Moving concave shapes (detphys_kinematic.h):
DetPhysKinematic,DetPhysMotion,IDetPhysMotionFunction - Peers whose config check does not match (detphys_turn.h version 9, detphys_rt.h version 7):
DetPhysRtSession.,TryGetTagInfo DetPhysTurnSession.(false with an older core),TryGetTagInfo DetPhysTagInfo(Active,RemoteKnown,PeerKnows,DiffParts,DiffText()and more; integers only),DetPhysTag(PartName,PartNames,RtSupported/TurnSupported, constantsPart*/Info*),DetPhysRtFrameFlags.(0x200) andTagMismatch DetPhysRtFrame.TagMismatch - Transports (detphys_udp.h and others):
DetPhysUdpLink,DetPhysLoopback,DetPhysFaultyLink - Connection interface, room codes (detphys_link.h), own relay (detphys_relay.h):
DetPhysLink(CreateRelay,CreateHub,CreateUdp,CreateLoopback,Host,Join,Poll,Info,Endpoint,Close,TryParseHostPort),DetPhysLinkInfo(State,Role,Path,Reason,RoomCode,RttMs,PathText...),DetPhysLinkHub(test lobby,DetPhysLinkHubSettings),DetPhysRoomCode(Make,Parse),DetPhysRoomOpener(make / enter a room and wait until the role is known; a guest that comes first enters again),DetPhysLinkResult,DetPhysLinkState,DetPhysLinkPath,DetPhysLinkReason - EOS P2P transport (detphys_eos.h version 2; a separate library,
detphys_eos):DetPhysEos(CreateLink,IsAvailable,UnavailableReason,SdkVersion,LastError,PrepareAndroid,Shutdown),DetPhysEosSettings(the portal values,Relay,Load/TryLoad[the ini's[eos]],Find,Missing),DetPhysEosRelay,DetPhysLink.. The Editor scriptCreateEos DetPhysEosAndroidGradleadds the Android Gradle settings (see the EOS section of "8. Transports and room codes") - 3D world (detphys3d.h version 2):
DetPhysWorld3D(Step,Hash,EngineHash,AddHull,AddBody,AddShape,ApplyForceand more,WriteSnapshot/RestoreSnapshot,WriteTransfer/RestoreTransfer),DetPhysWorld3DSettings,DetPhysWorld3DView(read only:ReadBodies,ReadTransforms,GetShapes,ReadHull,Stats),DetPhysRuleWorld3D(the world inside a rule),DetPhysBody3DDesc,DetPhysShape3DDesc(Box,Sphere,Capsule,Hull,At),DetPhysBody3DView(Position,Rotation),DetPhysHull3DInfo,DetPhysHull3DMesh(ToUnityMesh),DetPhysQuat(One= 2^30,From,FromFloats),DetPhysShape3DKind,DetPhysBody3DFlags - 3D sessions (detphys_rt.h version 6, detphys_turn.h version 8):
DetPhysRtSession.,Create3D DetPhysRtSettings.(full snapshots in the ring),Default3D DetPhysRtRule3D(rules in C#),DetPhysRtContext3D,World3D,ResyncInfo(DetPhysRtResyncInfo);DetPhysTurnSession.,Create3D DetPhysTurnRule3D,DetPhysTurnContext3D,DetPhysTurnTick,DetPhysTurnEndReason,SetCheckpointKind,World3D. Both haveIs3DandRule3D - 3D moving concave shapes (detphys3d_kinematic.h version 1):
DetPhysKinematic3D(Add,Bind,Step,Check,TryPoseAt,Stats),DetPhysMotion3D(Spin,PingPong,Orbit,Points),IDetPhysMotion3DFunction,DetPhysMotion3DPoint,DetPhysKinematic3DPose. WithUsesKinematic => truein the rule the session owns the table (DetPhysRtContext3D.,Kinematic DetPhysTurnContext3D.,Kinematic DetPhysRtSession.); splitting is set with the sameKinematic3D DetPhysKinematicSettingsas 2D - Desync debugger (detphys_debug.h version 3, 2D and 3D): Sessions:
SetDebug(DetPhysDebugSettings.),On DebugReportCount,TryGetDebugReport(DetPhysDesyncReport: first tick, body, field, both values, ULP, cause),DebugBundle(DNDB),DebugStats(real time and turn-based, 2D and 3D). Your own ring:DetPhysDebugRecorder(Record,Record3D,Export),DetPhysDebug(Compare,TryGetFileInfo,WriteFile,FieldName,CauseName),DetPhysDesyncStatus,DetPhysDesyncCause - Match components (MonoBehaviour):
DetPhysRtMatch(2D real time),DetPhysRtMatch3D(3D real time),DetPhysTurnMatch(2D turn based, the built-in stacking rule or yourDetPhysTurnRule) andDetPhysTurnMatch3D(3D turn based, yourDetPhysTurnRule3D). Add one to a GameObject and set it in the Inspector: it starts inStartand steps inUpdate- Connecting (all of them):
connection(DetPhysMatchConnection:kind=Local[two players on this device],Udp(peer,listen,address,port),Relay(relay,host,roomCode,bucket,joinRetrySeconds),Eos(eosConfig,eosRelay) orManual[from code]; simulated delay and loss for testingsimulate*),startAutomatically,stepInUpdate,StartMatch,StartWithLink,StartWithEndpoint,StartRoom,Stop,Step/StepAt,Clock,IsRunning,InLobby,IsPeerConnected,LocalPeer,RoomCode,LinkInfo,Error. UnityEvents:onConnected,onPeerLost,onError,onRoomCode,onRoomReady,onSettingsMismatch(what differs, e.g.rule) - Real time:
rule(DetPhysRuleSource.= the built-in push /BuiltIn CSharp=RuleorRuleFactory),push(DetPhysPushSettingsin 2D,DetPhysPush3DSettingsin 3D),shapes(2D shapes),sessionId,inputDelay,maxPrediction,automaticInputDelay,desyncDebugger,workers,kinematic,maxTicksPerFrame,endAtTick,InputSource((peer, tick) → input integers) orLocalInput,AdjustSettings,Session,ConfirmedTick,RolledBack,StateReplaced. UnityEvents:onTickConfirmed(tick, hash, flags; the same on both peers),onDesync,onResynced,onRejoined,onInputDelayChanged,onDesyncReport(the desync debugger's report as text),onMatchEnded - Turn based:
rule(2D;DetPhysRuleSource.= the built-in stacking /BuiltIn CSharp=RuleorRuleFactory),rules,shapes(2D),Rule/RuleFactory,world(3D),firstMover,maxTicksPerTurn,peerTimeoutMs,ticksPerFrame,playbackSpeed,desyncDebugger,InputSource((peer, turn) → the move; null asks again next frame) orSubmit,State,IsLocalTurn,Results. UnityEvents:onLocalTurn,onTurnFinished(turn, hash, flags),onMatchOver,onDesync,onDesyncReport,onStateChanged - Drawing:
views(DetPhysViewSettings:syncTransforms[copy to Transforms every frame],bodies[Transforms by body id],createViews[simple views — boxes, spheres, hulls and so on — for bodies without a Transform],material[empty = the default material, for the built-in pipeline, URP and HDRP],colorByShape[color the default material by body type and shape],skipStatic),ViewOf,ViewCount. 2D worlds use the XY plane (rotation about z); 3D worlds use Unity's axes
- Connecting (all of them):
- Built-in 3D push (detphys_rt.h version 8):
DetPhysRtSession.,CreatePush3D IsBuiltInPush3D,Push3DSettings,DetPhysPush3DSettings(seed,turntable,tableSpinMradS,boxCount/sphereCount/hullCount,predictButtonsReleased),DetPhysPush3D(Input,QuantizeAxis,Params,Fingerprint,GetLayout,AutoInputs,IsAvailable),DetPhysPush3DLayout - Shape Baker (detphys_bake.h version 1; Editor only,
DetPhys.Editor): the windowWindow > DetPhys > Shape Baker(DetPhysShapeBakerWindow),DetPhysShapeBaker(Bake[a Texture2D, a Sprite or either],BakePng,BakeAlpha,Save[a.dnshape.bytesasset],DefaultAssetPath),DetPhysBakeSettings(pixelsPerMeter,useSpritePixelsPerUnit,alphaThreshold,simplifyPixels,method,maxVerticesand more),DetPhysBakeMethod(Steiner,HertelMehlhorn),DetPhysBakeResult(Succeeded,Error,Data,Shape,Stats,Outline). At run time:DetPhysShapeFile(Parse,TryParse,PieceCount,PiecesMeters,BoundsMeters) reads a.dnshape - Random numbers:
DetPhysRandom(splitmix64) - Raw C ABI:
DetPhys.(push:Native. DetPhysNative DetPhysNativePush, 3D:DetPhysNative3D., desync debugger:cs DetPhysNativeDebug.)cs
- 2D turn-based rules can be written in C# too. Subclass
DetPhysTurnRule, setInputWords,StateWords,RuleId,Params(part of the settings check, so put every setting of the rule here) andUsesKinematic, and writeBeginMatch(the start of a match: the world is empty and the shapes are registered) andApplyInput(put the mover's input into the world), plus only what you need ofCheckInput(HasCheckInput),AfterTick(HasAfterTick; returns aDetPhysTurnTick; by default the turn ends when everything sleeps) andEndTurn(HasEndTurn; returns the next mover and ends the match withmatchOver; by default the movers alternate). Pass it toDetPhysTurnSession.; everything else is the same as the built-in stacking rule (Create(settings, rule, meshes, localPeer, endpoint, kinematic = null) Poll,Submit,TryGetResult,World). The callbacks get aDetPhysTurnContextwithWorld(DetPhysRuleWorld:AddBody,AddShape,ApplyImpulse,TryGetBody,TryGetMeshInfo,MeshCount,BodyCountand so on),GetState/SetState,Mover,Turn,Match,MatchTurn,Tick,SettledandKinematic(the session'sDetPhysKinematicwhenUsesKinematic => true; moving platforms never sleep, so end turns inAfterTickby the tick count). The session'sRuleandKinematicreturn them. With the match components, useDetPhysTurnMatchwithrule = CSharpandRule/RuleFactory.Assets/in the "Stack Versus" sample is the built-in stacking rule written in C#: it returnsSamples/ DetPhys/ 1. 0. 0/ DetPhys Samples/ StackVersus/ Runtime/ CSharpStackRule. cs DetPhysStackRules.asToParams() ParamsandDetPhysStack.asRuleId RuleIdand computes with the same formulas in the same order, so it connects to peers using the built-in rule and to peers with the same rule written in Godot or Unreal, with the same hash on every turn. - 3D rules can be written in C# (
DetPhysRtRule3D,DetPhysTurnRule3D; the same rules as the 2DDetPhysRtRule: integers only, state in the state words, hulls registered in Begin in the same order on both peers). The rule of the "3D push" sample (Assets/) has the same params and rule id (with or without the turntable) as the core's built-in 3D push (Samples/ DetPhys/ 1. 0. 0/ DetPhys Samples/ Push3D/ Runtime/ Shared/ Push3DRule. cs detphys_, version 8), so it connects to peers using the core rule (such as the Godot sample). Use the core rule withrt_ create_ push3d DetPhysRtSession.(CreatePush3D DetPhysPush3DSettings) orDetPhysRtMatch3Dwithrule = BuiltIn. - Drawing: Box3D and Unity both have y up, so
DetPhysBody3DView.andPosition Rotationcan be used as they are (Box3D is right-handed and Unity left-handed, so the picture is a mirror image of the right-handed world; everything is mirrored the same way;DetPhysHull3DMesh.turns the hull triangles the way Unity expects).ToUnityMesh - The samples compare their confirmed hashes with the reference hashes stored in each sample's
Resourcesfolder when they run with automatic inputs, so you can check on any device that 2D and 3D worlds, sessions and moving concave shapes give the same hashes. - A transport written in C# (an implementation table given to
detphys_) is not wrapped yet; use the transports of the C ABI for now.link_ create
Godot (add-on addons/detphys, layer version 7)
- World: GDScript:
DetPhysWorld,DetPhysWorldSettings,DetPhys(hash hex, chains). C#:DetPhysWorld,DetPhysWorldSettings,DetPhysHash - Body readback: GDScript:
DetPhysWorldReader(read_bodies,read_body_info,get_body_shapes,get_; sessions inherit it). C#: Same declarations as Unitymesh_ polygons - Turn-based: GDScript:
DetPhysTurnSession(create_stack),DetPhysTurnSettings,DetPhysStackRules, nodeDetPhysStackMatch. C#:DetPhysTurnSession - Real time, built-in push: GDScript:
DetPhysRtSession(create_push,get_layout,kinematic_check),DetPhysRtSettings,DetPhysPushRules(movingfieldtoo), nodeDetPhysRtMatch. C#:DetPhysRtSession.,CreatePush DetPhysPush - Peers whose config check does not match: GDScript:
DetPhysRtSession.,get_ tag_ info() DetPhysTurnSession.(a Dictionary of integers:get_ tag_ info() flags,diff_partsand more;local_parts/remote_partsare PackedInt64Arrays of 8), statictag_,part_ name(part) tag_, constantspart_ names(parts, separator) DETPHYS_,TAG_ PART_* DETPHYS_,TAG_ INFO_* DETPHYS_(andRT_ FRAME_ TAG_ MISMATCH DETPHYS_), node signalRT_ FRAME_ DEBUG tag_(mismatch(info) DetPhysRtMatch,DetPhysStackMatch; info addsknown_after_msandparts_text; callcheck_tag()when you driveadvance_onceyourself). C#:TryGetTagInfo(real time, turn-based;DetPhysTagInfoNative),DetPhysTag(PartName,PartNames) - Transports: GDScript:
DetPhysLink(udp_listen,udp_connect,set_faults),DetPhysLoopback. C#:DetPhysUdpLink,DetPhysLoopback - Connection interface, room codes, own relay (detphys_link.h, detphys_relay.h): GDScript:
DetPhysLink(staticrelay(host, port, local_,port) host_,room(bucket, code, entropy, timeout_ ms) join_,room(code, bucket, timeout_ ms) poll,get_state,get_role,get_path,get_room_code,get_info[Dictionary with names],get_link_error,close, staticroom_code_make,room_code_parse,room_code_check,state_name,reason_name,path_name, constantsDETPHYS_LINK_*,DETPHYS_RELAY_*;set_faultsworks too),DetPhysLinkHub(create,create_link,pump). The nodesDetPhysRtMatchandDetPhysStackMatchcalllink.poll()every frame. C#:DetPhysLink(CreateRelay,Host,Join,Poll,Info,Transport),DetPhysLinkHub,DetPhysRoomCode,DetPhysRoomOpener(the same as in Unity: make / enter a room and wait until the role is known; a guest that comes first enters again;FailResultis aDetPhysNative.number)LinkError* - EOS P2P transport (detphys_eos.h version 2): GDScript has
DetPhysLink(staticeos(settings),eos_available(),eos_,sdk_ version() eos_error();detphys_eosis loaded when first used) and the helper scriptaddons/(detphys/ eos/ detphys_ eos. gd load_ini,find_ini,create_link,prepare_android,available,error). For Android exports the editor plugin "DetPhys" adds the EOS SDK's aar and the Gradle settings. C# has the same API as Unity:DetPhysEos(CreateLink,IsAvailable,UnavailableReason,SdkVersion,LastError,PrepareAndroid,AndroidExternalFilesDir,Shutdown),DetPhysEosSettings(Load/TryLoad[res://anduser://work too],Find,Missing),DetPhysEosRelay; declarations inDetPhysNativeEos.(GDScript and C# use the samecs detphys_eos) - 3D, built-in 3D push (detphys_rt.h version 8, detphys3d.h, detphys3d_kinematic.h; layer version 3): GDScript:
DetPhysRtSession.,create_ push3d(settings, rules, local_ peer, link, world = null) DetPhysRtSettings.(FULL snapshots),default_ 3d() DetPhysPush3DRules(Resource, one to one with the desc:box_count,sphere_count,hull_count,spawn_max,field[FIELD_NONE/FIELD_TURNTABLE],seed,table_and more;spin_ mrad_ s to_params,fingerprint,get_layout, staticauto_, constantsinputs(seed, peer, ticks) BUTTON_*,TAG_*,INPUT_WORDS),DetPhysWorld3DSettings(tick_hz, substeps, gravity xyz, worker_count). Input: 3 words every tick[move x, move z, buttons]. Readback (for drawing):is_3d,get_world3d_tick/_hash,get_body3d_count,get_,world3d_ stats read_(7 floats: position in m, quaternion x, y, z, w),transforms3d(first) read_bodies3d()(8 ints: id, type, flags, tag, shape count, first shape, hull),get_body3d(id),get_(Vector3 / Quaternion),body3d_ shapes(id) get_hull3d_count,get_hull3d(hull),get_(ready forhull3d_ arrays(hull) ArrayMesh.). The turntable's table:add_ surface_ from_ arrays has_kinematic,get_,kinematic_ stats kinematic_check(the same names as 2D). C#:DetPhysRtSession.(CreatePush3D Is3D,World3D,ReadTransforms3D,ResyncInfo,KinematicCheck),DetPhysPush3D(Desc,Params,Fingerprint,Layout,AutoInputs); declarations inDetPhysNativePush3D.cs - State sent on a resync, desync debugger (detphys_debug.h version 3; 2D and 3D sessions): GDScript:
DetPhysRtSession.(get_ resync_ info() registry_,rebuilds hull_,replacements last_bytesand more; 3D also sends the shape registry and the hull table),set_,debug(enabled, ticks_ before = 30, max_ reports = 4, timeout_ ms = 10000) get_debug_count,get_(debug_ report(index) status,first_tick,body,field_name,ulp,cause_name,text[the same line as Unity'sDetPhysDesyncReport] and more),get_(DNDB, open it withdebug_ bundle(index) tools/desync),get_debug_stats, staticdebug_field_name,debug_cause_name,rt_abi_version,world3d_,abi_ version debug_. C#:abi_ version ResyncInfo, the same desync debugger as Unity (SetDebug[DetPhysDebugSettings.],On DebugReportCount,TryGetDebugReport[DetPhysDesyncReport],DebugBundle,DebugStats; real-time and turn-based sessions),DetPhysDebugRecorder(Record3D,Export),DetPhysDebug(Compare,FieldName,CauseName) andDebugNudgeAtfor tests - 3D, rules you write (C#; detphys_rt.h version 6, detphys_turn.h version 8, detphys3d.h, detphys3d_kinematic.h): the same names and design as Unity. Derive from
DetPhysRtRule3D(real time) orDetPhysTurnRule3D(turn based) and pass it toDetPhysRtSession.orCreate3D(rule, localPeer, transport, owner, world = null, sessionId = 0x36, inputDelay = 0, maxPrediction = 10, snapshot = Full, recordAllHashes = true, kinematic = null) DetPhysTurnSession.(Create3D(rule, localPeer, transport, owner, world = null, sessionId = 0x36, maxTicksPerTurn = 600, peerTimeoutMs = -1, firstMover = 0, kinematic = null) transportisDetPhysUdpLink.,Transport DetPhysLink.orTransport DetPhysLoopback.;Side(n) owneris the object that holds it). The callbacks get aDetPhysRtContext3D/DetPhysTurnContext3DwithWorld(DetPhysRuleWorld3D:AddHull,AddBody,AddShape,ApplyForce,ApplyImpulse,TryGetBodyand more),GetState/SetState,TickandKinematic(when the rule returnsUsesKinematic => true, theDetPhysKinematic3Dthe session owns; add moving concave shapes inBegin:Add,DetPhysMotion3D./Spin PingPong/Orbit/Points,IDetPhysMotion3DFunction). Turn speeds into integers withDetPhysFixed.. Session readback:FloorMilli Is3D,Rule3D,World3D(DetPhysWorld3DView:ReadBodies,ReadTransforms,GetShapes,ReadHull,Stats,Hash),ReadTransforms3D,Kinematic3D, andSetCheckpointKindfor turn-based sessions. To step a world directly:DetPhysWorld3D(Editgives the same calls as a rule;WriteSnapshot/RestoreSnapshot,WriteTransfer/RestoreTransfer) andDetPhysKinematic3D(Step,Check). For drawing:DetPhysBody3DView.,Position Rotation(GodotVector3,Quaternion),DetPhysHull3DMesh.(anToArrayMesh() ArrayMeshwith Godot's front-face order) andDetPhysQuat.(to quantize inputs). Declarations are the same files as Unity:From(Quaternion) DetPhysNative3D.,cs DetPhysNativeKinematic.,cs DetPhysNativeDebug.cs - The rules of a rule are the same as in Unity: results may depend only on the inputs, the context, the world and
Params, computed with integers. Real-time callbacks run again for the same tick on every rollback, so keep the match state in the world and the state words. Register hulls inBegin(BeginMatch), in the same order on every peer. Change the kinematic table only inBegintoo - Sample rules (
samples/, namespacerules3d/ DetPhysSampleRules3D. cs DetPhys.Samples):DetPhysSamplePush3DRule(the 3D push written in C#; it has the same params and rule id as the built-in rule, so it plays peers that use the built-in rule [GDScriptcreate_push3d, Unity, Unreal]),DetPhysSampleStack3DRule(3D stacking, turn based) andDetPhysSampleSpinTableRule(a turning octagonal table, a concave shape moved by the kinematic table). With the launch optionrule=cs, the "3D push" sample plays an automatic match with this rule (without drawing)
- The rules of a rule are the same as in Unity: results may depend only on the inputs, the context, the world and
- 3D, rules you write (GDScript; layer version 4): rules with the same design as in C# can be written in GDScript alone.
extendsDetPhysRtRule3D(real time) orDetPhysTurnRule3D(turn based), setinput_words,state_words,rule_id,params(a PackedInt32Array that is part of the config check, so put every value of the rule in it) anduses_kinematicin_init, and pass the rule toDetPhysRtSession.orcreate3d(settings, rule, local_ peer, link, world = null) DetPhysTurnSession.(create3d(settings, rule, local_ peer, link, world = null) settingsisDetPhysRtSettings./default_ 3d() DetPhysTurnSettings,worldis aDetPhysWorld3DSettings[null = defaults]; on failure they return null and print the reason as a Godot error).- Real-time callbacks:
_begin(ctx)(tick 0; create hulls, bodies and kinematic bodies),_(every tick;apply_ inputs(ctx, inputs) inputsholds both peers in one PackedInt32Array, word w of peer p isinputs[p * input_),words + w] _after_tick(ctx)(optional) and_(optional; return the peer's input that has not arrived yet as a PackedInt32Array ofpredict(peer, tick, known_ tick, known) input_wordswords; without it the last received input is repeated). - Turn-based callbacks:
_(every match; the world starts empty),begin_ match(ctx) _(place the mover's move),apply_ input(ctx, input) _(optional; return a bool, false rejects the move),check_ input(ctx, input) _after_tick(ctx)(optional; returnTICK_CONTINUE,TICK_END_TURNorTICK_END_MATCH) and_(optional; return the next mover 0 / 1, plusend_ turn(ctx, reason) MATCH_OVERto end the match;reasonisREASON_END_TURN,REASON_END_MATCHorREASON_CAPPED). - Contexts:
DetPhysRtContext3D(tick,resimulating,local_peer,world,get_state(i)/set_state(i, v),fail(why),add_,kinematic(body, motion) kinematic_) andcheck() DetPhysTurnContext3D(turn,match,match_turn,mover,tick,settled, plus the sameworld,get_state/set_state,fail,add_kinematic,kinematic_check). They are valid only inside a callback. - World (
DetPhysRuleWorld3D, all values are integers):add_(points in x, y, z order; returns the hull index),hull(xyz, units_ per_ meter = 1000, max_ vertices = 0) add_body(desc),add_,shape(body, shape) remove_body,set_transform,set_velocity,apply_force(mN),apply_torque,apply_impulse(mN·s),apply_,angular_ impulse get_body(id)(x_mm,vx_mm_s,wx_mrad_s,qx–qw[timesDETPHYS3D_],QUAT_ ONE type,removed,awakeand more),get_,hull_ info(hull) get_tick,get_hash,get_body_count.desc,shapeandmotionare Dictionaries whose keys are the field names of the C structs (x_mm,radius_mm,half_x_mm,density_milli,friction_milli,flags,shapeand so on). Missing keys take the defaults; unknown keys and float values are rejected as typos (the rule stops andget_rule_error()tells why). Constants:DetPhysRuleWorld3D.,DETPHYS3D_ SHAPE_* DETPHYS3D_BODY_*,DETPHYS3D_,BODY_ FLAG_* DETPHYS3D_PATH_*,DETPHYS_EASE_*. - Moving concave shapes: a rule with
uses_adds them insidekinematic = true _begin(_begin_match) withctx.. In real time,add_ kinematic({"shape": {...}}, {"path": DetPhysRuleWorld3D. DETPHYS3D_ PATH_ FIXED, "spin_ mrad_ s": 1200, ...}) kinematic_and the othermax_ subticks kinematic_*values ofDetPhysRtSettingsset how finely the table is stepped. - Reading the session: the same
is_3d,get_world3d_hash,read_,transforms3d read_bodies3d,get_body3d,get_hull3d/get_,hull3d_ arrays has_kinematicandkinematic_checkas the 3D push work on both real-time and turn-based sessions, plusget_rule()andget_rule_error(). - The same rules as in C# apply: results may depend only on the inputs, the context, the world and
params, computed with integers (do not letfloat,randi(),Timeor Dictionary iteration order reach the result; use aDetPhysRandommade from a seed). Real-time callbacks run again for the same tick on every rollback, so keep the match state in the world and the state words. Register hulls inside_beginin the same order on every peer. - Sample rules (
samples/rules3d):push3d_rule.gd(the 3D push; it has the same params, rule id and results as the built-in rule and C#'sDetPhysSamplePush3DRule, so it playscreate_push3dand C# peers),stack3d_rule.gd(3D stacking, turn based) andspin_(the spinning octagonal table). See 3. Concepts for an example.table_ rule. gd
- Real-time callbacks:
- 2D, rules you write (GDScript and C#; detphys_rt.h, detphys_turn.h, detphys_body.h, detphys_kinematic.h; layer version 5, match nodes and C# rules for them 6): rules for the 2D world (Box2D) with the same design as 3D. Shapes (
.dnshape) are passed when the session is created and registered from index 0.- GDScript:
extendsDetPhysRtRule2D(real time) orDetPhysTurnRule2D(turn based), setinput_words,state_words,rule_id,paramsanduses_kinematicin_init, and pass the rule toDetPhysRtSession.orcreate2d(settings, rule, local_ peer, link, meshes = []) DetPhysTurnSession.(create2d(settings, rule, local_ peer, link, meshes = []) meshesis an Array of.dnshapePackedByteArrays; on failure they return null and print the reason as a Godot error). The callbacks and their return values are the same as in 3D (_begin,_apply_inputs,_after_tick,_predict/_begin_match,_apply_input,_check_input,_after_tick,_end_turn).paramsreturns a copy, so build the PackedInt32Array first and assign it once. - Contexts:
DetPhysRtContext2DandDetPhysTurnContext2D(the same names as 3D:tick,world,get_state/set_state,fail,add_kinematic,kinematic_check; turn based also hasturn,match_turn,mover,settledandget_match()). - World (
DetPhysRuleWorld2D):add_body(desc),add_,shape(body, shape) remove_body,set_,transform(body, x_ mm, y_ mm, angle_ mrad) set_,velocity(body, vx_ mm_ s, vy_ mm_ s, w_ mrad_ s) apply_,force(body, fx_ mN, fy_ mN) apply_,impulse(body, ix_ mNs, iy_ mNs) get_body(id),get_body_count,get_awake_count,get_mesh_count,get_(mesh_ info(mesh) radius_mmand more),get_tick,get_hash.desc,shapeandmotionare Dictionaries whose keys are the field names of the C structs (type,x_mm,angle_mrad,tag, and inshape:kind,mesh,size_x_mm,offset_x_mm,density_milli,friction_milliand more).get_bodyreturns integers (x_mm,y_mm,angle_mrad,vx_mm_s,w_mrad_s,type,shape_kind,mesh,removedand more) and floats for drawing (x,y,angle,vx,vy,w). Do not compute with the floats; use them only to compare a position with a limit. Constants:DetPhysRuleWorld2D.,DETPHYS_ BODY_* DETPHYS_SHAPE_*,DETPHYS_PATH_*,DETPHYS_EASE_*. - Moving concave shapes: a rule with
uses_adds them insidekinematic = true _begin(_begin_match) withctx.. Theadd_ kinematic({"shape": {"kind": DetPhysRuleWorld2D. DETPHYS_ SHAPE_ MESH, "mesh": 3}}, {"path": DetPhysRuleWorld2D. DETPHYS_ PATH_ FIXED, "x_ mm": -5500, "y_ mm": 4000, "spin_ mrad_ s": -1200}) pointsof aPOINTSpath are 4 words per point:x_.mm, y_ mm, angle_ mrad, ticks - C#: inherit
DetPhysRtRule(real time, the same name as in Unity) orDetPhysTurnRule(turn based, the same design as 3D), and pass the rule toDetPhysRtSession.orCreate(rule, localPeer, meshes, transport, owner, sessionId = 0x16, inputDelay = 0, maxPrediction = 10, recordAllHashes = true, kinematic = null) DetPhysTurnSession.(Create(rule, localPeer, meshes, transport, owner, sessionId = 0x7E57, maxTicksPerTurn = 0, peerTimeoutMs = -1, firstMover = 0) meshesis abyte[][]of.dnshapefiles). The callbacks get aDetPhysRtContext/DetPhysTurnContextand useWorld(DetPhysRuleWorld:AddBody,AddShape,ApplyForce,ApplyImpulse,TryGetBody,TryGetMeshInfo,MeshCountand more),GetState/SetStateandKinematic(DetPhysKinematic:Add,DetPhysMotion./Spin PingPong/Orbit/Points,IDetPhysMotionFunction). Sessions haveRule,Kinematicand, turn based,World2D. - The same rules as in 3D apply: results may depend only on the inputs, the context, the world and
params, computed with integers. Real-time callbacks run again for the same tick on every rollback, so keep the match state in the world and the state words. Change the kinematic table only inside_begin(_begin_match). - Peers with the same rule connect and confirm the same tick hashes whether the rule is written in GDScript, C#, Unreal C++ or is the core's built-in rule (they are matched by
paramsandrule_id). Check that your values match the built-in rules withDetPhysPushRules.,to_ params() RULE_ID,DetPhysStackRules.andto_ params() RULE_ID. - Sample rules (
samples/rules2d):push_rule.gd/DetPhysSamplePushRule(the push, with or without the moving stage) andstack_rule.gd/DetPhysSampleStackRule(stacking, turn based; the next shape decided by a seed or chosen by the input). They have the same params, rule id and results as the built-in rules (create_push,create_stack). - Match nodes (layer version 6): put a rule in
ruleofDetPhysRtMatchorDetPhysStackMatchbeforestart, and the node plays that rule with the same links (UDP, relay rooms, EOS rooms), signals and drawing readback as the built-in rules (an emptyruleplays the built-in push / stacking). It takes a GDScript rule (DetPhysRtRule2D/DetPhysTurnRule2D) or a C# rule wrapped inDetPhysRuleRef(new DetPhysRuleRef(new MyRule()), for bothDetPhysRtRuleandDetPhysTurnRule). Use one rule instance per node. The input (input_source,submit) is the rule'sinput_wordsintegers. Giveclock(func() -> int, µs) your own clock to step with it (for tests).DetPhysRtSession.andcreate2d DetPhysTurnSession.also take acreate2d DetPhysRuleRef(the core calls the C# callbacks directly).
- GDScript:
- 3D match nodes (C#):
DetPhysRtMatch3D(Rule[empty = the built-in 3D push withSeed,Turntable,PredictButtonsReleased],World,Kinematic,InputSource[tick → input words],Start(localPeer, transport, owner),Stop,StepFrame/StepAt(nowUs),Session,RolledBack,Replaced,IsPeerConnected,QuantizeAxis; signalsConnected,TickConfirmed(tick, hash, flags),DesyncFound,Resynced,Rejoined,PeerLost,Failed) andDetPhysTurnMatch3D(Rule[required],InputSource[turn number → move; null = ask again next frame],MaxTicksPerTurn,MaxTicksPerFrame,Results; signalsConnected,TurnFinished(turn, hash, flags),MatchOver,StateChanged,Failed). Both are[GlobalClass], so they appear in the editor's "Add Node". WithAutoProcesson (the default) they advance in_Process; giveClockyour own clock (µs) to advance ticks by it (for tests) - Random numbers: GDScript:
DetPhysRandom. C#:DetPhysRandom
- 3D coordinates: Box3D and Godot are both y up, right-handed, in meters, so the positions and quaternions of
read_go straight intotransforms3d Transform3D(Basis(Quaternion(qx, qy, qz, qw)), Vector3(x, y, z))(unlike Unity, the picture is not mirrored). Box3D's hull triangles are counter-clockwise seen from outside and Godot's front faces are clockwise, soget_hull3d/get_reorder them (hull3d_ arrays get_gives per-face vertices and outward normals).hull3d_ arrays - The "3D push" sample (
samples/push3d, GDScript only) plays Unity's "3D push" sample, with the same confirmed hashes. - Even when the core turns a HELLO with a different config hash into ERROR,
DetPhysStackMatchkeeps polling until the peer's parts arrive and it knows what differs (waiting up to 300 ms), and emitsfailedaftertag_mismatch. - In the Godot layer, matches use the built-in rules (stacking, push, 3D push). 2D and 3D rules (real time and turn based) and kinematic tables can be written in GDScript and C#. The desync debugger works on real-time sessions (2D and 3D) from GDScript, and on real-time and turn-based sessions from C#.
- The steps "make / enter a room, wait until the role is known (a guest that comes first enters again)" are written in GDScript in the sample's
samples/(copy it).common/ detphys_ sample_ room. gd
Unreal (plugin DetPhys 0.1.0)
- World (detphys.h):
UDetPhysWorld(Blueprint:CreateDetPhysWorld,Step,StepTicks,GetTick,GetStateHash; C++:GetNative()),FDetPhysWorldSettings,UDetPhysLibrary - Body readback (detphys_body.h):
ReadBodies,GetBody,GetBodyShapes,GetMeshPolygons(onUDetPhysWorldand on the sessions),FDetPhysBody,FDetPhysBodyShape,FDetPhysPolygon - Turn-based, built-in stacking (detphys_turn.h):
UDetPhysTurnSession::CreateStack(Poll/PollAt,Submit,NextResult,UpcomingShape,ShapeAt,GetLinkStats,GetWorldSerial),FDetPhysTurnSettings,FDetPhysStackRules,FDetPhysTurnResult(AgreedHash),FDetPhysTurnLinkStats - Real time, built-in push (detphys_rt.h):
UDetPhysRtSession::CreatePush(Poll,DueTicks,GetNextInputTick,Advance,DrainConfirmed,GetStats,ReadState, moving fieldHasMovingField,CheckMovingField,GetMovingFieldStats),FDetPhysRtSettings,FDetPhysPushRules(moving fieldField),FDetPhysRtFrame,FDetPhysConfirmedTick,FDetPhysRtStats - 2D, your own rules (detphys_rt.h, detphys_turn.h, detphys_body.h, detphys_kinematic.h): subclass
UDetPhysRtRule(real time) orUDetPhysTurnRule(turn based) in C++ and pass it toUDetPhysRtSession::Create(Outer, Settings, Rule, Shapes, LocalPeer, Link)orUDetPhysTurnSession::Create(Outer, Settings, Rule, Shapes, LocalPeer, Link). The shapes (Shapes) are registered as mesh 0, 1, ... before the rule'sBegin(BeginMatch). The virtual functions are the same as Unity'sDetPhysRtRuleand follow the 3D rules (real time:GetInputWords,GetStateWords,GetRuleId,GetParams,UsesKinematic,HasAfterTick,HasPredict,Begin,ApplyInputs,AfterTick,Predict,GetPlayerBody; turn based:GetInputWords,GetStateWords,GetRuleId,GetParams,UsesKinematic,GetKinematicMaxSubticks,GetKinematicSubtickMoveMm,BeginMatch,HasCheckInput/CheckInput,ApplyInput,HasAfterTick/AfterTick[EDetPhysTurnTick],HasEndTurn/EndTurn[EDetPhysTurnEndReason],ShapeAt). The callbacks getFDetPhysRtContext/FDetPhysTurnContext(GetWorld()=detphys_world*,GetTick,GetState/SetState,GetMeshCount,GetKinematic()=detphys_,kinematic* Fail; turn based alsoGetMover,GetTurn,GetMatch,GetMatchTurn,IsSettled). Build and move the world with the C ABI (detphys_body.h,detphys_) directly. The session'skinematic. h GetRule()returns the rule, andGetPlayerBody,UpcomingShapeandShapeAtreturn what the rule'sGetPlayerBodyandShapeAtanswer. WithUsesKinematictrue the session owns a kinematic table (real time: split by theKinematic*values inSettings; read it withGetKinematic())- A rule with the same rule id and params as a built-in rule connects to peers running the built-in rule (
CreatePush,CreateStack, Unity, Godot,detphys_in the C ABI, and so on), with the same confirmed-tick and turn hashesrt_ create_ push - Sample rules (
DetPhysSampleRules2D.inh DetPhysSample):UDetPhysSamplePushRule(the push game, with or without the moving field; values inFDetPhysPushRules) andUDetPhysSampleStackRule(stacking, turn based; values inFDetPhysStackRules). Both use the same formulas and params as the built-in rules. TheDetPhysVersuscommandlet runs matches with them when givenrule=cpp
- A rule with the same rule id and params as a built-in rule connects to peers running the built-in rule (
- 3D, built-in 3D push (detphys_rt.h version 8, detphys3d.h, detphys3d_kinematic.h):
UDetPhysRtSession::CreatePush3D(Outer, Settings, Rules, LocalPeer, Link, World)(Poll,DueTicks,Advance[3 input words per tick:[move x, move z, buttons]],DrainConfirmedand the desync debugger work as in 2D; the turntable throughHasMovingField,CheckMovingField,GetMovingFieldStats; players throughGetPlayerBody),FDetPhysPush3DRules(one to one with the desc:BoxCount,SphereCount,HullCount,SpawnMax,Seed,Field[EDetPhysPush3DField::None/Turntable],TableSpinMradS,TableXMm,TableZMmand more),FDetPhysWorld3DSettings(tick rate, substeps, gravity xyz, worker threads),UDetPhys3DLibrary(DefaultRtSettings3D[FULL snapshots],AutoPush3DInputs,MakePush3DInput,GetPush3DLayout,Push3DParams,Push3DFingerprint, coordinate conversionCoreToUnrealLocation,CoreMmToUnreal,UnrealToCoreMm,CoreToUnrealRotation,CoreToUnrealDirection). Readback for drawing:Is3D,GetPush3DLayout,ReadTransforms3D(an array ofFTransform; index = body id),ReadBodies3D,GetBody3D(FDetPhysBody3D),GetBodyShapes3D(FDetPhysShape3D),GetHull3DCount,GetHull3DMesh(FDetPhysHull3DMesh: vertices, triangles and outward normals ready forUProceduralMeshComponent::CreateMeshSection),GetWorld3DTick,GetWorld3DHash,GetWorld3DStats,GetResyncInfo(FDetPhysResyncInfo, also for 2D). C++:GetDetPhysWorld3D()returns thedetphys3d_world*- Coordinates: the core is right-handed with y up and metres; Unreal is left-handed with z up and centimetres. Values returned as
FVector,FQuatandFTransformare converted to Unreal coordinates by the layer (position(x, y, z)m →(x, z, y) × 100cm, quaternion(qx, qy, qz, qw)→FQuat(-qx, -qz, -qy, qw), hull triangles in Unreal's front-face order). Swapping y and z keeps the look of the scene (nothing is mirrored). Integer values (*Mm, settings, input) stay in core coordinates
- Coordinates: the core is right-handed with y up and metres; Unreal is left-handed with z up and centimetres. Values returned as
- 3D, your own rules (detphys_rt.h, detphys_turn.h, detphys3d.h, detphys3d_kinematic.h): subclass
UDetPhysRtRule3D(real time) orUDetPhysTurnRule3D(turn based) in C++ and pass it toUDetPhysRtSession::Create3D(Outer, Settings, World, Rule, LocalPeer, Link)orUDetPhysTurnSession::Create3D(Outer, Settings, World, Rule, LocalPeer, Link). The virtual functions are the same as Unity'sDetPhysRtRule3D/DetPhysTurnRule3D(real time:GetInputWords,GetStateWords,GetRuleId,GetParams,UsesKinematic,Begin,ApplyInputs,AfterTick,Predict; turn based:BeginMatch,CheckInput,ApplyInput,AfterTick[EDetPhysTurnTick],EndTurn). TheFDetPhysRtContext3D/FDetPhysTurnContext3Da callback gets givesGetWorld()(thedetphys3d_world*: create bodies and hulls, apply forces and read with the core's C ABI),GetState/SetState,GetTick,GetKinematic()(withUsesKinematic, the kinematic tabledetphys3d_the session owns: add moving concave bodies inkinematic* Begin) andFail. Turn speeds into integers withFDetPhysRule3DMath::FloorMilli. 3D readback of a turn-based session:Is3D,ReadTransforms3D,ReadBodies3D,GetBody3D,GetBodyShapes3D,GetHull3DCount,GetHull3DMesh,GetWorld3DStats,GetWorldHash,ReadState,CheckMovingField. C++:GetDetPhysWorld3D(),GetKinematic3D()- Rules for rules: results may depend only on the inputs, the context, the world and
GetParams, computed with integers. Real-time callbacks run again for the same tick on every rollback, so keep match state in the world and in the state words (members of the rule object are not rolled back). Register hulls inBegin(BeginMatch) in the same order on every peer. Change the kinematic table only inBegin - Sample rules (
DetPhysSampleRules3D.inh DetPhysSample):UDetPhysSamplePush3DRule(the 3D push written in C++; its params and rule id equal the built-in rule's, so it also connects to built-in peers),UDetPhysSampleStack3DRule(3D stacking, turn based),UDetPhysSampleSpinTableRule(a spinning octagonal table, a concave body moved by the kinematic table)
- Rules for rules: results may depend only on the inputs, the context, the world and
- Desync debugger (session interface):
SetDebug,GetDesyncReportCount,GetDesyncReport,DebugNudgeAt(tests),FDetPhysDebugSettings,FDetPhysDesyncReport - Peers whose config check does not match:
UDetPhysTurnSession::GetTagInfo,UDetPhysRtSession::GetTagInfo(false with an older core),FDetPhysTagInfo(integers only; C++ hasIsActive()and the like),UDetPhysLibrary::TagPartName,TagPartNames, 512 inFDetPhysRtFrame.(Flags DETPHYS_)RT_ FRAME_ TAG_ MISMATCH - Transports (detphys_udp.h, loopback):
UDetPhysLink(UdpListen,UdpConnect,SetFaults[tests],GetLocalPort),UDetPhysLoopback(CreateLoopback,GetSide,Pump) - Pluggable transport, room codes (detphys_link.h), own relay (detphys_relay.h):
UDetPhysLink(staticCreateRelay(Host, Port, LocalPort),HostRoom(Bucket, Code, Entropy, TimeoutMs),JoinRoom(Code, Bucket, TimeoutMs),Poll,GetState,GetRole[0 / 1, -1 before],GetPath,GetRoomCode,GetInfo,GetInfoText,GetLinkError,Close[leaves the room],IsRoomLink, staticRoomCodeMake,RoomCodeParse,RoomCodeCheck,StateName,ReasonName,PathName,SplitHostPort,IsRoomApiAvailable;SetFaultsworks as before),FDetPhysLinkInfo,EDetPhysLinkState,EDetPhysLinkPath,EDetPhysLinkReason,UDetPhysLinkHub(test lobby:CreateHub,CreateLink,Pump,GetRoomCount),UDetPhysRoomOpener(OpenRelayRoom,OpenHubRoom, C++Open: make / enter a room and wait for the role, a guest that comes first enters again;Poll,GetRole,GetLink,GetAttempts,GetFailResult,GetFailReason) - EOS P2P transport (detphys_eos.h version 2; a separate library,
detphys_eos; Windows x64):UDetPhysEos(IsEosAvailable,GetEosError,GetEosSdkVersion,GetEosLocation,LoadEosSettings,FindEosSettingsFile,CreateEosLink(Outer, Settings),OpenEosRoom(Outer, Settings, bHost, Code, Bucket, Entropy, RetryForMs, RetryEveryMs, TimeoutMs),DescribeEosSettings,ParseEosRelay,ShutdownEos),FDetPhysEosSettings(ProductId,SandboxId,DeploymentId,ClientId,ClientSecret[Transient],ProductName,ProductVersion,DisplayName,CacheDir,Relay[EDetPhysEosRelay:Allow/Force/Never],LoginTimeoutMs,LogLevel,bNewDeviceId[tests only]). The link is aUDetPhysLink(GetKind()is"eos") andClosefrees it at once.detphys_eos.dllis loaded when it is first used, so the plugin works without it. This is not Unreal's Online Subsystem EOS - Match ActorComponents and Delegates (Godot's
DetPhysRtMatch/DetPhysStackMatch):UDetPhysRtMatchComponent(Settings,Rules,LocalInput[C++:InputSource],StepFrame/StepFrameAt,GetSession,WasRolledBack,WasReplaced; DelegatesOnTickConfirmed,OnDesync,OnResynced,OnRejoined,OnInputDelayChanged),UDetPhysStackMatchComponent(Settings,Rules,TicksPerFrame,Speed,Submit,StepTicks; DelegatesOnLocalTurn,OnTurnFinished,OnMatchFinished,OnWorldReplaced). Both haveStartWithLink(LocalPeer, Link),HostRelayRoom/JoinRelayRoom,StartRoom(UDetPhysRoomOpener),Stop,Shapes/ShapeFiles,RoomBucket,bAutoStep, and the shared DelegatesOnConnected,OnPeerLost,OnFailed,OnTagMismatch,OnLinkStateChanged,OnRoomReady- Your own 2D rules:
CustomRuleonUDetPhysRtMatchComponentandUDetPhysStackMatchComponent(yourUDetPhysRtRule/UDetPhysTurnRule; empty = the built-in rule with the values inRules). With your own rule,OnLocalTurn'sShapeis what the rule'sShapeAtanswers andOnMatchFinished'sWinneris -1 (the rule decides the winner in the result'sStatewords) - 3D:
UDetPhysRtMatch3DComponent(World,Rule[yourUDetPhysRtRule3D; empty = the built-in 3D push with the values inRules3D];Settingsstart with FULL snapshots) andUDetPhysTurnMatch3DComponent(World,Rule[yourUDetPhysTurnRule3D, required]). Stepping, input, Delegates and the ways to connect are the same as the 2D components (OnLocalTurn'sShapeandOnMatchFinished'sWinnerare -1; the rule's state words in the result tell who won). Draw with the*3Dfunctions ofGetSession()
- Your own 2D rules:
- Shapes, input quantization:
UDetPhysLibrary(LoadShapeFile/LoadShapeFiles,ShapesFingerprint,QuantizeMove,QuantizeMm,QuantizeMrad,MakePushInput, automatic movesAutoStackInput/AutoPushInputs,NowUs),FDetPhysShapeData - Everything else: Call the C ABI of the
DetPhysCoremodule directly from C++ (header copies inSource/)ThirdParty/ DetPhysCore/ include
- Everything above can be called from Blueprint (settings and results are integer-only USTRUCTs). When you use the sessions directly, your code drives
Poll/Advanceevery frame. Add a match component to an Actor instead and it steps in Tick and reports what happened through Delegates (Blueprint "bind event"). - Call
Pollon a room link (relay, hub) every frame (the relay's ping and time-outs run there); the components do it themselves. Anything sent before the role (GetRole) is known is dropped (the session sends it again). - After
OnTagMismatch, aUDetPhysRtMatchComponentsession keeps waiting (the game decides whether to stop; the sample shows it and callsStop). ForUDetPhysStackMatchComponentthe core turns a peer with a different config hash into ERROR, soOnFailedfollows right afterOnTagMismatch. - With the same settings, a 3D push session connects to Unity and Godot 3D push peers with the same settings, with the same confirmed tick hashes. A wrapper for your own transport written in C++ / Blueprint (a vtable given to
detphys_) is (planned). C++ can use all of them through the core's C ABI today.link_ create