castle-web-cli 0.4.204 → 0.4.206

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/agent-failures.d.ts +3 -1
  2. package/dist/agent-failures.js +19 -0
  3. package/dist/agent-prompts.d.ts +1 -0
  4. package/dist/agent-prompts.js +7 -2
  5. package/dist/agent.d.ts +3 -2
  6. package/dist/agent.js +29 -18
  7. package/dist/castle-host/host.d.ts +17 -0
  8. package/dist/castle-host/host.js +551 -4
  9. package/dist/devSessionStorage.js +65 -4
  10. package/dist/effortSupport.d.ts +7 -0
  11. package/dist/effortSupport.js +31 -0
  12. package/dist/imports.d.ts +1 -1
  13. package/dist/imports.js +59 -19
  14. package/dist/index.js +4 -3
  15. package/dist/init.d.ts +9 -1
  16. package/dist/init.js +64 -25
  17. package/dist/kitCatalog.d.ts +13 -0
  18. package/dist/kitCatalog.js +111 -0
  19. package/dist/platformDoc.js +7 -2
  20. package/dist/serve.js +35 -2
  21. package/dist/shell/assets/{index-DHzA0-Sj.js → index-hWQTC8q6.js} +5 -5
  22. package/dist/shell/index.html +1 -1
  23. package/dist/vitePlugins.js +19 -1
  24. package/kits/base/CLAUDE.md +2 -0
  25. package/kits/base/castle.json +1 -1
  26. package/kits/base/sdk/README.md +131 -0
  27. package/kits/base/sdk/agent.d.ts +6 -0
  28. package/kits/base/sdk/agent.js +70 -0
  29. package/kits/base/sdk/castle.d.ts +4 -0
  30. package/kits/base/sdk/castle.js +2 -0
  31. package/kits/base/sdk/commands.d.ts +106 -0
  32. package/kits/base/sdk/commands.js +21 -0
  33. package/kits/base/sdk/decks.d.ts +7 -0
  34. package/kits/base/sdk/decks.js +31 -0
  35. package/kits/base/sdk/runtime.d.ts +4 -2
  36. package/kits/base/sdk/runtime.js +51 -40
  37. package/kits/base/sdk/server/storage.d.ts +44 -0
  38. package/kits/base/sdk/server/storage.js +54 -0
  39. package/kits/base/sdk/transport.d.ts +5 -1
  40. package/kits/base/sdk/transport.js +106 -23
  41. package/kits/multiplayer-2d/castle.json +5 -4
  42. package/kits/multiplayer-2d/code/client/poses.js +7 -0
  43. package/kits/multiplayer-2d/code/server/limits.js +3 -0
  44. package/kits/multiplayer-2d/code/server/ownership.js +36 -8
  45. package/kits/multiplayer-2d/code/systems/multiplayer.js +23 -2
  46. package/kits/multiplayer-3d/CLAUDE.md +12 -1
  47. package/kits/multiplayer-3d/castle.json +5 -4
  48. package/kits/multiplayer-3d/code/client/avatars.js +7 -1
  49. package/kits/multiplayer-3d/code/client/poses.js +61 -1
  50. package/kits/multiplayer-3d/code/client/steer.js +383 -0
  51. package/kits/multiplayer-3d/code/server/limits.js +3 -0
  52. package/kits/multiplayer-3d/code/server/ownership.js +114 -18
  53. package/kits/multiplayer-3d/code/server/world.js +12 -4
  54. package/kits/multiplayer-3d/code/systems/multiplayer.js +315 -34
  55. package/kits/physics-2d/castle.json +1 -0
  56. package/kits/physics-3d/CLAUDE.md +65 -7
  57. package/kits/physics-3d/castle.json +4 -3
  58. package/kits/physics-3d/docs/pxmodel-format.md +916 -15
  59. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  60. package/kits/physics-3d/engine3d/artobjects.js +218 -0
  61. package/kits/physics-3d/engine3d/blob.js +1058 -0
  62. package/kits/physics-3d/engine3d/branches.js +300 -0
  63. package/kits/physics-3d/engine3d/cage.js +496 -0
  64. package/kits/physics-3d/engine3d/cageops.js +516 -0
  65. package/kits/physics-3d/engine3d/frame.js +669 -0
  66. package/kits/physics-3d/engine3d/look.js +675 -0
  67. package/kits/physics-3d/engine3d/materialpresets.js +486 -0
  68. package/kits/physics-3d/engine3d/modelEditorWorld.js +3 -2
  69. package/kits/physics-3d/engine3d/modelrefs.js +120 -0
  70. package/kits/physics-3d/engine3d/motion.js +560 -0
  71. package/kits/physics-3d/engine3d/objtext.js +37 -0
  72. package/kits/physics-3d/engine3d/optimize.js +1083 -0
  73. package/kits/physics-3d/engine3d/paint.js +674 -0
  74. package/kits/physics-3d/engine3d/partgeometry.js +467 -0
  75. package/kits/physics-3d/engine3d/paths.js +324 -0
  76. package/kits/physics-3d/engine3d/pxmodel.js +429 -26
  77. package/kits/physics-3d/engine3d/scatter.js +102 -0
  78. package/kits/physics-3d/engine3d/sculpt.js +1148 -0
  79. package/kits/physics-3d/engine3d/surfacedetail.js +267 -0
  80. package/kits/physics-3d/engine3d/sweep.js +480 -0
  81. package/kits/physics-3d/engine3d/thumbnails.js +6 -4
  82. package/kits/physics-3d/engine3d/world3d.js +119 -17
  83. package/kits/physics-3d/eslint.config.js +13 -0
  84. package/kits/physics-3d/models/parts/axe.pxmodel +40 -0
  85. package/kits/physics-3d/models/parts/backpack.pxmodel +47 -0
  86. package/kits/physics-3d/models/parts/barrel.pxmodel +22 -0
  87. package/kits/physics-3d/models/parts/bedroll.pxmodel +28 -0
  88. package/kits/physics-3d/models/parts/belt-pouch.pxmodel +22 -0
  89. package/kits/physics-3d/models/parts/bolt.pxmodel +10 -0
  90. package/kits/physics-3d/models/parts/bracer.pxmodel +26 -0
  91. package/kits/physics-3d/models/parts/chain-span.pxmodel +12 -0
  92. package/kits/physics-3d/models/parts/chimney.pxmodel +11 -0
  93. package/kits/physics-3d/models/parts/crate.pxmodel +44 -0
  94. package/kits/physics-3d/models/parts/crystal.pxmodel +22 -0
  95. package/kits/physics-3d/models/parts/door-arched.pxmodel +12 -0
  96. package/kits/physics-3d/models/parts/engine-block.pxmodel +39 -0
  97. package/kits/physics-3d/models/parts/exhaust-pipe.pxmodel +30 -0
  98. package/kits/physics-3d/models/parts/fence-span.pxmodel +10 -0
  99. package/kits/physics-3d/models/parts/fender.pxmodel +19 -0
  100. package/kits/physics-3d/models/parts/headlight.pxmodel +24 -0
  101. package/kits/physics-3d/models/parts/hood.pxmodel +17 -0
  102. package/kits/physics-3d/models/parts/horned-helmet.pxmodel +37 -0
  103. package/kits/physics-3d/models/parts/jerry-can.pxmodel +26 -0
  104. package/kits/physics-3d/models/parts/ladder.pxmodel +10 -0
  105. package/kits/physics-3d/models/parts/lamp.pxmodel +20 -0
  106. package/kits/physics-3d/models/parts/lantern.pxmodel +30 -0
  107. package/kits/physics-3d/models/parts/leaf-cluster.pxmodel +21 -0
  108. package/kits/physics-3d/models/parts/offroad-tire.pxmodel +48 -0
  109. package/kits/physics-3d/models/parts/pauldron.pxmodel +26 -0
  110. package/kits/physics-3d/models/parts/rivet.pxmodel +8 -0
  111. package/kits/physics-3d/models/parts/rock.pxmodel +21 -0
  112. package/kits/physics-3d/models/parts/roll-bar-light.pxmodel +26 -0
  113. package/kits/physics-3d/models/parts/round-shield.pxmodel +31 -0
  114. package/kits/physics-3d/models/parts/saddlebag.pxmodel +30 -0
  115. package/kits/physics-3d/models/parts/spoked-wheel.pxmodel +39 -0
  116. package/kits/physics-3d/models/parts/staff.pxmodel +33 -0
  117. package/kits/physics-3d/models/parts/stepping-stones.pxmodel +8 -0
  118. package/kits/physics-3d/models/parts/stone-base.pxmodel +10 -0
  119. package/kits/physics-3d/models/parts/sword.pxmodel +33 -0
  120. package/kits/physics-3d/models/parts/window-lit.pxmodel +13 -0
  121. package/kits/physics-3d/models/parts/wizard-hat.pxmodel +28 -0
  122. package/kits/physics-3d/models/templates/biped-stout.pxmodel +59 -0
  123. package/kits/physics-3d/models/templates/biped-tall.pxmodel +63 -0
  124. package/kits/physics-3d/models/templates/quadruped.pxmodel +52 -0
  125. package/kits/physics-3d/scripts/render/filmstrip.js +217 -0
  126. package/kits/physics-3d/scripts/render/index.html +20 -0
  127. package/kits/physics-3d/scripts/render/sheet.js +411 -0
  128. package/kits/physics-3d/scripts/render.mjs +646 -0
  129. package/kits/real-time/castle.json +2 -2
  130. package/kits/real-time/code/client/ownership.js +14 -4
  131. package/kits/real-time/code/client/smooth.js +2 -2
  132. package/kits/real-time/code/server/session.js +20 -4
  133. package/kits/turn-based/castle.json +1 -0
  134. package/package.json +2 -2
