-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2392 lines (2262 loc) · 101 KB
/
Copy pathserver.js
File metadata and controls
2392 lines (2262 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// server.js — node server.js (Node 18+)
// Authoritative physics server. One cannon-es world is the single source of
// truth for every piece. Clients send intent (grab / move-target / release /
// flip / spawn); the server simulates and Colyseus syncs the resulting
// transforms to everyone via delta-compressed Schema state.
import express from 'express';
import helmet from 'helmet';
import { createServer } from 'http';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { performance } from 'node:perf_hooks';
import { Server, Room, ServerError, matchMaker } from '@colyseus/core';
import { WebSocketTransport } from '@colyseus/ws-transport';
import { Schema, MapSchema, defineTypes, Encoder } from '@colyseus/schema';
Encoder.BUFFER_SIZE = 128 * 1024; // default 16KB overflows a busy table's piece map; 128KB gives ample headroom
import * as CANNON from 'cannon-es';
import {
KINDS,
PROPS,
BOARDS,
TABLE,
deckHeight,
MEASURE,
DISPENSERS,
dispensedSpec,
itemMatchesDispenser,
stackVisible,
gridActive,
snapToCell,
TRAY,
trayCenter,
trayParts,
trayPlace,
inTray,
colorProps,
STARTERS,
cardGeom,
sanitizeGeom,
sanitizeMatGeom,
seatAngle,
SEAT_ANGLES,
LETTER_DIST,
MAHJONG,
DECK_MODELS,
} from './shared/pieces.js';
import * as db from './db.js'; // Postgres-backed saved-asset library (metadata; files stay on disk)
import { hashPassword, verifyPassword, makeToken, hashToken } from './auth.js';
import { runMigrations } from './migrate.js'; // startup schema migrator (owner-role DDL)
import { RANK, rankOf, canManageMember, canSetMemberRole } from './server/permissions.js';
import { httpErrorHandler } from './server/http/async-route.js';
import { createRequireUser, createRequireAdmin } from './server/http/auth-context.js';
import { createAuthRouter } from './server/http/routes/auth.js';
import { createRoomsRouter } from './server/http/routes/rooms.js';
import { createUploadRouter } from './server/http/routes/uploads.js';
import { createAdminRouter } from './server/http/routes/admin.js';
import { absorbedEntry, cardBackRef, cardFrontRef } from './server/deck-state.js';
import { registerCardHandlers } from './server/game/handlers/cards.js';
import { registerMovementHandlers } from './server/game/handlers/movement.js';
import { registerMemberHandlers } from './server/game/handlers/members.js';
import { registerLibraryHandlers } from './server/game/handlers/library.js';
import { registerPieceHandlers } from './server/game/handlers/pieces.js';
import {
registerRoomStateHandlers,
saveRoomStateNow,
scheduleRoomSave,
} from './server/game/handlers/room-state.js';
import { registerOverlayHandlers } from './server/game/handlers/overlays.js';
import { registerRoomFeatureHandlers } from './server/game/handlers/room-features.js';
import { readProps, writeProps } from './server/game/props-codec.js';
import { bootstrapAdminFromEnvironment } from './server/bootstrap-admin.js';
import {
boundedString,
cardPlacementPayload,
dispenserDragPayload,
oneField,
pieceIdPayload,
reorderHandPayload,
} from './server/message-validation.js';
import { createRateLimitStore, makeRateLimiter } from './server/rate-limit.js';
import { trustedProxyHops } from './server/redis-config.js';
import { safeMessage, safeRoomTask } from './server/game/safe-message.js';
import { buildCollider, buildWorld, COLLIDER_TYPES } from './server/physics.js';
import {
applyScene as applyPersistedScene,
serializeGame as serializePersistedGame,
serializeScene as serializePersistedScene,
} from './server/game/scene-persistence.js';
// --- Simulation tuning (all the physics "feel" constants in one place) -------
const SIM = {
gravity: -20, // world gravity (y)
friction: 0.35,
restitution: 0.2, // contact material
tableThick: 0.5, // table slab half-height
wall: { half: 4, thick: 0.5, over: 1 }, // walls: half-height (y 0..8), half-thickness, corner overlap
servo: { stiffness: 25, maxSpeed: 45, angDamp: 0.6 }, // held-piece velocity servo (tracks cursor)
damp: { flat: 0.5, solid: 0.15 }, // angular damping: cards/decks vs everything else
flipHop: 1.6,
flipArc: 0.7, // flip feedback nudge + kinematic arc height
roll: { up: 16, spread: 8, spin: 22 }, // die roll impulse (up drives peak height ~ up^2)
trayRoll: { up: 8, spread: 13, spin: 30 }, // tray-die roll: a real toss, kept in by the walls + lid
impact: { minVel: 1.5 }, // min collision speed (m/s) to fire a landing sound
spawnY: 4, // height a spawned piece drops from
bounds: { margin: 1.5, floor: -3, ceiling: 12 }, // out-of-bounds safety net
absorb: { x: 1.1, z: 1.4 }, // how close a dropped card must be to a deck to merge
propRight: { strength: 9, maxTilt: 0.85, damp: 0.82 }, // self-righting for standing props (pawn/chess)
throwCap: 40, // general release-speed clamp
// --- global solver / contacts / timestep (stack stability vs CPU) ---
solverIterations: 12, // contact solver passes: more = firmer stacks, more CPU
contact: { stiffness: 1e7, relaxation: 3 }, // contact-equation firmness / relaxation
step: { fixed: 1 / 120, maxSub: 4 }, // physics timestep: smaller fixed + more substeps = less tunneling, more CPU
// --- CARDS: the thin-stack problem is tuned here ---------------------------
cards: {
colliderThick: 0.04, // HALF-thickness of the INVISIBLE card collider (the mesh stays thin). Bigger = far more
// stable stacks & less clip-through, but stacked cards show a small air-gap. Try 0.03–0.08.
linDamp: 0.25, // linear damping — cards settle sooner
angDamp: 0.7, // angular damping for cards (overrides damp.flat)
maxThrow: 14, // clamp a card's release speed so a flung card can't tunnel through another
sleepSpeed: 0.5, // a card goes fully static (stops jittering) below this speed...
sleepTime: 0.2, // ...sustained for this many seconds
},
maxPieces: 250,
};
// Dev profiling toggle: PERF_LOG=1 logs a per-second physics/tick summary (docs/ROADMAP.md §1).
const PERF_LOG = process.env.PERF_LOG === '1';
// --- Saved-asset library -----------------------------------------------------
// A shared, on-disk library of decks / boards / props that survives restarts
// (mount ASSETS_DIR as a Docker volume to persist it). Layout:
//
// <ASSETS_DIR>/{uploads,decks,boards,props}/
// <random>.<ext> uploaded images / models, served at /assets/<kind>/<random>
// <slug>.json metadata, NEVER web-served (a route guard blocks .json)
//
// Because filenames are random and the .json metadata is never served, a card
// front that's meant to stay hidden can't be discovered by poking at /assets.
const ASSETS_DIR = process.env.ASSETS_DIR || './saved-assets';
const ASSET_KINDS = ['uploads', 'decks', 'boards', 'props', 'sky', 'dice', 'mats'];
const LIBRARY_KINDS = ['deck', 'board', 'prop', 'scene', 'sky', 'dice', 'mat'];
for (const kind of ASSET_KINDS) fs.mkdirSync(path.join(ASSETS_DIR, kind), { recursive: true });
// Clamp a number into [min, max].
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
const GRID_LIFT_MAX = 3; // how high (world units) the table grid can float above the felt
// A bounded image data-URL (the only avatar shape we accept — small enough to
// sync in state, and never an arbitrary URL/script). Used by setAvatar + /me/avatar.
const isBoundedImageDataURL = (data) =>
typeof data === 'string' && data.startsWith('data:image') && data.length < 60000;
// A skybox reference: '' (default), a local equirect URL, or a cube descriptor
// {"t":"cube","f":[6 local urls]}. Only local /assets/sky/ or /sky/ paths, never
// external — every client loads it.
const skyUrlOk = (u) =>
typeof u === 'string' &&
u.length < 300 &&
!u.includes('..') &&
(u.startsWith('/assets/sky/') || u.startsWith('/sky/'));
// A custom dice-texture URL — a local /assets/dice/ image, no traversal. Format guard for the
// dice library (mirrors skyUrlOk); the file just landed via /upload?kind=dice.
const diceUrlOk = (u) =>
typeof u === 'string' && u.length < 300 && !u.includes('..') && u.startsWith('/assets/dice/');
const validSky = (v) => {
if (v === '') return true;
if (typeof v !== 'string' || v.length > 2000) return false;
if (v[0] === '{') {
let d;
try {
d = JSON.parse(v);
} catch {
return false;
}
return !!d && d.t === 'cube' && Array.isArray(d.f) && d.f.length === 6 && d.f.every(skyUrlOk);
}
return skyUrlOk(v);
};
// Keep an untrusted category name inside the allowlist (falls back to 'uploads').
const assetKind = (kind) => (ASSET_KINDS.includes(kind) ? kind : 'uploads');
const isDataURL = (value) => typeof value === 'string' && value.startsWith('data:image');
// A card "ref" is whatever string the client sends for a card face: procedural
// text, a URL, or an inline data-URL. We only bound its length here.
const deckRefOk = (value) => typeof value === 'string' && value.length < 200000;
// Write raw bytes into a category folder under a random name; return its URL.
function saveAsset(kind, bytes, ext = 'jpg') {
const validKind = assetKind(kind);
const name = crypto.randomBytes(9).toString('hex') + '.' + String(ext).replace(/[^a-z0-9]/gi, '');
fs.writeFileSync(path.join(ASSETS_DIR, validKind, name), bytes);
return `/assets/${validKind}/${name}`;
}
// Move an inline base64 image (data-URL) onto disk and return its URL, or null
// if the string isn't a data-URL. Used when saving a deck whose art was pasted
// inline rather than uploaded as a file.
function saveImageRef(dataURL, kind = 'decks') {
const match = /^data:(image\/\w+);base64,(.+)$/s.exec(dataURL);
if (!match) return null;
const [, mimeType, base64] = match;
const ext = mimeType.split('/')[1].replace('jpeg', 'jpg');
return saveAsset(kind, Buffer.from(base64, 'base64'), ext);
}
// ---- Orphaned-asset cleanup (admin) ---------------------------------------
// Files under saved-assets/ that nothing references anymore. "Referenced" is
// gathered conservatively (broad regex over every library row + room skybox +
// every LIVE table's state), and we skip anything newer than a day so an
// in-progress upload can't be swept. public/ is never touched (built-ins live there).
const LIVE_ROOMS = new Set(); // in-process TableRoom instances (see onCreate/onDispose)
const ASSET_PATH_RE = /\/assets\/(?:uploads|decks|boards|props|sky|dice)\/[A-Za-z0-9._-]+/g;
const ORPHAN_MIN_AGE_MS = 24 * 60 * 60 * 1000;
const extractAssetPaths = (str, set) => {
const m = String(str).match(ASSET_PATH_RE);
if (m) for (const p of m) set.add(p);
};
async function findOrphanAssets() {
const referenced = new Set();
for (const blob of await db.allAssetRefBlobs()) extractAssetPaths(blob, referenced); // DB refs (throws → abort)
for (const room of LIVE_ROOMS) extractAssetPaths(JSON.stringify(room.state.toJSON()), referenced); // live tables
const cutoff = Date.now() - ORPHAN_MIN_AGE_MS;
const orphans = [];
for (const kind of ASSET_KINDS) {
let names;
try {
names = fs.readdirSync(path.join(ASSETS_DIR, kind));
} catch {
continue;
}
for (const name of names) {
let st;
try {
st = fs.statSync(path.join(ASSETS_DIR, kind, name));
} catch {
continue;
}
if (!st.isFile() || st.mtimeMs > cutoff) continue; // skip dirs and too-new files
if (referenced.has(`/assets/${kind}/${name}`)) continue; // still in use
orphans.push({ url: `/assets/${kind}/${name}`, kind, name, size: st.size });
}
}
return orphans;
}
function trashOrphans(orphans) {
const moved = [];
for (const o of orphans) {
try {
const destDir = path.join(ASSETS_DIR, '.trash', o.kind);
fs.mkdirSync(destDir, { recursive: true });
fs.renameSync(path.join(ASSETS_DIR, o.kind, o.name), path.join(destDir, o.name));
moved.push(o.url);
} catch (e) {
console.error('[cleanup] move', o.url, e.message);
}
}
return moved;
}
// --- Synced state ----------------------------------------------------------
// defineTypes() is the no-build-step way to declare schema in plain JS.
// (The modern alternative is TypeScript with @type() decorators.)
// Clients rebuild this schema automatically via reflection — no shared file.
class Piece extends Schema {}
defineTypes(Piece, {
type: 'string',
owner: 'string',
props: 'string',
count: 'number', // count = cards in a deck (0 for other pieces)
x: 'number',
y: 'number',
z: 'number',
qx: 'number',
qy: 'number',
qz: 'number',
qw: 'number',
});
class Player extends Schema {} // PUBLIC per-player info: seat/turn order + hand count (never card identities)
defineTypes(Player, {
seat: 'number',
order: 'number',
hand: 'number',
name: 'string',
color: 'string',
avatar: 'string',
showing: 'number',
handBack: 'string',
role: 'string',
}); // showing = how many hand cards this player is currently revealing (public badge; never the content); handBack = the (public) back image of their hand cards; role = their per-room role (owner/gm/helper/player)
// Per-room role ladder — the server gates privileged actions by rank, and the
// client hides tools it can't use (courtesy only; these checks are the real rule).
// PUBLIC shared timer. We sync only the anchor (running/mode/base/since), never a
// ticking number — each client computes the live value with timerLive(), the same
// way the render loop interpolates piece positions locally. base = ms frozen at
// the last pause; since = server Date.now() at the last start (0 while paused).
class Timer extends Schema {
constructor() {
super();
this.running = false;
this.mode = 'up';
this.base = 0;
this.since = 0;
this.duration = 300000;
}
}
defineTypes(Timer, {
running: 'boolean',
mode: 'string',
base: 'number',
since: 'number',
duration: 'number',
});
// A durable scoreboard row: a free label + a number, keyed by id in State.scores.
class ScoreRow extends Schema {
constructor(label = '', score = 0) {
super();
this.label = label;
this.score = score;
}
}
defineTypes(ScoreRow, { label: 'string', score: 'number' });
// The whiteboard is a synced singleton (like the timer), NOT a physics piece: it
// rides a circular track behind the players (angle), one person "owns" it to draw,
// and it's dark (chalkboard) or light (whiteboard). Strokes are held server-side,
// not in the schema. Ephemeral — gone on room dispose.
class Whiteboard extends Schema {
constructor() {
super();
this.enabled = false;
this.angle = 0;
this.owner = '';
this.dark = true;
}
}
defineTypes(Whiteboard, { enabled: 'boolean', angle: 'number', owner: 'string', dark: 'boolean' });
// Dice trays are PERSONAL: one physics-walled box per seat, on the track directly behind that
// player (angle from SEAT_ANGLES). `State.trays` maps seat index → true for each tray that's
// out; the dice inside are ordinary `die` pieces tagged `props.traySeat = N`, so they ride
// scene save/load and the physics/net/roll all key on the owning seat. Each player toggles
// only their own tray. (Replaced the old single shared `DiceTray` singleton.)
// PUBLIC per-room measurement scale — a DISPLAY/snap layer over the FIXED world
// scale; it never rescales physics or piece sizes. worldPerUnit converts a world
// distance into display units; unitLabel is freeform ("in"/"cm"/"hex"/…). roundStep
// is the display rounding, in display units. cellWorld/gridStyle/gridColor/gridLift
// are the grid: cell size (world units), 'off'|'square'|'hex', the line colour (so it
// reads on any felt), and the grid's height above the felt. GM-set, durable.
class RoomScale extends Schema {
constructor() {
super();
this.worldPerUnit = 1;
this.unitLabel = 'u';
this.roundStep = 0.1;
this.cellWorld = 0;
this.cellZ = 0;
this.gridX = 0;
this.gridZ = 0;
this.gridStyle = 'off';
this.gridColor = '#ffffff';
this.gridLift = 0.05;
this.snapAnchor = 'center';
this.gridHidden = false;
}
}
defineTypes(RoomScale, {
worldPerUnit: 'number',
unitLabel: 'string',
roundStep: 'number',
cellWorld: 'number',
cellZ: 'number',
gridX: 'number',
gridZ: 'number',
gridStyle: 'string',
gridColor: 'string',
gridLift: 'number',
snapAnchor: 'string',
gridHidden: 'boolean',
});
// PUBLIC measurement/template overlay — a flat, non-physics annotation on the felt
// (rendered via the OVERLAY registry client-side). Every overlay is two points plus
// optional scalars, so one shape + one interaction (drag A→B) covers ruler today and
// circle/cone/line next. Never enters the physics world.
class Overlay extends Schema {
constructor() {
super();
this.kind = 'ruler';
this.color = '#ffffff';
this.owner = '';
this.x = 0;
this.z = 0;
this.x2 = 0;
this.z2 = 0;
this.w = 0;
this.ang = 0;
}
}
defineTypes(Overlay, {
kind: 'string',
color: 'string',
owner: 'string',
x: 'number',
z: 'number',
x2: 'number',
z2: 'number',
w: 'number',
ang: 'number',
});
class State extends Schema {
constructor() {
super();
this.pieces = new MapSchema();
this.players = new MapSchema();
this.turn = '';
this.timer = new Timer();
this.scores = new MapSchema();
this.notes = '';
this.tableX = TABLE.x;
this.tableZ = TABLE.z;
this.whiteboard = new Whiteboard();
this.trays = new MapSchema();
this.skybox = '';
this.feltColor = '#2f6b4f';
this.roomName = '';
this.turnPending = '';
this.unclaimed = new MapSchema();
this.scale = new RoomScale();
this.overlays = new MapSchema();
}
}
defineTypes(State, {
pieces: { map: Piece },
players: { map: Player },
turn: 'string',
timer: Timer,
scores: { map: ScoreRow },
notes: 'string',
tableX: 'number',
tableZ: 'number',
whiteboard: Whiteboard,
trays: { map: 'boolean' },
skybox: 'string',
feltColor: 'string',
roomName: 'string',
turnPending: 'string',
unclaimed: { map: 'string' },
scale: RoomScale,
overlays: { map: Overlay },
});
const PALETTE = [
'#4a78c9',
'#c94a4a',
'#4ac97a',
'#c9a24a',
'#9a4ac9',
'#4ac9c9',
'#e8793a',
'#d85ca8',
];
// --- Physics world (identical setup to the single-player client) ------------
// GM-resizable table: half-extent bounds (default is TABLE = 10 x 7).
const TABLE_LIMIT = { minX: 4, maxX: 20, minZ: 3, maxZ: 16 };
// Backstop against a scene inlining raw image data (the normal flow stores card/
// model art as file refs, so a real scene is tiny; this only catches the edge case).
const SCENE_MAX_BYTES = 2_000_000;
// Whiteboard: cap the server-held stroke history (a knob — raise/lower freely).
const WHITEBOARD_MAX_STROKES = 2000;
// Overlays: cap the room total and each player's share, so the map can't be spammed
// unbounded (mirrors the whiteboard/score caps). Both are free knobs.
const OVERLAY_MAX = 200;
const OVERLAY_MAX_PER_PLAYER = 40;
const OVERLAY_KINDS = new Set(['ruler', 'circle', 'cone', 'line']); // valid overlay kinds (add here + in the client OVERLAY registry)
const rnd = () => [(Math.random() - 0.5) * 8, SIM.spawnY, (Math.random() - 0.5) * 6];
// The landing/drop cue for a piece. A TILE (a card/deck carrying a `tile` kind — domino/letter/mahjong)
// clacks like a tile / thunks like its wooden box, instead of the paper card/deck sounds.
const isTilePiece = (p) => !!(p && p.tile);
const dropSfx = (t, p) =>
t === 'card'
? isTilePiece(p)
? 'tile-drop'
: 'card-drop'
: t === 'deck'
? isTilePiece(p)
? 'tiledeck-drop'
: 'deck-drop'
: t === 'die'
? 'die-drop'
: 'object-drop';
// Fisher–Yates in-place shuffle.
const shuffle = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = (Math.random() * (i + 1)) | 0;
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
// A card is identified by texture REFERENCES: 'rank:A:#111' (procedural face),
// 'back' (procedural back), or a data-URL / URL for an uploaded/file image.
// A deck = a shared back + an ordered list of front refs.
// A standard, shuffled 52-card deck as a list of face "refs" (see deckRefOk).
// A ref like "rank:A:♠:#000000" tells the client how to draw that face itself,
// so we never ship 52 images — just 52 short strings.
function buildSimpleDeck(jokers = false) {
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const suits = [
{ symbols: ['♠', '♣'], color: '#000000' }, // black
{ symbols: ['♥', '♦'], color: '#bd2500' }, // red
];
const cards = [];
for (const { symbols, color } of suits)
for (const symbol of symbols)
for (const rank of ranks) cards.push(`rank:${rank}:${symbol}:${color}`);
if (jokers) cards.push('joker:#bd2500', 'joker:#1a1a1a'); // one red, one black — a complete 54-card deck
return { back: 'back', cards: shuffle(cards) };
}
// A shuffled double-six domino set as a "deck" of 28 tiles. `tile: 'domino'` rides to every card
// so each spawned/held domino gets its 2:1 tile geometry (see cardGeom), face-down or face-up.
function buildDominoSet() {
const cards = [];
for (let a = 0; a <= 6; a++) for (let b = a; b <= 6; b++) cards.push(`domino:${a}:${b}`);
return { back: 'domback', cards: shuffle(cards), tile: 'domino', deckModel: 'bentwood' };
}
// A shuffled 100-tile letter bag for Wordy McWordface, built from LETTER_DIST (edit the bag there).
// `tile:'letter'` gives each tile its chunky square geometry; `snap:true` rides to every drawn/played
// tile (see geoOf) so it snaps into a board cell (see spawnCardFlat / releasePiece).
function buildScrabbleBag() {
const cards = [];
for (const [L, [count, value]] of Object.entries(LETTER_DIST))
for (let i = 0; i < count; i++) cards.push(`letter:${L}:${value}`); // blank letter '' → 'letter::0'
return {
back: 'lback',
cards: shuffle(cards),
tile: 'letter',
snap: true,
deckModel: 'bentwood',
};
}
// The standard 144-tile Mahjong wall as a shuffled "deck", from the MAHJONG face lists. `tile:'mahjong'`
// gives each tile its chunky geometry; the face refs are bundled image URLs (composited ivory tiles).
function buildMahjongWall() {
const cards = [];
const push = (id, n) => {
for (let i = 0; i < n; i++) cards.push(MAHJONG.base + id + '.png');
};
for (const suit of MAHJONG.suits) for (let r = 1; r <= 9; r++) push(suit + r, 4); // 3 suits × 1-9 × 4 = 108
for (const h of MAHJONG.honors) push(h, 4); // winds + dragons × 4 = 28
for (const b of MAHJONG.bonus) push(b, 1); // flowers + seasons × 1 = 8
return { back: 'mjback', cards: shuffle(cards), tile: 'mahjong', deckModel: 'bentwood' };
}
// The PUBLIC geometry/behavior a card/tile inherits from its deck: a named tile kind (`tile`), an
// explicit `geom` (custom-aspect image decks), and a `snap` flag (word tiles snap to the grid). Plain
// playing cards carry none, so this returns {} and nothing extra is stored — normal cards are
// untouched. Threaded wherever a card is dealt, drawn, held, or played, so a face-down tile still
// shows its true shape (and snap behavior) while its face is private.
const geoOf = (o) => {
const g = {};
if (o && o.tile) g.tile = o.tile;
if (o && o.geom) g.geom = o.geom;
if (o && o.snap) g.snap = true;
return g;
};
// --- The room --------------------------------------------------------------
class TableRoom extends Room {
async onCreate(options) {
this.maxClients = SEAT_ANGLES.length;
this.setState(new State());
this.world = buildWorld(SIM);
this.mat = this.world.__mat;
LIVE_ROOMS.add(this); // so orphan cleanup can see this table's live asset references
this.roomCode = (options && options.code) || null;
const roomRec = this.roomCode ? await db.findRoomByCode(this.roomCode) : null;
this.roomId = roomRec ? roomRec.id : null; // this live table's persistent room id (for membership)
this.state.roomName = roomRec ? String(roomRec.name || '').slice(0, 60) : ''; // synced display name for the table header (empty for the code-less editor room)
if (this.roomId) {
// restore the durable scoreboard, notes, and table size for this room
const rs = await db.getRoomState(this.roomId);
for (const row of rs.scoreboard) {
if (row && row.id)
this.state.scores.set(
String(row.id),
new ScoreRow(String(row.label || '').slice(0, 40), Number(row.score) || 0),
);
}
this.state.notes = String(rs.notes || '').slice(0, 8000);
this.state.tableX = clamp(rs.tableX, TABLE_LIMIT.minX, TABLE_LIMIT.maxX);
this.state.tableZ = clamp(rs.tableZ, TABLE_LIMIT.minZ, TABLE_LIMIT.maxZ);
if (/^#[0-9a-f]{6}$/i.test(rs.feltColor || '')) this.state.feltColor = rs.feltColor;
this.applyScale(rs.scale); // grid + measurement calibration (seeded defaults survive a null column)
this.state.skybox = validSky(String(rs.skybox || '')) ? String(rs.skybox || '') : '';
this.savedScene = rs.scene || null; // GM's last saved table state — applied below, once physics maps exist
}
this.buildBounds(this.state.tableX, this.state.tableZ); // table surface + walls at the current size
this.bodies = new Map(); // id -> CANNON.Body (physics, not synced)
this.targets = new Map(); // id -> {x,y,z} (drag target of the owner)
this.groups = new Map(); // sessionId -> Map(id -> {x,y,z} offset) (a multi-select group drag)
this._released = new Map(); // id -> release time; first hard impact after fires a landing sound
this.flips = new Map(); // id -> scripted half-flip in progress
this.deckCards = new Map(); // id -> [frontRef] PRIVATE: a deck's face-down cards (never synced)
this.drafts = new Map(); // sessionId -> {back,cards} PRIVATE: a deck being built in chunks
this.cardData = new Map(); // id -> { front } PRIVATE: a face-down table card's hidden face
this.hands = new Map(); // sessionId -> [{hid,front,back}] PRIVATE: each player's hidden hand
this.lastDrop = new Map(); // sessionId -> { ids:[pieceId], ts } PRIVATE: undo for handToTable
this.notebooks = new Map(); // user/session key -> text PRIVATE: each player's notes (ephemeral; dies with the room)
this.strokes = []; // whiteboard stroke history (server-held; sent to late-joiners, gone on dispose)
this.chatLog = []; // recent public chat (server-held; last 80, sent to late-joiners, gone on dispose)
this.shows = new Map(); // sessionId -> {to:Set,cards:[]} PRIVATE: an active hold-to-show (who sees which of the shower's cards)
this.pendingInspect = new Map(); // sessionId -> {deckId,front,back} PRIVATE: a card drawn to inspect, not yet placed
this.pendingHands = new Map(); // userId -> {name,cards} saved-game hands awaiting their owner's return (rebind on join)
this.pendingTurn = null; // userId whose turn it was in a saved game, awaiting their return
this.nextId = 1;
this.nextHid = 1;
this.nextOverlayId = 1;
// Scoreboard row ids: a plain counter, seeded past any rows just restored above
// (their 's<N>' keys) so a reloaded room's next add can't collide with an old row.
this.nextScoreId = 1;
this.state.scores.forEach((_, id) => {
const n = /^s(\d+)$/.exec(id);
if (n) this.nextScoreId = Math.max(this.nextScoreId, +n[1] + 1);
});
if (this.savedScene) this.applyScene(this.savedScene); // rebuild the saved table state (pieces persist across an empty room)
// Contain unexpected failures in every inline table message. Specialized
// library handlers below override the public message while sharing the same
// logging and recovery behavior.
const tableMessage = (type, handler) => safeMessage(this, type, handler);
// --- Movement: grab → drag → release (single + multi-select) ---------
registerMovementHandlers(this, {
isMovable: (piece) => !!(KINDS[piece.type] && KINDS[piece.type].mass > 0),
maxPieces: SIM.maxPieces,
});
registerPieceHandlers(this, {
maxPieces: SIM.maxPieces,
flipHop: SIM.flipHop,
roll: SIM.roll,
trayRoll: SIM.trayRoll,
boardKeys: Object.keys(BOARDS),
propKeys: Object.keys(PROPS),
dispenserKeys: Object.keys(DISPENSERS),
colliders: COLLIDER_TYPES,
geoOf,
randomPosition: rnd,
spawnY: SIM.spawnY,
});
// --- Cards: flip, deal, take, inspect, shuffle, split ----------------------
registerCardHandlers(this, {
flipHop: SIM.flipHop,
maxPieces: SIM.maxPieces,
spawnY: SIM.spawnY,
geoOf,
dropSfx,
randomPosition: rnd,
shuffle,
});
// Dispensers: hand out one item on left-click / left-drag (right-drag moves the
// whole thing, handled by the generic grab). Uniform, public copies — no private
// list, unlike a deck. dispense = drop beside it; dispenseDrag = drop + carry.
tableMessage('dispense', (client, message) => {
const parsed = pieceIdPayload(message);
if (!parsed) return;
const { id } = parsed;
const disp = this.state.pieces.get(id);
if (!disp || disp.type !== 'dispenser') return;
const item = this.dispenserItem(disp);
if (!item) return;
const body = this.bodies.get(id);
this.spawn(item.type, body ? this.besideDeck(body) : rnd(), item.props);
this.afterDispense(disp, id);
this.broadcast('sfx', { type: 'object-drop' });
});
tableMessage('dispenseDrag', (client, message) => {
const msg = dispenserDragPayload(message);
if (!msg) return;
const disp = this.state.pieces.get(msg.id);
if (!disp || disp.type !== 'dispenser') return;
const item = this.dispenserItem(disp);
if (!item) return;
const body = this.bodies.get(msg.id);
const newId = this.spawn(
item.type,
body ? [body.position.x, 2.5, body.position.z] : rnd(),
item.props,
);
this.afterDispense(disp, msg.id);
// Hand the new item straight to the dragger's cursor (reuses the deal-adopt path).
this.state.pieces.get(newId).owner = client.sessionId;
this.targets.set(newId, { x: msg.x, y: msg.y, z: msg.z });
client.send('dealt', { id: newId });
});
registerLibraryHandlers(this, {
db,
boardKeys: Object.keys(BOARDS),
colliders: COLLIDER_TYPES,
libraryKinds: LIBRARY_KINDS,
refOk: deckRefOk,
sanitizeGeom,
sanitizeMatGeom,
deckModels: Object.keys(DECK_MODELS),
randomPosition: rnd,
sceneMaxBytes: SCENE_MAX_BYTES,
skyUrlOk,
diceUrlOk,
});
registerRoomStateHandlers(this, {
createScoreRow: (label, score) => new ScoreRow(label, score),
tableLimits: TABLE_LIMIT,
gridLiftMax: GRID_LIFT_MAX,
sceneMaxBytes: SCENE_MAX_BYTES,
});
// Play a card from your hand onto the table, face-up or face-down.
tableMessage('playCard', (client, message) => {
const parsed = cardPlacementPayload(message);
if (!parsed) return;
const { hid, faceDown, x, z } = parsed;
const hand = this.hands.get(client.sessionId);
if (!hand) return;
const index = hand.findIndex((card) => card.hid === hid);
if (index < 0) return;
const [card] = hand.splice(index, 1);
const pos =
typeof x === 'number' && typeof z === 'number'
? [x, 3, z] // where the client dropped it
: [(Math.random() - 0.5) * 4, 3, (Math.random() - 0.5) * 3]; // or scattered
this.spawnHandCard(pos, card, faceDown);
this.sendHand(client);
this.broadcast('sfx', { type: dropSfx('card', card) }); // played tile clacks
});
// Reorder a player's own hand (drag-to-rearrange / sort). The order must be a permutation of
// the current hand — never adds or drops a card — so any drift (e.g. a card played mid-drag)
// just resyncs. Private, so it only re-sends to this client.
tableMessage('reorderHand', (client, message) => {
const parsed = reorderHandPayload(message);
if (!parsed) return;
const hand = this.hands.get(client.sessionId);
if (!hand || !hand.length) return;
if (parsed.order.length !== hand.length) return this.sendHand(client); // drift → resync
const byHid = new Map(hand.map((card) => [card.hid, card]));
const next = [];
for (const hid of parsed.order) {
const card = byHid.get(hid);
if (!card) return this.sendHand(client); // unknown hid → resync
next.push(card);
}
this.hands.set(client.sessionId, next); // length + uniqueness + all-present ⇒ a permutation
this.sendHand(client);
});
// Put the player's whole hand on the table (e.g. an Uno "swap hands"), face up or
// down, spread just in front of their marker (x/z sent by the client).
tableMessage('handToTable', (client, message) => {
const parsed = cardPlacementPayload(message, { wholeHand: true });
if (!parsed) return;
const { faceDown, x, z } = parsed;
const hand = this.hands.get(client.sessionId);
if (!hand || !hand.length) return;
const cx = typeof x === 'number' ? x : 0,
cz = typeof z === 'number' ? z : 0;
let spawned = 0;
const ids = []; // remember what we created, so the drop can be undone
for (const card of hand) {
if (this.state.pieces.size >= SIM.maxPieces) break; // respect the piece cap
const pos = [cx + (Math.random() - 0.5) * 3, 0.1, cz + (Math.random() - 0.5) * 1.6];
const id = this.spawnHandCard(pos, card, faceDown);
ids.push(id);
spawned++;
}
const capped = spawned < hand.length; // couldn't place the whole hand — table filled up
hand.splice(0, spawned);
this.sendHand(client);
if (spawned) {
this.lastDrop.set(client.sessionId, { ids, ts: Date.now() });
this.broadcast('sfx', { type: 'hand-drop' });
}
if (capped) this.notifyFull(client);
});
tableMessage('handFromTable', (client) => {
const batch = this.lastDrop.get(client.sessionId);
this.lastDrop.delete(client.sessionId); // one shot, either way
if (!batch || Date.now() - batch.ts > 30000) return; // 30s grace, matching the toast
let restored = 0;
for (const id of batch.ids) {
const piece = this.state.pieces.get(id);
if (!piece || piece.type !== 'card') continue; // moved, taken, or table reset
const props = readProps(piece);
const front = (this.cardData.get(id) || {}).front || props.front;
this.addToHand(client, front, props.back || 'back', geoOf(props), props.open);
this.removePiece(id);
restored++;
}
client.send('dropUndone', { restored });
if (restored) this.broadcast('sfx', { type: 'card-take' });
});
// Wipe the room back to an empty table — pieces and all private state.
tableMessage('reset', (client) => {
if (this.rank(client) < RANK.gm) return; // wiping the table is GM+
this.clearTable();
const t = this.state.timer; // stop and zero the shared timer too
t.running = false;
t.since = 0;
t.base = t.mode === 'down' ? t.duration : 0;
});
// Load a one-click starter game — clears the table and sets up the chosen game (GM+).
tableMessage('loadStarter', (client, message) => {
if (this.rank(client) < RANK.gm) return; // replacing the whole table is GM+ (like scene load / reset)
const parsed = oneField(message, 'game', (game) =>
typeof game === 'string' && STARTERS[game] ? game : null,
);
if (!parsed) return;
this.setupStarter(parsed.game);
});
// --- Member management (DB-backed; all mutations authorized server-side) ---
registerMemberHandlers(this, { db });
tableMessage('nextTurn', () => this.advanceTurn());
tableMessage('turnOrder', (client, message) => {
if (this.rank(client) < RANK.gm) return;
const parsed = oneField(message, 'order', (value) => {
if (!Array.isArray(value) || value.length !== this.state.players.size) return null;
const ids = value.every(
(sid) => typeof sid === 'string' && sid.length <= 64 && this.state.players.has(sid),
)
? [...value]
: null;
return ids && new Set(ids).size === ids.length ? ids : null;
});
if (!parsed) return;
parsed.order.forEach((sid, order) => {
this.state.players.get(sid).order = order;
});
});
tableMessage('setName', (client, message) => {
const parsed = oneField(message, 'name', (name) => boundedString(name, { min: 1, max: 20 }));
if (!parsed) return;
const player = this.state.players.get(client.sessionId);
if (player) player.name = parsed.name.trim() || player.name;
});
tableMessage('setAvatar', async (client, message) => {
const parsed = oneField(message, 'data', (data) =>
isBoundedImageDataURL(data) ? data : null,
);
if (!parsed) return;
const player = this.state.players.get(client.sessionId);
if (player) {
// Persist to the account so it follows the user across sessions and rooms.
if (client.auth && client.auth.userId)
await db.setUserAvatar(client.auth.userId, parsed.data);
player.avatar = parsed.data;
}
});
registerOverlayHandlers(this, {
createOverlay: () => new Overlay(),
kinds: OVERLAY_KINDS,
maxLength: MEASURE.maxLen,
maxOverlays: OVERLAY_MAX,
maxPerPlayer: OVERLAY_MAX_PER_PLAYER,
maxStrokes: WHITEBOARD_MAX_STROKES,
});
registerRoomFeatureHandlers(this, {
trayRoll: SIM.trayRoll,
validSky,
});
this.setSimulationInterval((dt) => this.update(dt), 1000 / 60); // fixed 60Hz sim
this.setPatchRate(1000 / 60); // 60Hz state broadcast (delta-compressed; cheap on LAN)
}
// Create a piece: a physics body + a synced Piece record, wired together by id.
// pos is [x,y,z]; props are the type-specific fields (shape, sides, back, …).
spawn(type, pos, props = {}, quat = null) {
const mass = type === 'prop' ? (PROPS[props.shape] || PROPS.box).mass : KINDS[type].mass;
const body = new CANNON.Body({ mass, material: this.mat });
const collider = buildCollider(type, props, { cardColliderThickness: SIM.cards.colliderThick });
if (collider.shape)
body.addShape(collider.shape, collider.offset); // some colliders (flat) sit off-centre
else body.addShape(collider);
body.position.set(pos[0], pos[1], pos[2]);
// An exact orientation (scene load) wins; otherwise dice/props tumble, boards/decks stay flat.
if (quat && quat.length === 4) {
body.quaternion.set(quat[0], quat[1], quat[2], quat[3]);
} else if (KINDS[type].mass > 0 && type !== 'deck' && type !== 'dispenser' && type !== 'mat') {
body.quaternion.setFromEuler(Math.random() * 6, Math.random() * 6, Math.random() * 6);
}
// Cards get their own damping/sleep tuning so stacks settle nicely.
if (type === 'card') {
body.angularDamping = SIM.cards.angDamp;
body.linearDamping = SIM.cards.linDamp;
body.sleepSpeedLimit = SIM.cards.sleepSpeed;
body.sleepTimeLimit = SIM.cards.sleepTime;
} else if (type === 'mat') {
body.angularDamping = SIM.damp.flat; // stays level
body.linearDamping = 0.6; // a heavy surface — resting pieces / bumps don't shove it
} else {
body.angularDamping = type === 'deck' ? SIM.damp.flat : SIM.damp.solid;
}
if (props.traySeat != null) body.__traySeat = +props.traySeat; // a tray die obeys its seat's tray bounds, not the table's
this.world.addBody(body);
const id = String(this.nextId++);
const piece = new Piece();
piece.type = type;
piece.owner = '';
piece.count = 0;
piece.props = '{}';
if (type === 'deck') {
// A deck's cards + order are PRIVATE (deckCards); only the shared back is
// published, which is all a client needs to render the face-down stack.
const deckData =
props.set === 'domino'
? buildDominoSet() // a domino boneyard, spawned on its own (no starter/table-clear)
: props.set === 'letter'
? buildScrabbleBag() // a Wordy McWordface letter bag on its own
: props.set === 'mahjong'
? buildMahjongWall() // a 144-tile mahjong wall on its own
: props.cards && props.cards.length
? {
back: props.back || 'back',
cards: props.cards,
...geoOf(props),
deckModel: props.deckModel,
} // pre-built cards (e.g. a starter) can carry a skin
: buildSimpleDeck(!!props.jokers);
this.deckCards.set(id, deckData.cards.slice());
piece.count = deckData.cards.length;
const deckProps = { back: deckData.back, ...geoOf(deckData) }; // deck-level tile/geom rides to its cards
if (deckData.deckModel && DECK_MODELS[deckData.deckModel])
deckProps.model = deckData.deckModel; // an optional 3D box/bag/pouch skin
if (props.color != null) deckProps.color = props.color; // skin tints (pouch: bag / string)
if (props.textColor != null) deckProps.textColor = props.textColor;
if (props.open) {
deckProps.open = true; // a deck of double-sided tiles → dealt tiles turn over
const topBack = cardBackRef(deckData.cards[deckData.cards.length - 1]);
if (topBack) deckProps.cover = topBack; // its visible top face follows the current top tile
}
writeProps(piece, deckProps);
} else if (type === 'dispenser') {
const d = DISPENSERS[props.disp] || {};
piece.count = d.infinite || !d.count ? 0 : clamp(+props.count || d.count.def, 1, d.count.max); // remaining items (0 = infinite)
writeProps(piece, props);
} else {
writeProps(piece, props);
}
this.writeTransform(piece, body);
this.state.pieces.set(id, piece);
this.bodies.set(id, body);
body.addEventListener('collide', (e) => {
// landing sound, only for pieces a player just dropped
const rel = this._released.get(id);
if (rel === undefined) return; // deals/rolls/idle collisions stay silent here
if (Date.now() - rel > 3000) {
this._released.delete(id);
return;
} // never really landed — disarm
if (Math.abs(e.contact.getImpactVelocityAlongNormal()) < SIM.impact.minVel) return; // ignore gentle grazes
this._released.delete(id); // one cue per drop (kills multi-bounce spam)
this.broadcast('sfx', { type: dropSfx(type, props) }); // props carries `tile` for tile pieces/decks
});
if (type === 'deck') this.updateDeckCollider(id); // match the collider to the stack height
if (type === 'dispenser') this.updateStackCollider(id); // stack cylinder ∝ count (no-op for a bowl)
return id;
}
// --- Small card helpers (shared by the deal/draw/play handlers) -------------
// Spawn a card lying flat at pos (no random tumble); returns its id. Callers
// set the private front (cardData) and/or owner afterward as needed.
spawnCardFlat(pos, publicProps) {
if (publicProps && publicProps.snap && gridActive(this.state.scale)) {
// a word tile played onto the board snaps into its cell
const p = snapToCell(pos[0], pos[2], this.state.scale);
pos = [p.x, pos[1], p.z];
}
const id = this.spawn('card', pos, publicProps);
const body = this.bodies.get(id);
body.quaternion.set(0, 0, 0, 1);
this.writeTransform(this.state.pieces.get(id), body);
return id;