castle-web-cli 0.4.230 → 0.4.232
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.
- package/dist/castle-host/host.js +81 -0
- package/dist/devSaveStorage.d.ts +36 -0
- package/dist/devSaveStorage.js +469 -0
- package/dist/devSessionChild.js +22 -12
- package/dist/devSessionServer.js +8 -2
- package/dist/devSessionStorage.d.ts +9 -0
- package/dist/devSessionStorage.js +66 -1
- package/dist/init.js +1 -1
- package/dist/serve.js +5 -1
- package/dist/serverBundle.js +5 -3
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +148 -1
- package/kits/base/sdk/castle.d.ts +4 -0
- package/kits/base/sdk/castle.js +2 -0
- package/kits/base/sdk/commands.d.ts +15 -0
- package/kits/base/sdk/multiplayer.js +52 -4
- package/kits/base/sdk/save.d.ts +197 -0
- package/kits/base/sdk/save.js +525 -0
- package/kits/base/sdk/saveCoordinator.d.ts +39 -0
- package/kits/base/sdk/saveCoordinator.js +252 -0
- package/kits/base/sdk/server/storage.d.ts +3 -2
- package/kits/base/sdk/server/storage.js +25 -5
- package/kits/base/sdk/server/wrapper.d.ts +4 -0
- package/kits/base/sdk/server/wrapper.js +2 -0
- package/kits/base/sdk/store.d.ts +3 -2
- package/kits/base/sdk/store.js +5 -0
- package/kits/hub-game/CLAUDE.md +29 -4
- package/kits/hub-game/code/client/avatar.js +39 -0
- package/kits/hub-game/code/client/chat.js +12 -0
- package/kits/hub-game/code/client/chrome.js +237 -13
- package/kits/hub-game/code/client/grab.js +166 -7
- package/kits/hub-game/code/client/hats.js +26 -0
- package/kits/hub-game/code/client/hookLayer.js +36 -3
- package/kits/hub-game/code/client/hudClear.js +126 -0
- package/kits/hub-game/code/client/state.js +35 -1
- package/kits/hub-game/code/client/talk.js +10 -36
- package/kits/hub-game/code/client/tiers.js +505 -0
- package/kits/hub-game/code/client/together.js +144 -4
- package/kits/hub-game/code/client/wear.js +96 -14
- package/kits/hub-game/code/server/actors.js +5 -0
- package/kits/hub-game/code/server/grab.js +299 -13
- package/kits/hub-game/code/server/hub.js +162 -7
- package/kits/hub-game/code/server/manifest.js +80 -8
- package/kits/hub-game/code/server/npcs.js +21 -33
- package/kits/hub-game/code/server/party.js +75 -6
- package/kits/hub-game/code/server/say.js +8 -2
- package/kits/hub-game/code/server/wear.js +116 -11
- package/kits/hub-game/code/systems/hub.js +386 -21
- package/kits/hub-game/docs/contract.md +285 -19
- package/kits/hub-game/package.json +1 -1
- package/kits/hub-game/scripts/test-chat.mjs +32 -0
- package/kits/hub-game/scripts/test-grab-client.mjs +511 -0
- package/kits/hub-game/scripts/test-grab.mjs +857 -3
- package/kits/hub-game/scripts/test-hats.mjs +229 -0
- package/kits/hub-game/scripts/test-hub-trip.mjs +721 -0
- package/kits/hub-game/scripts/test-hud-clear.mjs +676 -0
- package/kits/hub-game/scripts/test-manifest.mjs +122 -1
- package/kits/hub-game/scripts/test-npcs.mjs +34 -24
- package/kits/hub-game/scripts/test-party.mjs +108 -4
- package/kits/hub-game/scripts/test-say.mjs +59 -2
- package/kits/hub-game/scripts/test-tiers.mjs +854 -0
- package/kits/hub-game/scripts/test-together.mjs +33 -1
- package/kits/hub-game/scripts/test-try-on.mjs +940 -0
- package/kits/physics-2d/CLAUDE.md +2 -0
- package/kits/physics-2d/castle.json +2 -2
- package/kits/physics-2d/engine/scene.js +127 -0
- package/kits/physics-2d/package.json +1 -1
- package/kits/physics-2d/scripts/test-skip-unchanged.mjs +298 -0
- package/kits/physics-3d/CLAUDE.md +531 -0
- package/kits/physics-3d/behaviors/Player.jsx +437 -3
- package/kits/physics-3d/castle.json +3 -3
- package/kits/physics-3d/docs/pxmodel-format.md +4 -0
- package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -1
- package/kits/physics-3d/engine3d/actornode.js +253 -0
- package/kits/physics-3d/engine3d/nearshadows.js +600 -0
- package/kits/physics-3d/engine3d/optimize.js +49 -0
- package/kits/physics-3d/engine3d/orbitinput.js +277 -0
- package/kits/physics-3d/engine3d/unchanged.js +153 -0
- package/kits/physics-3d/engine3d/world3d.js +525 -11
- package/kits/physics-3d/package.json +1 -1
- package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
- package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
- package/kits/physics-3d/scripts/test-camera-follow.mjs +543 -0
- package/kits/physics-3d/scripts/test-camera-orbit.mjs +2105 -0
- package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
- package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
- package/kits/physics-3d/scripts/test-static-actors.mjs +667 -0
- package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
- package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
- package/kits/physics-3d/scripts/test-steady-hover.mjs +633 -0
- package/kits/physics-3d/systems/physics3d.js +273 -9
- package/package.json +1 -1
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
// The walkable player: a dynamic locked-rotation capsule driven by impulses
|
|
2
|
+
// (the vase floating-capsule controller), a faux-isometric follow camera, and
|
|
3
|
+
// the "look at things" reading of nearby Lookables into the hud.
|
|
4
|
+
//
|
|
5
|
+
// Controls: WASD / arrows move (camera-relative), Q / E orbit the camera.
|
|
6
|
+
// State lives on `actor.runtime` -- behavior instances are per-frame.
|
|
7
|
+
|
|
8
|
+
const DEG = Math.PI / 180;
|
|
9
|
+
|
|
10
|
+
function keyDown(keys, ...codes) {
|
|
11
|
+
return codes.some((code) => keys.has(code));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Tank-style drive input: `forward` (-1..1) walks along the facing direction,
|
|
15
|
+
// `turn` (-1..1) steers it. W/S (and up/down arrows) drive, A/D (and
|
|
16
|
+
// left/right) turn. The pointer-drag stick maps the same way -- drag up walks,
|
|
17
|
+
// drag sideways turns, and the drag ANGLE blends the two, so a diagonal drag
|
|
18
|
+
// walks a curve and a pure sideways drag turns in place.
|
|
19
|
+
// Keys turn a bit harder than a full stick deflection -- discrete input wants
|
|
20
|
+
// the snappier response.
|
|
21
|
+
const KEY_TURN = 1.35;
|
|
22
|
+
|
|
23
|
+
function readDrive(keys, stick) {
|
|
24
|
+
let forward = 0;
|
|
25
|
+
let turn = 0;
|
|
26
|
+
if (keyDown(keys, 'KeyW', 'ArrowUp')) forward += 1;
|
|
27
|
+
if (keyDown(keys, 'KeyS', 'ArrowDown')) forward -= 1;
|
|
28
|
+
if (keyDown(keys, 'KeyD', 'ArrowRight')) turn += KEY_TURN;
|
|
29
|
+
if (keyDown(keys, 'KeyA', 'ArrowLeft')) turn -= KEY_TURN;
|
|
30
|
+
if (forward === 0 && turn === 0 && stick?.active && Math.hypot(stick.x, stick.y) >= 0.15) {
|
|
31
|
+
forward = -stick.y;
|
|
32
|
+
turn = stick.x;
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
forward: Math.max(-1, Math.min(1, forward)),
|
|
36
|
+
turn: Math.max(-KEY_TURN, Math.min(KEY_TURN, turn)),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Spring-hover the capsule a touch above the ground (smooths steps and edges);
|
|
41
|
+
// returns whether the player counts as grounded. The spring stays out of the
|
|
42
|
+
// way while the player is on the way up from a jump.
|
|
43
|
+
function applyHover(phys, actor, t, dims, dt) {
|
|
44
|
+
const hit = phys.castRay({ x: t.x, y: t.y, z: t.z }, { x: 0, y: -1, z: 0 }, dims.height, actor);
|
|
45
|
+
const hoverHeight = dims.height / 2 + 0.15;
|
|
46
|
+
const grounded = Boolean(hit && hit.distance < hoverHeight + 0.25);
|
|
47
|
+
const vel = phys.getVelocity(actor);
|
|
48
|
+
if (hit && hit.distance < hoverHeight + 0.4 && vel.y <= 1) {
|
|
49
|
+
const accel = 160 * (hoverHeight - hit.distance) - 18 * vel.y;
|
|
50
|
+
phys.applyImpulse(actor, { x: 0, y: accel * phys.mass(actor) * dt, z: 0 });
|
|
51
|
+
}
|
|
52
|
+
return grounded;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The hover of a scene that set `"engine": { "camera": { "follow": "rigid" } }`
|
|
56
|
+
// (the kit's CLAUDE.md has the terms): the same spring, asked for as a force.
|
|
57
|
+
// `applyHover` pushes once per drawn frame while gravity pulls once per fixed
|
|
58
|
+
// physics step, and a frame takes none, one or two steps, so on a frame that
|
|
59
|
+
// is not exactly one step the player is kicked up or let drop: a bob of a
|
|
60
|
+
// centimetre or two walking, which the rigid camera would show as the view
|
|
61
|
+
// bobbing. A force acts once per step, as gravity does, so the spring and
|
|
62
|
+
// gravity balance on every step whatever the frames are.
|
|
63
|
+
//
|
|
64
|
+
// The spring rests STEADY_REST higher than applyHover's so the player stands
|
|
65
|
+
// where it does without the key. applyHover's push lands at the start of a
|
|
66
|
+
// step and gravity is spread through it, so the velocity it reads standing
|
|
67
|
+
// still is not 0 but a fraction of a step's fall (-0.123 m/s for the kit's
|
|
68
|
+
// player, whose gravity scale is 2), and the spring's damper answers that
|
|
69
|
+
// with lift: 18 * 0.123 / 160 = 1.38 cm. Under a force the velocity at rest
|
|
70
|
+
// is 0. (0.69 cm per unit of gravity scale: a player with another scale
|
|
71
|
+
// stands that much off its keyless height.) What counts as grounded is
|
|
72
|
+
// measured as it is there.
|
|
73
|
+
//
|
|
74
|
+
// The force is the physics system's to drop: `addForce` lasts this frame's
|
|
75
|
+
// physics pass and no longer, so a frame this does not run on has no lift.
|
|
76
|
+
const STEADY_REST = 0.0138;
|
|
77
|
+
|
|
78
|
+
function hoverSteadily(phys, actor, t, dims) {
|
|
79
|
+
const hit = phys.castRay({ x: t.x, y: t.y, z: t.z }, { x: 0, y: -1, z: 0 }, dims.height, actor);
|
|
80
|
+
const hoverHeight = dims.height / 2 + 0.15;
|
|
81
|
+
const vel = phys.getVelocity(actor);
|
|
82
|
+
if (hit && hit.distance < hoverHeight + 0.4 && vel.y <= 1) {
|
|
83
|
+
const accel = 160 * (hoverHeight + STEADY_REST - hit.distance) - 18 * vel.y;
|
|
84
|
+
phys.addForce(actor, { x: 0, y: accel * phys.mass(actor), z: 0 });
|
|
85
|
+
}
|
|
86
|
+
return Boolean(hit && hit.distance < hoverHeight + 0.25);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The fall-faster pull under the same key: a force for the same reason.
|
|
90
|
+
function pullSteadily(phys, actor) {
|
|
91
|
+
phys.addForce(actor, { x: 0, y: -14 * phys.mass(actor), z: 0 });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function applyMove(phys, actor, move, speed, grounded, dt) {
|
|
95
|
+
const mass = phys.mass(actor);
|
|
96
|
+
const vel = phys.getVelocity(actor);
|
|
97
|
+
if (move) {
|
|
98
|
+
const factor = Math.min(1, dt * 14) * (grounded ? 1 : 0.3);
|
|
99
|
+
phys.applyImpulse(actor, {
|
|
100
|
+
x: (move.x * speed - vel.x) * mass * factor,
|
|
101
|
+
y: 0,
|
|
102
|
+
z: (move.z * speed - vel.z) * mass * factor,
|
|
103
|
+
});
|
|
104
|
+
} else if (grounded) {
|
|
105
|
+
const factor = Math.min(1, dt * 12);
|
|
106
|
+
phys.applyImpulse(actor, { x: -vel.x * mass * factor, y: 0, z: -vel.z * mass * factor });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// A player moving faster than this between two frames was teleported: a scene
|
|
111
|
+
// switch, or the session placing them where they left off. Walking never covers
|
|
112
|
+
// it in one frame.
|
|
113
|
+
const TELEPORT_PER_FRAME = 3;
|
|
114
|
+
|
|
115
|
+
function updateCamera(scene, t, rt, props, dt) {
|
|
116
|
+
const cam = scene.three?.camera;
|
|
117
|
+
if (!cam) return;
|
|
118
|
+
const targetX = t.x - props.camDistance * Math.sin(rt.camAngle);
|
|
119
|
+
const targetY = t.y + props.camHeight;
|
|
120
|
+
const targetZ = t.z + props.camDistance * Math.cos(rt.camAngle);
|
|
121
|
+
|
|
122
|
+
// A teleport snaps the camera instead of swooshing it across the map. The
|
|
123
|
+
// player's position from the previous frame is what detects it.
|
|
124
|
+
const last = rt.camLastAt;
|
|
125
|
+
const jumped = last && Math.hypot(t.x - last.x, t.z - last.z) > TELEPORT_PER_FRAME;
|
|
126
|
+
rt.camLastAt = { x: t.x, z: t.z };
|
|
127
|
+
if (jumped || Math.hypot(targetX - cam.position.x, targetZ - cam.position.z) > 20) {
|
|
128
|
+
cam.position.set(targetX, targetY, targetZ);
|
|
129
|
+
} else {
|
|
130
|
+
const lerp = 1 - Math.exp(-12 * dt);
|
|
131
|
+
cam.position.x += (targetX - cam.position.x) * lerp;
|
|
132
|
+
cam.position.y += (targetY - cam.position.y) * lerp;
|
|
133
|
+
cam.position.z += (targetZ - cam.position.z) * lerp;
|
|
134
|
+
}
|
|
135
|
+
cam.lookAt(t.x, t.y + 0.5, t.z);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// How fast the rigid follow camera's offset and height catch up: the rate of
|
|
139
|
+
// updateCamera's lerp, so an orbit (Q/E, or turning) swings as it does there.
|
|
140
|
+
const FOLLOW_RATE = 12;
|
|
141
|
+
|
|
142
|
+
// One frame of `x' = FOLLOW_RATE * (target - x)` for a target that moved from
|
|
143
|
+
// `from` to `to` at a steady rate over the frame, solved exactly. A target that
|
|
144
|
+
// moves steadily is trailed by the same distance however the frames are cut,
|
|
145
|
+
// and one that stands still is reached as updateCamera's lerp reaches it.
|
|
146
|
+
function settle(value, from, to, dt) {
|
|
147
|
+
if (!(dt > 0)) return value;
|
|
148
|
+
const lag = (to - from) / (dt * FOLLOW_RATE);
|
|
149
|
+
return to - lag + (value - from + lag) * Math.exp(-FOLLOW_RATE * dt);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// The follow camera of a scene that set `"engine": { "camera": { "follow":
|
|
153
|
+
// "rigid" } }` (the kit's CLAUDE.md has the terms). It moves with the player
|
|
154
|
+
// as one piece: the offset from the player (its angle and height) and the
|
|
155
|
+
// player's height are eased, the player's ground position is not, so a steady
|
|
156
|
+
// walk leaves the player at one place on screen whatever the frame lengths.
|
|
157
|
+
// It is placed at the end of the frame (`placeFollowing`), on the position the
|
|
158
|
+
// frame is drawn with.
|
|
159
|
+
function followRigidly(scene, t, per, rt, props, dt) {
|
|
160
|
+
const cam = scene.three?.camera;
|
|
161
|
+
if (!cam) return;
|
|
162
|
+
const ox = -props.camDistance * Math.sin(per.camAngle);
|
|
163
|
+
const oy = props.camHeight;
|
|
164
|
+
const oz = props.camDistance * Math.cos(per.camAngle);
|
|
165
|
+
const last = per.camLastAt;
|
|
166
|
+
const jumped = last && Math.hypot(t.x - last.x, t.z - last.z) > TELEPORT_PER_FRAME;
|
|
167
|
+
per.camLastAt = { x: t.x, z: t.z };
|
|
168
|
+
// The offset is read each frame from where the camera is, against the
|
|
169
|
+
// point it followed last frame, so a camera something else moved since (a
|
|
170
|
+
// trip's camera, a cutscene) is eased on from where it was left.
|
|
171
|
+
const at = cam.position;
|
|
172
|
+
const f = (rt.camFollow ??= { from: { x: t.x, y: t.y, z: t.z }, to: null });
|
|
173
|
+
let x = at.x - f.from.x;
|
|
174
|
+
let y = at.y - f.from.y;
|
|
175
|
+
let z = at.z - f.from.z;
|
|
176
|
+
let height = f.from.y;
|
|
177
|
+
const to = f.to ?? { x: ox, y: oy, z: oz, height: t.y };
|
|
178
|
+
if (jumped || Math.hypot(t.x + ox - at.x, t.z + oz - at.z) > 20) {
|
|
179
|
+
[x, y, z, height] = [ox, oy, oz, t.y];
|
|
180
|
+
} else {
|
|
181
|
+
x = settle(x, to.x, ox, dt);
|
|
182
|
+
y = settle(y, to.y, oy, dt);
|
|
183
|
+
z = settle(z, to.z, oz, dt);
|
|
184
|
+
height = settle(height, to.height, t.y, dt);
|
|
185
|
+
}
|
|
186
|
+
f.to = { x: ox, y: oy, z: oz, height: t.y };
|
|
187
|
+
f.from = { x: t.x, y: height, z: t.z };
|
|
188
|
+
cam.position.set(t.x + x, height + y, t.z + z);
|
|
189
|
+
cam.lookAt(t.x, t.y + 0.5, t.z);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Under the key, Player.update asks for its camera by the actor's id and the
|
|
193
|
+
// scene data it was made for (`scene.followCamera`), every frame, physics
|
|
194
|
+
// ready or not; the physics system calls this at the end of the frame, after
|
|
195
|
+
// it has written this frame's positions back (or at once, when it could not
|
|
196
|
+
// step), if the same scene is still loaded. The player is looked up as the
|
|
197
|
+
// scene has it then: one despawned or turned off since gets no camera.
|
|
198
|
+
function placeFollowing(scene, id, dt) {
|
|
199
|
+
const actor = scene.getActor(id);
|
|
200
|
+
const t = actor?.components.Transform;
|
|
201
|
+
const props = actor?.components.Player;
|
|
202
|
+
if (!t || !props || props.$enabled === false) return;
|
|
203
|
+
const per = (scene.persistent ??= {});
|
|
204
|
+
if (per.camAngle === undefined) per.camAngle = Math.PI / 4;
|
|
205
|
+
followRigidly(scene, t, per, actor.runtime, props, dt);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// The nearest Lookable the player is facing, within its range.
|
|
209
|
+
function findLookText(scene, actor, t, facing) {
|
|
210
|
+
const fx = Math.sin(facing);
|
|
211
|
+
const fz = Math.cos(facing);
|
|
212
|
+
let bestText = '';
|
|
213
|
+
let bestDist = Infinity;
|
|
214
|
+
for (const other of scene.actorsWith('Lookable')) {
|
|
215
|
+
if (other.id === actor.id) continue;
|
|
216
|
+
const ot = other.components.Transform;
|
|
217
|
+
if (!ot) continue;
|
|
218
|
+
const dx = ot.x - t.x;
|
|
219
|
+
const dz = ot.z - t.z;
|
|
220
|
+
const dist = Math.hypot(dx, dz);
|
|
221
|
+
const range = other.components.Lookable.range ?? 4;
|
|
222
|
+
if (dist < 0.01 || dist > range || dist >= bestDist) continue;
|
|
223
|
+
if ((dx * fx + dz * fz) / dist < 0.7) continue;
|
|
224
|
+
bestText = other.components.Lookable.text ?? '';
|
|
225
|
+
bestDist = dist;
|
|
226
|
+
}
|
|
227
|
+
return bestText;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export class Player {
|
|
231
|
+
static behaviorName = 'Player';
|
|
232
|
+
static defaultProps = { speed: 6, turnSpeed: 2.4, jumpSpeed: 8, camDistance: 9, camHeight: 7 };
|
|
233
|
+
static propertyMeta = {
|
|
234
|
+
speed: { min: 0, step: 0.5 },
|
|
235
|
+
turnSpeed: { min: 0, step: 0.1 },
|
|
236
|
+
jumpSpeed: { min: 0, step: 0.5 },
|
|
237
|
+
camDistance: { min: 0, step: 0.5 },
|
|
238
|
+
camHeight: { min: 0, step: 0.5 },
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
constructor(props) {
|
|
242
|
+
this.props = props;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
update(actor, scene, dt) {
|
|
246
|
+
if (scene.cameraFollowsRigidly === true) {
|
|
247
|
+
scene.followCamera = { id: actor.id, data: scene.data, dt, place: placeFollowing };
|
|
248
|
+
}
|
|
249
|
+
const phys = scene.physics3d;
|
|
250
|
+
if (!phys?.ready()) return;
|
|
251
|
+
const t = actor.components.Transform;
|
|
252
|
+
// Cross-scene state (camera angle, score) lives on the runtime's
|
|
253
|
+
// persistent store so it survives `loadFromFile`; actor.runtime is
|
|
254
|
+
// rebuilt on every scene load.
|
|
255
|
+
const per = (scene.persistent ??= {});
|
|
256
|
+
const rt = actor.runtime;
|
|
257
|
+
if (per.camAngle === undefined) per.camAngle = Math.PI / 4;
|
|
258
|
+
if (per.score === undefined) per.score = 0;
|
|
259
|
+
|
|
260
|
+
const shape = actor.components.Shape;
|
|
261
|
+
const dims = { radius: shape?.radius ?? 0.35, height: shape?.height ?? 1.4 };
|
|
262
|
+
// Under the camera key the player is held steady on screen: the hover
|
|
263
|
+
// and the fall-faster pull are forces (hoverSteadily). Without it every
|
|
264
|
+
// call below is the one made before the key had this meaning.
|
|
265
|
+
const steady = scene.cameraFollowsRigidly === true;
|
|
266
|
+
const grounded = steady ? hoverSteadily(phys, actor, t, dims) : applyHover(phys, actor, t, dims, dt);
|
|
267
|
+
const drive = readDrive(scene.keys, scene.moveInput);
|
|
268
|
+
per.camAngle += drive.turn * this.props.turnSpeed * dt;
|
|
269
|
+
rt.facing = Math.PI - per.camAngle;
|
|
270
|
+
const move =
|
|
271
|
+
drive.forward !== 0
|
|
272
|
+
? {
|
|
273
|
+
x: Math.sin(per.camAngle) * drive.forward,
|
|
274
|
+
z: -Math.cos(per.camAngle) * drive.forward,
|
|
275
|
+
}
|
|
276
|
+
: null;
|
|
277
|
+
applyMove(phys, actor, move, this.props.speed, grounded, dt);
|
|
278
|
+
t.rotationY = rt.facing / DEG;
|
|
279
|
+
|
|
280
|
+
// Jump: Space on keyboard, or a short tap anywhere on the canvas (which
|
|
281
|
+
// works while another finger drives the drag stick). A tap is buffered
|
|
282
|
+
// briefly so one made just before touchdown still fires.
|
|
283
|
+
if (scene.moveInput?.consumeJump?.()) rt.jumpBuffer = 0.18;
|
|
284
|
+
else rt.jumpBuffer = Math.max(0, (rt.jumpBuffer ?? 0) - dt);
|
|
285
|
+
if ((keyDown(scene.keys, 'Space') || rt.jumpBuffer > 0) && grounded) {
|
|
286
|
+
rt.jumpBuffer = 0;
|
|
287
|
+
const vel = phys.getVelocity(actor);
|
|
288
|
+
phys.setVelocity(actor, { x: vel.x, y: this.props.jumpSpeed, z: vel.z });
|
|
289
|
+
// The jump replaces the velocity the hover was holding; this frame's
|
|
290
|
+
// lift goes too, or it would be added to the jump.
|
|
291
|
+
if (steady) phys.resetForces(actor);
|
|
292
|
+
}
|
|
293
|
+
// Fall faster than the rise: extra downward pull past the jump apex kills
|
|
294
|
+
// the floaty arc.
|
|
295
|
+
if (!grounded) {
|
|
296
|
+
const vel = phys.getVelocity(actor);
|
|
297
|
+
if (vel.y < 1) {
|
|
298
|
+
if (steady) pullSteadily(phys, actor);
|
|
299
|
+
else phys.applyImpulse(actor, { x: 0, y: -14 * phys.mass(actor) * dt, z: 0 });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (scene.cameraFollowsRigidly !== true) updateCamera(scene, t, per, this.props, dt);
|
|
304
|
+
const remaining = scene.actorsWith('Pickup').length;
|
|
305
|
+
const total = per.score + remaining;
|
|
306
|
+
const score =
|
|
307
|
+
total === 0 ? '' : remaining === 0 ? '◆ all shards found' : `◆ ${per.score}/${total}`;
|
|
308
|
+
scene.hud = { score, look: findLookText(scene, actor, t, rt.facing) };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// 3d scene player: mounts a SceneRuntime (from the imported physics-2d kit's
|
|
2
|
+
// engine -- the actor/behavior model is shared) against a three.js world.
|
|
3
|
+
// Behaviors update, the physics3d system steps rapier, then Transforms sync to
|
|
4
|
+
// three nodes and the composer renders. No game logic here.
|
|
5
|
+
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
|
6
|
+
import { makeScene } from '@imports/castle.physics-2d/engine/scene';
|
|
7
|
+
import {
|
|
8
|
+
makeWorld3D,
|
|
9
|
+
resizeWorld,
|
|
10
|
+
syncActors,
|
|
11
|
+
renderWorld,
|
|
12
|
+
disposeWorld,
|
|
13
|
+
updatePhysicsDebug,
|
|
14
|
+
} from './world3d';
|
|
15
|
+
|
|
16
|
+
export function Scene3DPlayer({
|
|
17
|
+
sceneData,
|
|
18
|
+
sprites,
|
|
19
|
+
files,
|
|
20
|
+
behaviorClasses,
|
|
21
|
+
scenePath,
|
|
22
|
+
onFirstFrame,
|
|
23
|
+
}) {
|
|
24
|
+
const canvasRef = useRef(null);
|
|
25
|
+
const scoreRef = useRef(null);
|
|
26
|
+
const lookRef = useRef(null);
|
|
27
|
+
const [error, setError] = useState(null);
|
|
28
|
+
const [runId, setRunId] = useState(0);
|
|
29
|
+
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
const canvas = canvasRef.current;
|
|
32
|
+
if (!canvas) return undefined;
|
|
33
|
+
const runtime = makeScene(sceneData, behaviorClasses, sprites, files, scenePath);
|
|
34
|
+
const world = makeWorld3D(canvas);
|
|
35
|
+
runtime.three = world;
|
|
36
|
+
runtime.hud = {};
|
|
37
|
+
// Scene-independent state: survives `loadFromFile` (the scene data is
|
|
38
|
+
// replaced, the runtime instance is not). Player score/inventory and the
|
|
39
|
+
// camera angle live here so they cross scene switches.
|
|
40
|
+
runtime.persistent = {};
|
|
41
|
+
runtime.currentScenePath = scenePath ?? 'scenes/main.scene';
|
|
42
|
+
// This loop applies `requestedContent` with `requestedScene` (another
|
|
43
|
+
// deck's content, mounted as data); a caller checks before asking.
|
|
44
|
+
runtime.mountsContent = true;
|
|
45
|
+
|
|
46
|
+
const detachInput = attachInput(canvas, runtime, world);
|
|
47
|
+
const stopResize = attachResize(canvas, world);
|
|
48
|
+
const onLoopError = (err) => {
|
|
49
|
+
console.error(err);
|
|
50
|
+
setError(err);
|
|
51
|
+
};
|
|
52
|
+
const hudRefs = { score: scoreRef, look: lookRef };
|
|
53
|
+
const stopLoop = startLoop(runtime, world, sprites, hudRefs, onFirstFrame, onLoopError);
|
|
54
|
+
return () => {
|
|
55
|
+
stopLoop();
|
|
56
|
+
stopResize();
|
|
57
|
+
detachInput();
|
|
58
|
+
runtime.dispose();
|
|
59
|
+
disposeWorld(world);
|
|
60
|
+
};
|
|
61
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
62
|
+
}, [runId]);
|
|
63
|
+
|
|
64
|
+
const onRestart = useCallback(() => {
|
|
65
|
+
setError(null);
|
|
66
|
+
setRunId((n) => n + 1);
|
|
67
|
+
}, []);
|
|
68
|
+
|
|
69
|
+
return (
|
|
70
|
+
<div style={{ position: 'fixed', inset: 0, background: '#000' }}>
|
|
71
|
+
<canvas
|
|
72
|
+
ref={canvasRef}
|
|
73
|
+
tabIndex={0}
|
|
74
|
+
style={{
|
|
75
|
+
width: '100%',
|
|
76
|
+
height: '100%',
|
|
77
|
+
display: 'block',
|
|
78
|
+
outline: 'none',
|
|
79
|
+
touchAction: 'none',
|
|
80
|
+
userSelect: 'none',
|
|
81
|
+
WebkitUserSelect: 'none',
|
|
82
|
+
WebkitTouchCallout: 'none',
|
|
83
|
+
}}
|
|
84
|
+
/>
|
|
85
|
+
<div ref={scoreRef} style={hudStyles.score} />
|
|
86
|
+
<div ref={lookRef} style={hudStyles.look} />
|
|
87
|
+
{error ? <LoopErrorOverlay error={error} onRestart={onRestart} /> : null}
|
|
88
|
+
</div>
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function attachInput(canvas, runtime, world) {
|
|
93
|
+
const onKeyDown = (event) => {
|
|
94
|
+
// Space is gameplay (jump); keep it from scrolling the page.
|
|
95
|
+
if (event.code === 'Space' && event.target === canvas) event.preventDefault();
|
|
96
|
+
if (event.code === 'KeyP' && !event.repeat) {
|
|
97
|
+
world.debugLines.visible = !world.debugLines.visible;
|
|
98
|
+
}
|
|
99
|
+
runtime.keys.add(event.code);
|
|
100
|
+
runtime.keys.add(event.key);
|
|
101
|
+
};
|
|
102
|
+
const onKeyUp = (event) => {
|
|
103
|
+
runtime.keys.delete(event.code);
|
|
104
|
+
runtime.keys.delete(event.key);
|
|
105
|
+
};
|
|
106
|
+
// Pointer (mouse or touch) input is multitouch, tracked per pointerId:
|
|
107
|
+
// - a DRAG is the virtual stick -- the offset from where the drag started
|
|
108
|
+
// maps to a walk direction (drag up = forward). The first pointer to
|
|
109
|
+
// travel past the tap slop owns the stick until it lifts.
|
|
110
|
+
// - a TAP (down and up quickly without moving much) is a jump, even while
|
|
111
|
+
// another finger is dragging. `moveInput.consumeJump()` hands the
|
|
112
|
+
// pending tap to the Player behavior exactly once.
|
|
113
|
+
// `runtime.moveInput` is what the Player behavior reads.
|
|
114
|
+
const STICK_RADIUS_PX = 56;
|
|
115
|
+
const TAP_SLOP_PX = 12;
|
|
116
|
+
const TAP_MS = 300;
|
|
117
|
+
const pointers = new Map();
|
|
118
|
+
let stickId = null;
|
|
119
|
+
let jumpPending = false;
|
|
120
|
+
const move = {
|
|
121
|
+
x: 0,
|
|
122
|
+
y: 0,
|
|
123
|
+
active: false,
|
|
124
|
+
consumeJump() {
|
|
125
|
+
const had = jumpPending;
|
|
126
|
+
jumpPending = false;
|
|
127
|
+
return had;
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
runtime.moveInput = move;
|
|
131
|
+
const clearStick = () => {
|
|
132
|
+
stickId = null;
|
|
133
|
+
move.active = false;
|
|
134
|
+
move.x = 0;
|
|
135
|
+
move.y = 0;
|
|
136
|
+
};
|
|
137
|
+
const onPointerDown = (event) => {
|
|
138
|
+
canvas.focus();
|
|
139
|
+
pointers.set(event.pointerId, {
|
|
140
|
+
x: event.clientX,
|
|
141
|
+
y: event.clientY,
|
|
142
|
+
time: performance.now(),
|
|
143
|
+
moved: false,
|
|
144
|
+
});
|
|
145
|
+
canvas.setPointerCapture(event.pointerId);
|
|
146
|
+
};
|
|
147
|
+
const onPointerMove = (event) => {
|
|
148
|
+
const p = pointers.get(event.pointerId);
|
|
149
|
+
if (!p) return;
|
|
150
|
+
const dx = event.clientX - p.x;
|
|
151
|
+
const dy = event.clientY - p.y;
|
|
152
|
+
if (!p.moved && Math.hypot(dx, dy) > TAP_SLOP_PX) p.moved = true;
|
|
153
|
+
// A pointer claims the stick once it is clearly a drag (and nothing else
|
|
154
|
+
// holds it) -- so a tapping finger never yanks the walk direction.
|
|
155
|
+
if (p.moved && stickId === null) stickId = event.pointerId;
|
|
156
|
+
if (stickId !== event.pointerId) return;
|
|
157
|
+
const nx = dx / STICK_RADIUS_PX;
|
|
158
|
+
const ny = dy / STICK_RADIUS_PX;
|
|
159
|
+
const len = Math.hypot(nx, ny);
|
|
160
|
+
const scale = len > 1 ? 1 / len : 1;
|
|
161
|
+
move.active = true;
|
|
162
|
+
move.x = nx * scale;
|
|
163
|
+
move.y = ny * scale;
|
|
164
|
+
};
|
|
165
|
+
const onPointerUp = (event) => {
|
|
166
|
+
const p = pointers.get(event.pointerId);
|
|
167
|
+
pointers.delete(event.pointerId);
|
|
168
|
+
if (stickId === event.pointerId) clearStick();
|
|
169
|
+
if (event.type === 'pointercancel' || !p) return;
|
|
170
|
+
if (!p.moved && performance.now() - p.time < TAP_MS) jumpPending = true;
|
|
171
|
+
};
|
|
172
|
+
window.addEventListener('keydown', onKeyDown);
|
|
173
|
+
window.addEventListener('keyup', onKeyUp);
|
|
174
|
+
canvas.addEventListener('pointerdown', onPointerDown);
|
|
175
|
+
canvas.addEventListener('pointermove', onPointerMove);
|
|
176
|
+
canvas.addEventListener('pointerup', onPointerUp);
|
|
177
|
+
canvas.addEventListener('pointercancel', onPointerUp);
|
|
178
|
+
if (document.hasFocus() || window.parent === window) canvas.focus();
|
|
179
|
+
return () => {
|
|
180
|
+
window.removeEventListener('keydown', onKeyDown);
|
|
181
|
+
window.removeEventListener('keyup', onKeyUp);
|
|
182
|
+
canvas.removeEventListener('pointerdown', onPointerDown);
|
|
183
|
+
canvas.removeEventListener('pointermove', onPointerMove);
|
|
184
|
+
canvas.removeEventListener('pointerup', onPointerUp);
|
|
185
|
+
canvas.removeEventListener('pointercancel', onPointerUp);
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function attachResize(canvas, world) {
|
|
190
|
+
const fit = () => resizeWorld(world, canvas.clientWidth, canvas.clientHeight);
|
|
191
|
+
const observer = new ResizeObserver(fit);
|
|
192
|
+
observer.observe(canvas);
|
|
193
|
+
fit();
|
|
194
|
+
return () => observer.disconnect();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function startLoop(runtime, world, sprites, hudRefs, onFirstFrame, onError) {
|
|
198
|
+
let raf = 0;
|
|
199
|
+
let previousTime = performance.now();
|
|
200
|
+
let firstFrameSignaled = false;
|
|
201
|
+
const tick = (now) => {
|
|
202
|
+
const dt = Math.min(0.033, (now - previousTime) / 1000);
|
|
203
|
+
previousTime = now;
|
|
204
|
+
try {
|
|
205
|
+
runtime.update(dt);
|
|
206
|
+
// A behavior may have requested a scene switch; apply it here, between
|
|
207
|
+
// frames, never mid physics dispatch. The load resets
|
|
208
|
+
// registered systems -- the rapier world frees and lazily rebuilds --
|
|
209
|
+
// while `runtime.persistent` carries the player's cross-scene state.
|
|
210
|
+
if (runtime.requestedScene) {
|
|
211
|
+
const next = loadRequestedScene(runtime);
|
|
212
|
+
runtime.currentScenePath = next;
|
|
213
|
+
runtime.persistent.sceneChangeGraceUntil = runtime.time + 1;
|
|
214
|
+
}
|
|
215
|
+
syncActors(world, runtime, runtime.sprites ?? sprites, dt);
|
|
216
|
+
if (world.debugLines.visible) updatePhysicsDebug(world, runtime.physics3d?.debugRender());
|
|
217
|
+
renderWorld(world, runtime);
|
|
218
|
+
updateHud(runtime, hudRefs);
|
|
219
|
+
} catch (err) {
|
|
220
|
+
onError?.(err);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (!firstFrameSignaled) {
|
|
224
|
+
firstFrameSignaled = true;
|
|
225
|
+
requestAnimationFrame(() => onFirstFrame?.());
|
|
226
|
+
}
|
|
227
|
+
raf = requestAnimationFrame(tick);
|
|
228
|
+
};
|
|
229
|
+
raf = requestAnimationFrame(tick);
|
|
230
|
+
return () => cancelAnimationFrame(raf);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Load the scene a behavior asked for, with the content it comes from when
|
|
234
|
+
// that is another deck's (a hub content pack; `null` puts this deck's own
|
|
235
|
+
// back). Content that fails to load puts the scene that was running back and
|
|
236
|
+
// leaves the error on `runtime.mountError` for the asker. Returns the path now
|
|
237
|
+
// loaded.
|
|
238
|
+
function loadRequestedScene(runtime) {
|
|
239
|
+
const next = runtime.requestedScene;
|
|
240
|
+
runtime.requestedScene = null;
|
|
241
|
+
if (runtime.requestedContent === undefined) {
|
|
242
|
+
runtime.loadFromFile(next);
|
|
243
|
+
return next;
|
|
244
|
+
}
|
|
245
|
+
const before = { content: runtime.content ?? null, path: runtime.currentScenePath };
|
|
246
|
+
runtime.setContent(runtime.requestedContent);
|
|
247
|
+
runtime.requestedContent = undefined;
|
|
248
|
+
try {
|
|
249
|
+
runtime.loadFromFile(next);
|
|
250
|
+
return next;
|
|
251
|
+
} catch (err) {
|
|
252
|
+
console.error('[engine] content failed to load; staying where we were', err);
|
|
253
|
+
runtime.setContent(before.content);
|
|
254
|
+
runtime.loadFromFile(before.path);
|
|
255
|
+
runtime.mountError = err;
|
|
256
|
+
return before.path;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Behaviors write `scene.hud = { score, look }`; the loop pushes it into the
|
|
261
|
+
// overlay divs imperatively (no react re-render at frame rate).
|
|
262
|
+
function updateHud(runtime, hudRefs) {
|
|
263
|
+
const hud = runtime.hud ?? {};
|
|
264
|
+
const scoreText = hud.score ? String(hud.score) : '';
|
|
265
|
+
const lookText = hud.look ?? '';
|
|
266
|
+
if (hudRefs.score.current && hudRefs.score.current.textContent !== scoreText) {
|
|
267
|
+
hudRefs.score.current.textContent = scoreText;
|
|
268
|
+
}
|
|
269
|
+
if (hudRefs.look.current && hudRefs.look.current.textContent !== lookText) {
|
|
270
|
+
hudRefs.look.current.textContent = lookText;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const hudStyles = {
|
|
275
|
+
score: {
|
|
276
|
+
position: 'absolute',
|
|
277
|
+
top: 14,
|
|
278
|
+
left: 16,
|
|
279
|
+
color: '#7bd9ed',
|
|
280
|
+
font: "16px/1.4 'SFMono-Regular', Consolas, monospace",
|
|
281
|
+
textShadow: '0 1px 2px rgba(0,0,0,0.8)',
|
|
282
|
+
pointerEvents: 'none',
|
|
283
|
+
},
|
|
284
|
+
look: {
|
|
285
|
+
position: 'absolute',
|
|
286
|
+
bottom: 22,
|
|
287
|
+
left: 0,
|
|
288
|
+
right: 0,
|
|
289
|
+
textAlign: 'center',
|
|
290
|
+
color: '#e6e6e2',
|
|
291
|
+
fontStyle: 'italic',
|
|
292
|
+
font: 'italic 15px/1.4 Georgia, serif',
|
|
293
|
+
textShadow: '0 1px 3px rgba(0,0,0,0.9)',
|
|
294
|
+
pointerEvents: 'none',
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
function LoopErrorOverlay({ error, onRestart }) {
|
|
299
|
+
return (
|
|
300
|
+
<div
|
|
301
|
+
style={{
|
|
302
|
+
position: 'absolute',
|
|
303
|
+
inset: 0,
|
|
304
|
+
zIndex: 2147483000,
|
|
305
|
+
padding: '20px 22px',
|
|
306
|
+
background: 'rgba(20, 8, 8, 0.94)',
|
|
307
|
+
color: '#ffd9dc',
|
|
308
|
+
font: "13px/1.5 'SFMono-Regular', Consolas, monospace",
|
|
309
|
+
overflow: 'auto',
|
|
310
|
+
}}>
|
|
311
|
+
<div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 12 }}>
|
|
312
|
+
<span style={{ fontSize: 15, fontWeight: 700, color: '#ff6b74' }}>Play error</span>
|
|
313
|
+
<button
|
|
314
|
+
type="button"
|
|
315
|
+
onClick={onRestart}
|
|
316
|
+
style={{
|
|
317
|
+
marginLeft: 'auto',
|
|
318
|
+
padding: '4px 12px',
|
|
319
|
+
border: '1px solid #a02828',
|
|
320
|
+
borderRadius: 4,
|
|
321
|
+
background: '#a02828',
|
|
322
|
+
color: '#fff',
|
|
323
|
+
font: 'inherit',
|
|
324
|
+
cursor: 'pointer',
|
|
325
|
+
}}>
|
|
326
|
+
Restart
|
|
327
|
+
</button>
|
|
328
|
+
</div>
|
|
329
|
+
<div style={{ color: '#fff', fontWeight: 600 }}>
|
|
330
|
+
{error?.name ?? 'Error'}: {error?.message ?? String(error)}
|
|
331
|
+
</div>
|
|
332
|
+
{typeof error?.stack === 'string' ? (
|
|
333
|
+
<pre style={{ whiteSpace: 'pre-wrap', color: '#e79aa0', fontSize: 12 }}>{error.stack}</pre>
|
|
334
|
+
) : null}
|
|
335
|
+
</div>
|
|
336
|
+
);
|
|
337
|
+
}
|