@@ -5,7 +5,9 @@
5
5
  // Two forms. A player pose is `[x, y, z, facing]`: the body stays upright, so
6
6
  // one yaw value is its whole orientation. Every other pose is
7
7
  // `[x, y, z, qx, qy, qz, qw]`, the same shape the server sends back for what
8
- // it simulates. Units are metres and radians.
8
+ // it simulates. Units are metres and radians. On the wire an object's pose is
9
+ // followed by its ownership epoch (`server/ownership.js`), which the client
10
+ // system strips before the pose reaches anything here.
9
11
  //
10
12
  // Wire packing comes first, then writes onto an engine Transform, then the
11
13
  // comparisons, blends and measurements the core takes as callbacks.
@@ -43,6 +45,7 @@ export const REACH = { radius: CLAIM_RADIUS, distanceBetween: flatDistance };
43
45
  const qa = new THREE.Quaternion();
44
46
  const qb = new THREE.Quaternion();
45
47
  const euler = new THREE.Euler();
48
+ const axis = new THREE.Vector3();
46
49
 
47
50
  //
48
51
  // Packing for the wire
@@ -53,6 +56,20 @@ export function packPose(p, q) {
53
56
  return [round(p.x), round(p.y), round(p.z), round(q.x), round(q.y), round(q.z), round(q.w)];
54
57
  }
55
58
 
59
+ // Pack a body's velocity as `[vx, vy, vz, wx, wy, wz]`: linear in metres per
60
+ // second, then angular in radians per second about each axis. It follows an
61
+ // owned object's pose in a move report and a grant in a handover.
62
+ export function packVelocity(linear, angular) {
63
+ return [
64
+ round(linear.x),
65
+ round(linear.y),
66
+ round(linear.z),
67
+ round(angular.x),
68
+ round(angular.y),
69
+ round(angular.z),
70
+ ];
71
+ }
72
+
56
73
  // Pack an upright player as `[x, y, z, facing, clamped]`.
57
74
  //
58
75
  // `clamped` is 1 only on the tick a player's own move was refused for being
@@ -197,6 +214,49 @@ export function advance(shown, target, f) {
197
214
  shown[6] = qa.w;
198
215
  }
199
216
 
217
+ // Return a full pose moved `seconds` forward at `velocity`, which is
218
+ // `[vx, vy, vz, wx, wy, wz]` as `packVelocity` makes it. Angular velocity is
219
+ // about world axes, so its turn is applied before the pose's own rotation.
220
+ export function project(pose, velocity, seconds) {
221
+ const [vx, vy, vz, wx, wy, wz] = velocity;
222
+ const spin = Math.hypot(wx, wy, wz);
223
+ qa.set(pose[3], pose[4], pose[5], pose[6]);
224
+ if (spin > 0) {
225
+ qb.setFromAxisAngle(axis.set(wx / spin, wy / spin, wz / spin), spin * seconds);
226
+ qa.premultiply(qb);
227
+ }
228
+ return [
229
+ pose[0] + vx * seconds,
230
+ pose[1] + vy * seconds,
231
+ pose[2] + vz * seconds,
232
+ qa.x,
233
+ qa.y,
234
+ qa.z,
235
+ qa.w,
236
+ ];
237
+ }
238
+
239
+ // The velocity that carries full pose `a` to full pose `b` in `seconds`, as
240
+ // `[vx, vy, vz, wx, wy, wz]`, the form `packVelocity` makes.
241
+ export function velocityBetween(a, b, seconds) {
242
+ return offsetBetween(a, b).map((value) => value / seconds);
243
+ }
244
+
245
+ // How far full pose `b` is from full pose `a`, as `[dx, dy, dz, rx, ry, rz]`:
246
+ // the move in metres, then the turn as a vector along its world axis whose
247
+ // length is the angle in radians, taken the shorter way round. `project` with
248
+ // this as the velocity and one second carries `a` to `b`.
249
+ export function offsetBetween(a, b) {
250
+ qa.set(a[3], a[4], a[5], a[6]).invert();
251
+ qb.set(b[3], b[4], b[5], b[6]).multiply(qa);
252
+ if (qb.w < 0) {
253
+ qb.set(-qb.x, -qb.y, -qb.z, -qb.w);
254
+ }
255
+ const sine = Math.hypot(qb.x, qb.y, qb.z);
256
+ const scale = sine > 1e-9 ? (2 * Math.atan2(sine, qb.w)) / sine : 2;
257
+ return [b[0] - a[0], b[1] - a[1], b[2] - a[2], qb.x * scale, qb.y * scale, qb.z * scale];
258
+ }
259
+
200
260
  // Ground-plane distance. An object on a shelf belongs to the player below it,
201
261
  // and a vertically sliding object stays the same distance away.
202
262
  export function flatDistance(a, b) {
@@ -0,0 +1,383 @@
1
+ // Live local bodies for network objects near this player. A live body is a
2
+ // dynamic rapier body that runs in the local physics world at the present, and
3
+ // each frame its velocity is pulled toward where the network has the object
4
+ // now: the newest network pose moved forward by the object's velocity. It
5
+ // collides with the local player as the object is, not as it was a render
6
+ // delay ago, and when this client is granted the object its body is already
7
+ // where the object is.
8
+ //
9
+ // The move from the newest network pose to the present is swept through the
10
+ // local world with the object's own colliders, and the target stops at the
11
+ // first thing in the way. A falling object's target lands on the ground, not
12
+ // under it, and the body is only ever moved at once to a pose that is clear.
13
+ // The body's own velocity is cut to what reaches the first surface in its way
14
+ // in a frame.
15
+ //
16
+ // Objects further off are drawn from interpolated network poses. The client
17
+ // system moves an object between the two only while it is at rest, so the
18
+ // drawn object never has to take up the render delay while it moves.
19
+ //
20
+ // Poses are the full object form of `poses.js`, `[x, y, z, qx, qy, qz, qw]`.
21
+
22
+ import RAPIER from '@dimforge/rapier3d-compat';
23
+ import * as THREE from 'three';
24
+ import * as Poses from './poses.js';
25
+
26
+ // An object at rest within this ground distance of the local player is live,
27
+ // and one at rest beyond it is interpolated. It is twice the claim radius. A
28
+ // moving object within the claim radius is made live at once, since this
29
+ // client may be granted it.
30
+ export const LIVE_RADIUS = 2 * Poses.REACH.radius;
31
+
32
+ // The object's velocity is read from its two newest network poses at least
33
+ // this far apart in simulation time, so the uneven spacing of reports on the
34
+ // server's ticks averages out.
35
+ const VELOCITY_SPAN_MS = 100;
36
+
37
+ // The server sends an object's pose only when it moved. With no pose for this
38
+ // long, the object has stopped where the newest pose left it.
39
+ const REST_AFTER_MS = 200;
40
+
41
+ // One server tick at 30 Hz. An object that was at rest before a pose is taken
42
+ // to have been at rest until one tick before it.
43
+ const TICK_MS = 34;
44
+
45
+ // Below these speeds, in metres and radians a second, an object is at rest.
46
+ const REST_SPEED = 0.05;
47
+ const REST_SPIN = 0.2;
48
+
49
+ // A live body at rest within these of the network pose is left alone, so it
50
+ // can fall asleep.
51
+ const REST_DISTANCE = 0.02;
52
+ const REST_TURN = 0.05;
53
+
54
+ // Steering. The body's velocity closes on the target velocity at FOLLOW_RATE a
55
+ // second, and the target velocity is the object's velocity plus MOVE_GAIN (or
56
+ // TURN_GAIN) times the distance still to go. FOLLOW_RATE is four times the
57
+ // gain, so the distance closes without overshoot (a critically damped spring).
58
+ const FOLLOW_RATE = 20;
59
+ const MOVE_GAIN = 5;
60
+ const TURN_GAIN = 5;
61
+
62
+ // A body further than SNAP_DISTANCE from the network pose is moved there at
63
+ // once. So is one held further than STUCK_DISTANCE for STUCK_MS, which is a
64
+ // body the local world will not let through.
65
+ const SNAP_DISTANCE = 1.5;
66
+ const STUCK_DISTANCE = 0.5;
67
+ const STUCK_MS = 500;
68
+
69
+ // Sweeping. A move shorter than MIN_MOVE is not swept. A shape that starts on
70
+ // a surface, as an object at rest on the ground does, can report a hit at once
71
+ // even when it moves along the surface, and a flat face sliding on a
72
+ // heightfield catches on the edges between its triangles. So a cast starts
73
+ // LIFT higher, and a hit within START_GAP of that start is cast again from LIFT
74
+ // off the surface hit. A move into a surface still hits it. A pose more than
75
+ // OVERLAP inside another collider is not moved to.
76
+ const MIN_MOVE = 0.001;
77
+ const START_GAP = 0.0001;
78
+ const LIFT = 0.02;
79
+ const OVERLAP = 0.05;
80
+
81
+ // Casts and overlap tests pass through sensors and kinematic bodies, which
82
+ // are other players and doors.
83
+ const PASSED = RAPIER.QueryFilterFlags.EXCLUDE_KINEMATIC | RAPIER.QueryFilterFlags.EXCLUDE_SENSORS;
84
+
85
+ const AT_REST = [0, 0, 0, 0, 0, 0];
86
+
87
+ // Create the steering state of one live body. `offSince` is when it last went
88
+ // further than STUCK_DISTANCE from the network pose, or null.
89
+ export function makeState() {
90
+ return { offSince: null };
91
+ }
92
+
93
+ // Where the network has an object at simulation time `serverMs`, and how it is
94
+ // moving: `{ pose, velocity, resting, from }`, or null when `track` is empty.
95
+ // `from` is the newest network pose, which `pose` is projected from. `handed`
96
+ // is the object's newest handover, `{ velocity, simMs }`, whose velocity
97
+ // stands in until the track has two poses far enough apart.
98
+ export function networkAt(track, handed, serverMs) {
99
+ const samples = track.samples;
100
+ const newest = samples.at(-1);
101
+ if (!newest) {
102
+ return null;
103
+ }
104
+ const age = Math.max(0, serverMs - newest.simMs);
105
+ if (age > REST_AFTER_MS) {
106
+ return { pose: newest.pose, velocity: AT_REST, resting: true, from: newest.pose };
107
+ }
108
+ const velocity =
109
+ trackVelocity(samples) ?? (handed?.simMs >= samples[0].simMs ? handed.velocity : AT_REST);
110
+ return {
111
+ pose: Poses.project(newest.pose, velocity, age / 1000),
112
+ velocity,
113
+ resting: slow(velocity),
114
+ from: newest.pose,
115
+ };
116
+ }
117
+
118
+ // `network` from `networkAt`, stopped at the first collider of the local
119
+ // `world` between its `from` and its `pose`, or `network` itself when nothing
120
+ // is in the way. `body` is the object's own rapier body, whose colliders are
121
+ // cast, and `player` is the local player's body, which is passed through. At a
122
+ // hit the velocity loses its part into the surface hit.
123
+ export function sweep(world, body, network, player) {
124
+ if (!world || !network) {
125
+ return network;
126
+ }
127
+ const from = network.from;
128
+ const move = {
129
+ x: network.pose[0] - from[0],
130
+ y: network.pose[1] - from[1],
131
+ z: network.pose[2] - from[2],
132
+ };
133
+ const length = Math.hypot(move.x, move.y, move.z);
134
+ if (length < MIN_MOVE) {
135
+ return network;
136
+ }
137
+ const first = firstHit(world, body, from, move, length, player);
138
+ if (!first) {
139
+ return network;
140
+ }
141
+ const t = first.time_of_impact;
142
+ const n = first.normal1;
143
+ const [vx, vy, vz, wx, wy, wz] = network.velocity;
144
+
145
+ // `normal1` is the surface's normal, pointing out of it toward the object.
146
+ const into = Math.min(0, vx * n.x + vy * n.y + vz * n.z);
147
+ const velocity = [vx - into * n.x, vy - into * n.y, vz - into * n.z, wx, wy, wz];
148
+ return {
149
+ pose: [
150
+ from[0] + move.x * t,
151
+ from[1] + move.y * t,
152
+ from[2] + move.z * t,
153
+ ...network.pose.slice(3),
154
+ ],
155
+ velocity,
156
+ resting: slow(velocity),
157
+ from,
158
+ };
159
+ }
160
+
161
+ // The first hit of `body`'s colliders moved by `move` from where they sit when
162
+ // the body is at `from`, or null. `length` is the length of `move`.
163
+ function firstHit(world, body, from, move, length, player) {
164
+ const filter = passing(player);
165
+ let first = null;
166
+ for (let i = 0; i < body.numColliders(); i += 1) {
167
+ const hit = castCollider(world, body, body.collider(i), from, move, length, filter);
168
+ if (hit && (!first || hit.time_of_impact < first.time_of_impact)) {
169
+ first = hit;
170
+ }
171
+ }
172
+ return first;
173
+ }
174
+
175
+ // The first hit of one of a body's colliders, as `firstHit` has it.
176
+ function castCollider(world, body, collider, from, move, length, filter) {
177
+ const { at, rotation } = colliderAt(collider, from);
178
+ const cast = (start) =>
179
+ world.castShape(
180
+ start,
181
+ rotation,
182
+ move,
183
+ collider.shape,
184
+ 0,
185
+ 1,
186
+ false,
187
+ PASSED,
188
+ undefined,
189
+ undefined,
190
+ body,
191
+ filter,
192
+ );
193
+ const start = { x: at.x, y: at.y + LIFT, z: at.z };
194
+ const hit = cast(start);
195
+ if (!hit || hit.time_of_impact * length > START_GAP) {
196
+ return hit;
197
+ }
198
+ const n = hit.normal1;
199
+ return cast({ x: start.x + n.x * LIFT, y: start.y + n.y * LIFT, z: start.z + n.z * LIFT });
200
+ }
201
+
202
+ // Whether `pose` would put `body` more than OVERLAP inside another collider of
203
+ // the local `world`. Rapier gives no depth against a heightfield or a triangle
204
+ // mesh, so those never count; a pose from `sweep` is not under them.
205
+ function overlaps(world, body, pose, player) {
206
+ const filter = passing(player);
207
+ let inside = false;
208
+ for (let i = 0; i < body.numColliders() && !inside; i += 1) {
209
+ const collider = body.collider(i);
210
+ const { at, rotation } = colliderAt(collider, pose);
211
+ world.intersectionsWithShape(
212
+ at,
213
+ rotation,
214
+ collider.shape,
215
+ (other) => {
216
+ const contact = collider.shape.contactShape(
217
+ at,
218
+ rotation,
219
+ other.shape,
220
+ other.translation(),
221
+ other.rotation(),
222
+ 0,
223
+ );
224
+ inside = Boolean(contact) && contact.distance < -OVERLAP;
225
+ return !inside;
226
+ },
227
+ PASSED,
228
+ undefined,
229
+ undefined,
230
+ body,
231
+ filter,
232
+ );
233
+ }
234
+ return inside;
235
+ }
236
+
237
+ // Where a body's collider is, `{ at, rotation }`, when the body is at `pose`.
238
+ function colliderAt(collider, pose) {
239
+ const turn = Poses.quatOf(pose);
240
+ const rotation = new THREE.Quaternion(turn.x, turn.y, turn.z, turn.w);
241
+ const offset = collider.translationWrtParent();
242
+ const at = new THREE.Vector3(offset?.x ?? 0, offset?.y ?? 0, offset?.z ?? 0)
243
+ .applyQuaternion(rotation)
244
+ .add(new THREE.Vector3(pose[0], pose[1], pose[2]));
245
+ const own = collider.rotationWrtParent();
246
+ if (own) {
247
+ rotation.multiply(new THREE.Quaternion(own.x, own.y, own.z, own.w));
248
+ }
249
+ return {
250
+ at: { x: at.x, y: at.y, z: at.z },
251
+ rotation: { x: rotation.x, y: rotation.y, z: rotation.z, w: rotation.w },
252
+ };
253
+ }
254
+
255
+ // A query filter that passes through `player`'s colliders, or none.
256
+ function passing(player) {
257
+ return player ? (collider) => collider.parent()?.handle !== player.handle : undefined;
258
+ }
259
+
260
+ // The velocity between the newest pose and the newest one at least
261
+ // VELOCITY_SPAN_MS before it, or null when the track does not span that long.
262
+ // A gap of REST_AFTER_MS between two poses is a rest, which ended one tick
263
+ // before the later pose, so an object that has just started moving gets its
264
+ // velocity from its first moving pose.
265
+ function trackVelocity(samples) {
266
+ const newest = samples.at(-1);
267
+ for (let i = samples.length - 2; i >= 0; i -= 1) {
268
+ const later = samples[i + 1].simMs;
269
+ const since = later - samples[i].simMs > REST_AFTER_MS ? later - TICK_MS : samples[i].simMs;
270
+ const span = newest.simMs - since;
271
+ if (span >= VELOCITY_SPAN_MS || since !== samples[i].simMs) {
272
+ return Poses.velocityBetween(samples[i].pose, newest.pose, span / 1000);
273
+ }
274
+ }
275
+ return null;
276
+ }
277
+
278
+ // Whether a `[vx, vy, vz, wx, wy, wz]` velocity is at rest.
279
+ function slow(velocity) {
280
+ const [vx, vy, vz, wx, wy, wz] = velocity;
281
+ return Math.hypot(vx, vy, vz) < REST_SPEED && Math.hypot(wx, wy, wz) < REST_SPIN;
282
+ }
283
+
284
+ // Whether a rapier body is at rest.
285
+ export function resting(body) {
286
+ if (body.isSleeping()) {
287
+ return true;
288
+ }
289
+ const v = body.linvel();
290
+ const w = body.angvel();
291
+ return slow([v.x, v.y, v.z, w.x, w.y, w.z]);
292
+ }
293
+
294
+ // Move a body to `pose` with `velocity`. `wake` false leaves a sleeping body
295
+ // asleep.
296
+ export function place(body, pose, velocity, wake = true) {
297
+ const [vx, vy, vz, wx, wy, wz] = velocity;
298
+ body.setTranslation({ x: pose[0], y: pose[1], z: pose[2] }, wake);
299
+ body.setRotation(Poses.quatOf(pose), wake);
300
+ body.setLinvel({ x: vx, y: vy, z: vz }, wake);
301
+ body.setAngvel({ x: wx, y: wy, z: wz }, wake);
302
+ }
303
+
304
+ // Pull a live body toward `network`, from `sweep`, over a frame of `dt`
305
+ // seconds. `now` is page time in milliseconds, for the stuck test. `world` is
306
+ // the local rapier world and `player` the local player's body.
307
+ export function steer(body, network, state, dt, now, world, player) {
308
+ const p = body.translation();
309
+ const q = body.rotation();
310
+ const off = Poses.offsetBetween([p.x, p.y, p.z, q.x, q.y, q.z, q.w], network.pose);
311
+ const distance = Math.hypot(off[0], off[1], off[2]);
312
+
313
+ // Steering sets velocity, which can carry a body through a thin collider in
314
+ // one physics step. Continuous collision detection stops it at a thin box or
315
+ // wall. It does not work against a heightfield, which `reaching` covers.
316
+ if (!body.isCcdEnabled()) {
317
+ body.enableCcd(true);
318
+ }
319
+
320
+ // A body that is far off, or has been held off, is moved to the network pose,
321
+ // unless that pose is inside something here. It is then steered as usual.
322
+ if (distance <= STUCK_DISTANCE) {
323
+ state.offSince = null;
324
+ } else {
325
+ state.offSince ??= now;
326
+ }
327
+ const due = distance > SNAP_DISTANCE || now - (state.offSince ?? now) > STUCK_MS;
328
+ if (due && !(world && overlaps(world, body, network.pose, player))) {
329
+ place(body, network.pose, network.velocity);
330
+ state.offSince = null;
331
+ return;
332
+ }
333
+
334
+ // At rest and in place, the body is not written.
335
+ const turn = Math.hypot(off[3], off[4], off[5]);
336
+ if (network.resting && distance < REST_DISTANCE && turn < REST_TURN && resting(body)) {
337
+ return;
338
+ }
339
+
340
+ // Close part of the gap between the body's velocity and the target velocity.
341
+ // The share closed depends on `dt`, so the pull is the same at any frame rate.
342
+ const f = 1 - Math.exp(-FOLLOW_RATE * Math.max(0, dt));
343
+ const [vx, vy, vz, wx, wy, wz] = network.velocity;
344
+ const v = body.linvel();
345
+ const w = body.angvel();
346
+ const next = {
347
+ x: v.x + (vx + MOVE_GAIN * off[0] - v.x) * f,
348
+ y: v.y + (vy + MOVE_GAIN * off[1] - v.y) * f,
349
+ z: v.z + (vz + MOVE_GAIN * off[2] - v.z) * f,
350
+ };
351
+ body.setLinvel(world ? reaching(world, body, next, dt, player) : next, true);
352
+ body.setAngvel(
353
+ {
354
+ x: w.x + (wx + TURN_GAIN * off[3] - w.x) * f,
355
+ y: w.y + (wy + TURN_GAIN * off[4] - w.y) * f,
356
+ z: w.z + (wz + TURN_GAIN * off[5] - w.z) * f,
357
+ },
358
+ true,
359
+ );
360
+ }
361
+
362
+ // `velocity` for `body` over the next frame of `dt` seconds, with its part into
363
+ // the first surface in the way cut to what reaches that surface. The physics
364
+ // steps can carry a fast body through a heightfield, which continuous
365
+ // collision detection does not stop. A frame runs at least one 60 Hz step.
366
+ function reaching(world, body, velocity, dt, player) {
367
+ const seconds = Math.max(dt, 1 / 60);
368
+ const move = { x: velocity.x * seconds, y: velocity.y * seconds, z: velocity.z * seconds };
369
+ const length = Math.hypot(move.x, move.y, move.z);
370
+ if (length < MIN_MOVE) {
371
+ return velocity;
372
+ }
373
+ const p = body.translation();
374
+ const q = body.rotation();
375
+ const hit = firstHit(world, body, [p.x, p.y, p.z, q.x, q.y, q.z, q.w], move, length, player);
376
+ const n = hit?.normal1;
377
+ const into = n ? velocity.x * n.x + velocity.y * n.y + velocity.z * n.z : 0;
378
+ if (into >= 0) {
379
+ return velocity;
380
+ }
381
+ const cut = -into * (1 - hit.time_of_impact);
382
+ return { x: velocity.x + n.x * cut, y: velocity.y + n.y * cut, z: velocity.z + n.z * cut };
383
+ }
@@ -58,6 +58,9 @@ export const OWNER_TIMEOUT_MS = 1500;
58
58
  // Reject client-owned object reports above this generous physical speed.
59
59
  export const MAX_OBJECT_SPEED = 40;
60
60
 
61
+ // Cap the spin an owner may report, in radians per second.
62
+ export const MAX_OBJECT_SPIN = 60;
63
+
61
64
  //
62
65
  // What the world does on its own
63
66
  //
@@ -1,11 +1,23 @@
1
1
  // Server-side ownership of loose scene objects. Claims and releases change body
2
2
  // types, owner reports place granted objects, and timeout checks return abandoned
3
3
  // objects to server simulation.
4
+ //
5
+ // Every handover adds one to the object's epoch. The epoch goes out with the
6
+ // handover and with each broadcast pose, and an owner's reports carry the epoch
7
+ // of the grant they were made under, so a report or a pose from before the
8
+ // latest handover is recognised and dropped.
4
9
 
5
10
  import RAPIER from '@dimforge/rapier3d-compat';
6
11
  import { number } from '@imports/castle.real-time/code/server/limits.js';
12
+ import { packVelocity } from '../client/poses.js';
7
13
  import * as Limits from './limits.js';
8
14
 
15
+ // A velocity of zero, for an owner that never reported one.
16
+ const AT_REST = [0, 0, 0, 0, 0, 0];
17
+
18
+ // Dropped stale-epoch reports are logged at most this often.
19
+ const STALE_LOG_MS = 5000;
20
+
9
21
  // Grant requested objects that are claimable, within reach, and available for
10
22
  // this player to take. The shared server grant prevents clients from retaining
11
23
  // contradictory owners for the same object.
@@ -69,28 +81,58 @@ function mayTakeOver(sim, entry, claimant, at) {
69
81
  // Transfer one object to `playerId`, or to server simulation when it is null.
70
82
  // Append the transfer to `handovers` for the next state broadcast.
71
83
  function handOver(sim, entry, id, playerId, handovers) {
84
+ const velocity = velocityOf(entry);
85
+ entry.epoch = (entry.epoch ?? 0) + 1;
86
+ entry.ack = null;
72
87
  entry.owner = playerId;
73
88
  entry.reportedAt = sim.timeMs;
74
89
  entry.claimedAt = sim.timeMs;
90
+ entry.velocity = velocity;
91
+ const pose = entry.pose;
92
+ entry.pose = null;
75
93
  if (playerId) {
76
94
  // An owned object is kinematic-position-based, so owner reports place it and
77
95
  // its collider remains active in the shared Rapier world.
78
96
  entry.body.setBodyType(RAPIER.RigidBodyType.KinematicPositionBased, true);
79
97
  } else {
80
- // A returned object becomes dynamic and starts from rest. This avoids
81
- // retaining velocity that existed only in the previous owner's local world.
98
+ // A returned object becomes dynamic and keeps the velocity it had, so a
99
+ // rolling object is still rolling when the server takes it back. Its last
100
+ // report is put on the body first: a kinematic target set for the next
101
+ // step does not reach a body that is dynamic by then.
102
+ const [vx, vy, vz, wx, wy, wz] = velocity;
103
+ if (pose) {
104
+ entry.body.setTranslation(pose.at, true);
105
+ entry.body.setRotation(pose.rotation, true);
106
+ }
82
107
  entry.body.setBodyType(RAPIER.RigidBodyType.Dynamic, true);
83
- entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true);
84
- entry.body.setAngvel({ x: 0, y: 0, z: 0 }, true);
108
+ entry.body.setLinvel({ x: vx, y: vy, z: vz }, true);
109
+ entry.body.setAngvel({ x: wx, y: wy, z: wz }, true);
85
110
  }
86
111
 
87
112
  // Wire handovers encode zero as server ownership and a player id as a grant.
113
+ // The velocity follows, and a new owner starts its local body at it. The new
114
+ // epoch comes last.
88
115
  // An optional list permits deck hooks to reuse this helper outside a broadcast.
89
- handovers?.push([id, playerId ?? 0]);
116
+ handovers?.push([id, playerId ?? 0, ...velocity, entry.epoch]);
117
+ }
118
+
119
+ // The object's velocity as `[vx, vy, vz, wx, wy, wz]`. An owned object moves at
120
+ // the velocity its owner last reported. A kinematic body's own velocity follows
121
+ // the report rate, not the object.
122
+ function velocityOf(entry) {
123
+ if (entry.owner) {
124
+ return entry.velocity ?? AT_REST;
125
+ }
126
+ return packVelocity(entry.body.linvel(), entry.body.angvel());
90
127
  }
91
128
 
92
129
  // Apply reported poses to objects granted to `playerId`. Reports for unowned or
93
- // differently owned ids are ignored.
130
+ // differently owned ids are ignored. A report is
131
+ // `[id, x, y, z, qx, qy, qz, qw, vx, vy, vz, wx, wy, wz, epoch, seq, base]`:
132
+ // the pose, then the object's velocity, which the object keeps when it is
133
+ // handed over, then the epoch of the grant, the report's sequence number, and
134
+ // the last sequence number the owner had seen acknowledged. A report from an
135
+ // older epoch is dropped. `seq` is acknowledged; `base` is not read yet.
94
136
  export function setObjectPoses(sim, playerId, poses, handovers) {
95
137
  if (!Array.isArray(poses)) {
96
138
  return;
@@ -98,9 +140,20 @@ export function setObjectPoses(sim, playerId, poses, handovers) {
98
140
 
99
141
  // Limit one message to sixteen pose checks to bound per-message server work.
100
142
  for (const pose of poses.slice(0, 16)) {
101
- const [id, x, y, z, qx, qy, qz, qw] = pose;
143
+ const [id, x, y, z, qx, qy, qz, qw, ...rest] = pose;
102
144
  const entry = sim.objects.get(id);
103
- if (entry?.owner !== playerId) {
145
+ if (!entry) {
146
+ continue;
147
+ }
148
+
149
+ // A report without an epoch comes from a client older than epochs, and is
150
+ // judged by owner alone.
151
+ const epoch = rest[6];
152
+ if (typeof epoch === 'number' && epoch < entry.epoch) {
153
+ dropStale(sim);
154
+ continue;
155
+ }
156
+ if (entry.owner !== playerId) {
104
157
  continue;
105
158
  }
106
159
  const asked = Limits.readPoint([x, y, z]);
@@ -121,16 +174,57 @@ export function setObjectPoses(sim, playerId, poses, handovers) {
121
174
  handOver(sim, entry, id, null, handovers);
122
175
  continue;
123
176
  }
177
+ const rotation = { x: number(qx), y: number(qy), z: number(qz), w: number(qw) };
124
178
  entry.body.setNextKinematicTranslation(asked);
125
- entry.body.setNextKinematicRotation({
126
- x: number(qx),
127
- y: number(qy),
128
- z: number(qz),
129
- w: number(qw),
130
- });
179
+ entry.body.setNextKinematicRotation(rotation);
180
+ entry.pose = { at: asked, rotation };
181
+ entry.velocity = readVelocity(rest.slice(0, 6));
182
+
183
+ // The acknowledgement is `[epoch, lastSeq, tAck, ageApplied, vetoedSeq]`.
184
+ // The report is steered toward as it is and nothing is vetoed yet, so the
185
+ // last two are zero.
186
+ entry.ack = [entry.epoch, number(rest[7]), sim.timeMs, 0, 0];
131
187
  }
132
188
  }
133
189
 
190
+ // Count one report dropped for an old epoch, and log the running count.
191
+ function dropStale(sim) {
192
+ sim.staleReports = (sim.staleReports ?? 0) + 1;
193
+ if (sim.timeMs - (sim.staleLoggedAt ?? -Infinity) >= STALE_LOG_MS) {
194
+ sim.staleLoggedAt = sim.timeMs;
195
+ console.log(`[multiplayer] ${sim.staleReports} stale-epoch reports dropped`);
196
+ }
197
+ }
198
+
199
+ // Return `[objectId, ...ack]` for each object whose owner's report was applied
200
+ // since the last broadcast, and clear them. The session sends these with the
201
+ // next STATE delta.
202
+ export function acks(sim) {
203
+ const out = [];
204
+ for (const [id, entry] of sim.objects) {
205
+ if (entry.ack) {
206
+ out.push([id, ...entry.ack]);
207
+ entry.ack = null;
208
+ }
209
+ }
210
+ return out;
211
+ }
212
+
213
+ // Read a reported velocity. Missing values read as zero, and each part is cut
214
+ // to the object limits so a report cannot fling the object on return.
215
+ function readVelocity(values) {
216
+ const linear = capped(values.slice(0, 3).map(number), Limits.MAX_OBJECT_SPEED);
217
+ const angular = capped(values.slice(3, 6).map(number), Limits.MAX_OBJECT_SPIN);
218
+ return [...linear, ...angular];
219
+ }
220
+
221
+ // Scale a three-part vector down to `most` in length, keeping its direction.
222
+ function capped([x = 0, y = 0, z = 0], most) {
223
+ const length = Math.hypot(x, y, z);
224
+ const scale = length > most ? most / length : 1;
225
+ return [x * scale, y * scale, z * scale];
226
+ }
227
+
134
228
  // Release objects whose owner disconnected or exceeded the report timeout. The
135
229
  // session server calls this every tick before processing new grants.
136
230
  export function sweepOwners(sim, handovers) {
@@ -145,13 +239,15 @@ export function sweepOwners(sim, handovers) {
145
239
  }
146
240
  }
147
241
 
148
- // Return `[objectId, playerId]` entries for a joiner's complete WORLD snapshot.
242
+ // Return one row per object for a joiner's complete WORLD snapshot. A row is
243
+ // the handover that would describe the object now, `[objectId, playerId|0,
244
+ // vx, vy, vz, wx, wy, wz, epoch]`, followed by 1 when the body is asleep and
245
+ // 0 when it is not.
149
246
  export function ownerships(sim) {
150
247
  const out = [];
151
248
  for (const [id, entry] of sim.objects) {
152
- if (entry.owner) {
153
- out.push([id, entry.owner]);
154
- }
249
+ const asleep = entry.body.isSleeping() ? 1 : 0;
250
+ out.push([id, entry.owner ?? 0, ...velocityOf(entry), entry.epoch ?? 0, asleep]);
155
251
  }
156
252
  return out;
157
253
  }