@zaisma/effects 0.0.0-stage → 1.0.1

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 (123) hide show
  1. package/EFFECT-FILES.md +301 -0
  2. package/LICENSE.txt +93 -0
  3. package/README.md +63 -2
  4. package/batches/chunks.js +294 -0
  5. package/batches/marks.js +160 -0
  6. package/batches/ribbons.js +233 -0
  7. package/batches/shared.js +155 -0
  8. package/batches/sprites.js +447 -0
  9. package/batches/warps.js +222 -0
  10. package/budget.js +115 -0
  11. package/debris.js +173 -0
  12. package/emit.js +143 -0
  13. package/flashes.js +113 -0
  14. package/format.js +365 -0
  15. package/index.d.ts +373 -0
  16. package/index.js +1168 -0
  17. package/library/bubbles_rising.json +47 -0
  18. package/library/bullet_impact.json +588 -0
  19. package/library/campfire.json +235 -0
  20. package/library/candle_flame.json +100 -0
  21. package/library/confetti.json +165 -0
  22. package/library/dash_burst.json +73 -0
  23. package/library/debris_glass.json +96 -0
  24. package/library/debris_metal.json +106 -0
  25. package/library/debris_stone.json +106 -0
  26. package/library/debris_wood.json +101 -0
  27. package/library/dust_motes.json +51 -0
  28. package/library/dust_puff.json +49 -0
  29. package/library/electric_sparks.json +175 -0
  30. package/library/embers_drift.json +55 -0
  31. package/library/exhaust_puff.json +62 -0
  32. package/library/explosion_air.json +232 -0
  33. package/library/explosion_large.json +373 -0
  34. package/library/explosion_magic.json +266 -0
  35. package/library/explosion_medium.json +289 -0
  36. package/library/explosion_small.json +289 -0
  37. package/library/explosion_water.json +177 -0
  38. package/library/falling_leaves.json +54 -0
  39. package/library/fire_burst.json +185 -0
  40. package/library/fire_large.json +279 -0
  41. package/library/fireball.json +288 -0
  42. package/library/fireflies.json +51 -0
  43. package/library/firework_burst.json +127 -0
  44. package/library/footstep.json +270 -0
  45. package/library/fountain_spray.json +80 -0
  46. package/library/frost_burst.json +202 -0
  47. package/library/ground_mist.json +50 -0
  48. package/library/ground_slam.json +122 -0
  49. package/library/heat_haze.json +24 -0
  50. package/library/hit_blade.json +150 -0
  51. package/library/hit_block.json +157 -0
  52. package/library/hit_critical.json +293 -0
  53. package/library/hit_heavy.json +211 -0
  54. package/library/hit_light.json +122 -0
  55. package/library/hit_magic.json +114 -0
  56. package/library/impact.json +417 -0
  57. package/library/impact_heavy.json +279 -0
  58. package/library/index.json +464 -0
  59. package/library/jump_puff.json +46 -0
  60. package/library/landing_heavy.json +105 -0
  61. package/library/landing_puff.json +75 -0
  62. package/library/level_up.json +164 -0
  63. package/library/lightning_arc.json +90 -0
  64. package/library/lightning_strike.json +387 -0
  65. package/library/magic_aura.json +127 -0
  66. package/library/magic_bolt.json +107 -0
  67. package/library/magic_bolt_impact.json +181 -0
  68. package/library/magic_cast.json +115 -0
  69. package/library/magic_charge.json +91 -0
  70. package/library/magic_heal.json +123 -0
  71. package/library/magic_shield.json +89 -0
  72. package/library/magic_teleport.json +177 -0
  73. package/library/mark_bullet_hole.json +20 -0
  74. package/library/mark_crack.json +18 -0
  75. package/library/mark_footprint.json +20 -0
  76. package/library/mark_frost.json +18 -0
  77. package/library/mark_puddle.json +18 -0
  78. package/library/mark_scorch.json +18 -0
  79. package/library/mark_slash.json +18 -0
  80. package/library/mark_splat.json +18 -0
  81. package/library/pickup_collect.json +117 -0
  82. package/library/pickup_glow.json +76 -0
  83. package/library/poison_cloud.json +107 -0
  84. package/library/portal.json +328 -0
  85. package/library/shockwave_air.json +71 -0
  86. package/library/shockwave_ground.json +95 -0
  87. package/library/slide_dust.json +48 -0
  88. package/library/smoke_column.json +93 -0
  89. package/library/smoke_puff.json +48 -0
  90. package/library/smoke_screen.json +87 -0
  91. package/library/sparks_burst.json +85 -0
  92. package/library/sparks_fountain.json +93 -0
  93. package/library/sparks_shower.json +89 -0
  94. package/library/splash_large.json +181 -0
  95. package/library/splash_small.json +111 -0
  96. package/library/steam_vent.json +64 -0
  97. package/library/summon_circle.json +494 -0
  98. package/library/swim_splash.json +77 -0
  99. package/library/torch_flame.json +219 -0
  100. package/library/trail_blade.json +39 -0
  101. package/library/trail_blade_fire.json +90 -0
  102. package/library/trail_dash.json +80 -0
  103. package/library/trail_magic.json +94 -0
  104. package/library/trail_projectile.json +31 -0
  105. package/library/trail_smoke.json +125 -0
  106. package/library/warp_pulse.json +22 -0
  107. package/library/warp_ripple.json +23 -0
  108. package/library/water_ripple.json +69 -0
  109. package/library/waterfall_mist.json +95 -0
  110. package/looks.js +162 -0
  111. package/motion.js +145 -0
  112. package/online.d.ts +79 -0
  113. package/online.js +32 -0
  114. package/package.json +69 -4
  115. package/partners.js +255 -0
  116. package/piece.json +415 -0
  117. package/piece.json.js +416 -0
  118. package/server.d.ts +55 -0
  119. package/server.js +26 -0
  120. package/shapes.js +269 -0
  121. package/sync.js +528 -0
  122. package/tables.js +109 -0
  123. package/weather.js +289 -0
package/sync.js ADDED
@@ -0,0 +1,528 @@
1
+ // Effects through a room: every player sees the same effect, particle for particle, at the same moment.
2
+ //
3
+ // An effect is drawn from its seed and its start alone, so sharing one is sharing those: a play is one message of a
4
+ // few dozen bytes on the room's clock, and nothing is sent while it plays. Each game starts it as far in as the
5
+ // room's clock says, so a message that took 80 ms to arrive shows the effect 80 ms old. Effects that keep playing
6
+ // (shared.start) and the weather are kept by whoever is in charge of the room, and reach a player who joins late.
7
+ //
8
+ // The same file runs in the game (online.js) and on its game server (server.js); each hands in the online core's
9
+ // defineKind. A game server passes plays on, holds every player to a rate, and can refuse one (beforePlay). On the
10
+ // relay each player's game holds the others to the same rate, so nobody floods a room.
11
+ import { PieceError } from "../piece/index.js";
12
+ import { EFFECT_NAME_PATTERN, MAXIMUM_EFFECT_NAME_CHARACTER_COUNT, SURFACE_KINDS } from "./format.js";
13
+
14
+ const PIECE_NAME = "@zaisma/effects";
15
+ const PLAY_CODE = 1;
16
+ const STOP_CODE = 2;
17
+ const HAS_DIRECTION = 1;
18
+ const HAS_NORMAL = 2;
19
+ const HAS_TO_POSITION = 4;
20
+ const HAS_SCALE = 8;
21
+ const HAS_STRENGTH = 16;
22
+ const HAS_COLOR = 32;
23
+ const HAS_SURFACE = 64;
24
+ const IS_KEPT = 128;
25
+ const FIXED_BYTE_COUNT = 26;
26
+ const MAXIMUM_PLAY_BYTE_COUNT = FIXED_BYTE_COUNT + 12 + 12 + 4 + 4 + 3 + 1 + 4 + 1 + MAXIMUM_EFFECT_NAME_CHARACTER_COUNT;
27
+ /** How many effects that keep playing a room holds at once. */
28
+ export const MAXIMUM_KEPT_COUNT = 64;
29
+ const MAXIMUM_PLACE_M = 1e7;
30
+ // A play may say it started a little ago (its way here), never long ago or ahead.
31
+ const MAXIMUM_START_AGO_MS = 5000;
32
+ const MAXIMUM_START_AHEAD_MS = 250;
33
+ const HEX_COLOR_PATTERN = /^#[0-9a-f]{6}$/;
34
+ const AT_FIELDS = ["positionM", "direction", "normal", "toPositionM", "scalePct", "strengthPct", "color", "surfaceKind"];
35
+ const KIND_FIELDS = ["effectNames", "maximumPlaysPerSec", "beforePlay"];
36
+ /** The weather a room shares: the piece's own settings, by their stated names on the wire. */
37
+ const WEATHER_FIELDS = [
38
+ { name: "rainPct", statedName: "rain_pct", maximumNumber: 100 },
39
+ { name: "snowPct", statedName: "snow_pct", maximumNumber: 100 },
40
+ { name: "fogPct", statedName: "fog_pct", maximumNumber: 100 },
41
+ { name: "windSpeedMPerSec", statedName: "wind_speed_m_per_sec", maximumNumber: 40 },
42
+ { name: "windDirectionDeg", statedName: "wind_direction_deg", maximumNumber: 360 },
43
+ { name: "windGustPct", statedName: "wind_gust_pct", maximumNumber: 100 },
44
+ ];
45
+
46
+ const refuse = (code, message, field, fix) => {
47
+ throw new PieceError(PIECE_NAME, code, { message, field, fix });
48
+ };
49
+ const isPoint = (value) => value !== null && typeof value === "object" && [value.x, value.y, value.z].every((part) => Number.isFinite(part) && Math.abs(part) <= MAXIMUM_PLACE_M);
50
+ const isNumberIn = (value, low, high) => Number.isFinite(value) && value >= low && value <= high;
51
+ const isName = (value) => typeof value === "string" && value.length <= MAXIMUM_EFFECT_NAME_CHARACTER_COUNT && EFFECT_NAME_PATTERN.test(value);
52
+ const toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
53
+ function fromHex(hex) {
54
+ if (typeof hex !== "string" || hex.length % 2 !== 0 || hex.length > MAXIMUM_PLAY_BYTE_COUNT * 2 || !/^[0-9a-f]*$/.test(hex)) return null;
55
+ const bytes = new Uint8Array(hex.length / 2);
56
+ for (let index = 0; index < bytes.length; index += 1) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
57
+ return bytes;
58
+ }
59
+
60
+ /**
61
+ * A play as bytes: its code, what it carries, when it started on the room's clock, its seed, where, then only what
62
+ * the play set (a direction or a normal, where it runs to, a scale, a strength, a colour, a surface, its kept id),
63
+ * and its name.
64
+ */
65
+ export function encodePlay(play) {
66
+ const way = play.normal ?? play.direction ?? null;
67
+ let flags = 0;
68
+ let byteCount = FIXED_BYTE_COUNT + 1 + play.effectName.length;
69
+ if (way) {
70
+ flags |= play.normal ? HAS_NORMAL : HAS_DIRECTION;
71
+ byteCount += 12;
72
+ }
73
+ if (play.toPositionM) {
74
+ flags |= HAS_TO_POSITION;
75
+ byteCount += 12;
76
+ }
77
+ if (play.scalePct !== null && play.scalePct !== undefined) {
78
+ flags |= HAS_SCALE;
79
+ byteCount += 4;
80
+ }
81
+ if (play.strengthPct !== null && play.strengthPct !== undefined) {
82
+ flags |= HAS_STRENGTH;
83
+ byteCount += 4;
84
+ }
85
+ if (play.color) {
86
+ flags |= HAS_COLOR;
87
+ byteCount += 3;
88
+ }
89
+ if (play.surfaceKind) {
90
+ flags |= HAS_SURFACE;
91
+ byteCount += 1;
92
+ }
93
+ if (play.keptId) {
94
+ flags |= IS_KEPT;
95
+ byteCount += 4;
96
+ }
97
+ const bytes = new Uint8Array(byteCount);
98
+ const view = new DataView(bytes.buffer);
99
+ let at = 0;
100
+ const point = (value) => {
101
+ view.setFloat32(at, value.x, true);
102
+ view.setFloat32(at + 4, value.y, true);
103
+ view.setFloat32(at + 8, value.z, true);
104
+ at += 12;
105
+ };
106
+ view.setUint8(0, PLAY_CODE);
107
+ view.setUint8(1, flags);
108
+ view.setFloat64(2, play.startedAtMs, true);
109
+ view.setUint32(10, play.seedNumber >>> 0, true);
110
+ at = 14;
111
+ point(play.positionM);
112
+ if (way) point(way);
113
+ if (play.toPositionM) point(play.toPositionM);
114
+ if (flags & HAS_SCALE) {
115
+ view.setFloat32(at, play.scalePct, true);
116
+ at += 4;
117
+ }
118
+ if (flags & HAS_STRENGTH) {
119
+ view.setFloat32(at, play.strengthPct, true);
120
+ at += 4;
121
+ }
122
+ if (flags & HAS_COLOR) {
123
+ const colorNumber = Number.parseInt(play.color.slice(1), 16);
124
+ view.setUint8(at, colorNumber >> 16);
125
+ view.setUint8(at + 1, (colorNumber >> 8) & 255);
126
+ view.setUint8(at + 2, colorNumber & 255);
127
+ at += 3;
128
+ }
129
+ if (flags & HAS_SURFACE) {
130
+ view.setUint8(at, SURFACE_KINDS.indexOf(play.surfaceKind));
131
+ at += 1;
132
+ }
133
+ if (flags & IS_KEPT) {
134
+ view.setUint32(at, play.keptId >>> 0, true);
135
+ at += 4;
136
+ }
137
+ view.setUint8(at, play.effectName.length);
138
+ for (let index = 0; index < play.effectName.length; index += 1) view.setUint8(at + 1 + index, play.effectName.charCodeAt(index));
139
+ return bytes;
140
+ }
141
+
142
+ /** A play from bytes, every part checked, or null for bytes that aren't one. */
143
+ export function decodePlay(bytes) {
144
+ if (!(bytes instanceof Uint8Array) || bytes.length < FIXED_BYTE_COUNT + 2 || bytes.length > MAXIMUM_PLAY_BYTE_COUNT || bytes[0] !== PLAY_CODE) return null;
145
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
146
+ const flags = view.getUint8(1);
147
+ if (flags & HAS_DIRECTION && flags & HAS_NORMAL) return null;
148
+ let at = 14;
149
+ let isShort = false;
150
+ const has = (byteCount) => {
151
+ if (at + byteCount > bytes.length) isShort = true;
152
+ return !isShort;
153
+ };
154
+ const point = () => {
155
+ if (!has(12)) return null;
156
+ const value = { x: view.getFloat32(at, true), y: view.getFloat32(at + 4, true), z: view.getFloat32(at + 8, true) };
157
+ at += 12;
158
+ return value;
159
+ };
160
+ const play = { effectName: "", positionM: null, direction: null, normal: null, toPositionM: null, scalePct: null, strengthPct: null, color: null, surfaceKind: null, seedNumber: view.getUint32(10, true), startedAtMs: view.getFloat64(2, true), keptId: null };
161
+ play.positionM = point();
162
+ if (flags & HAS_DIRECTION) play.direction = point();
163
+ if (flags & HAS_NORMAL) play.normal = point();
164
+ if (flags & HAS_TO_POSITION) play.toPositionM = point();
165
+ if (flags & HAS_SCALE && has(4)) {
166
+ play.scalePct = view.getFloat32(at, true);
167
+ at += 4;
168
+ }
169
+ if (flags & HAS_STRENGTH && has(4)) {
170
+ play.strengthPct = view.getFloat32(at, true);
171
+ at += 4;
172
+ }
173
+ if (flags & HAS_COLOR && has(3)) {
174
+ play.color = `#${((view.getUint8(at) << 16) | (view.getUint8(at + 1) << 8) | view.getUint8(at + 2)).toString(16).padStart(6, "0")}`;
175
+ at += 3;
176
+ }
177
+ if (flags & HAS_SURFACE && has(1)) {
178
+ play.surfaceKind = SURFACE_KINDS[view.getUint8(at)] ?? "";
179
+ at += 1;
180
+ }
181
+ if (flags & IS_KEPT && has(4)) {
182
+ play.keptId = view.getUint32(at, true);
183
+ at += 4;
184
+ }
185
+ if (!has(1)) return null;
186
+ const nameLength = view.getUint8(at);
187
+ if (isShort || at + 1 + nameLength !== bytes.length) return null;
188
+ play.effectName = String.fromCharCode(...bytes.subarray(at + 1));
189
+ const isSound =
190
+ isName(play.effectName) &&
191
+ Number.isFinite(play.startedAtMs) &&
192
+ isPoint(play.positionM) &&
193
+ [play.direction, play.normal, play.toPositionM].every((value) => value === null || isPoint(value)) &&
194
+ (play.scalePct === null || isNumberIn(play.scalePct, 0.01, 10000)) &&
195
+ (play.strengthPct === null || isNumberIn(play.strengthPct, 0, 1000)) &&
196
+ play.surfaceKind !== "" &&
197
+ (!(flags & IS_KEPT) || play.keptId > 0);
198
+ return isSound ? play : null;
199
+ }
200
+
201
+ const encodeStop = (keptId) => {
202
+ const bytes = new Uint8Array(5);
203
+ bytes[0] = STOP_CODE;
204
+ new DataView(bytes.buffer).setUint32(1, keptId >>> 0, true);
205
+ return bytes;
206
+ };
207
+ const decodeStop = (bytes) => (bytes instanceof Uint8Array && bytes.length === 5 && bytes[0] === STOP_CODE ? new DataView(bytes.buffer, bytes.byteOffset, 5).getUint32(1, true) : 0);
208
+
209
+ /** So many a second for each key, with a second's worth saved up: take(key, nowMs) answers whether one more may go. */
210
+ function createRateCap(perSec) {
211
+ const left = new Map();
212
+ return {
213
+ take(key, nowMs) {
214
+ const held = left.get(key) ?? { count: perSec, atMs: nowMs };
215
+ held.count = Math.min(held.count + (Math.max(nowMs - held.atMs, 0) / 1000) * perSec, perSec);
216
+ held.atMs = nowMs;
217
+ left.set(key, held);
218
+ if (held.count < 1) return false;
219
+ held.count -= 1;
220
+ return true;
221
+ },
222
+ forget: (key) => left.delete(key),
223
+ };
224
+ }
225
+
226
+ /** What play and start take, checked as effects.play checks it, as a play ready to send. */
227
+ function playOf(effectName, at, effectNames, callName) {
228
+ if (!isName(effectName)) refuse("bad_play", `${callName} takes an effect's name.`, "effectName", 'Give the name of an effect, like "explosion_large".');
229
+ if (effectNames && !effectNames.includes(effectName)) refuse("unknown_effect", `"${effectName}" isn't one of this room's shared effects.`, "effectName", `Use one of: ${effectNames.join(", ")}; or add it to effectNames, in the game and on its game server.`);
230
+ if (at === null || typeof at !== "object" || Array.isArray(at)) refuse("bad_play", `${callName} takes where to play as an object.`, "at", "Give { positionM: { x, y, z } }.");
231
+ for (const field of Object.keys(at)) {
232
+ if (!AT_FIELDS.includes(field)) refuse("unknown_argument", `A shared play has no "${field}".`, field, `Give only: ${AT_FIELDS.join(", ")}. An effect that rides on an object (follow) is each game's own: play it with effects.play.`);
233
+ }
234
+ if (!isPoint(at.positionM)) refuse("bad_play", `${callName} needs where to play.`, "positionM", "Give positionM: { x, y, z } in metres.");
235
+ for (const field of ["direction", "normal", "toPositionM"]) {
236
+ if (at[field] !== undefined && at[field] !== null && !isPoint(at[field])) refuse("bad_play", `${field} isn't { x, y, z }.`, field, "Give { x, y, z }.");
237
+ }
238
+ if (at.direction && at.normal) refuse("bad_play", "A play takes a direction or a normal, never both.", "normal", "Give the one the effect goes by: normal for a surface it lands on, direction for the way it's thrown.");
239
+ if (at.scalePct !== undefined && at.scalePct !== null && !isNumberIn(at.scalePct, 0.01, 10000)) refuse("bad_play", "scalePct isn't a number above 0, up to 10000.", "scalePct", "Give how big to play it against its file: 100 is as written.");
240
+ if (at.strengthPct !== undefined && at.strengthPct !== null && !isNumberIn(at.strengthPct, 0, 1000)) refuse("bad_play", "strengthPct isn't a number from 0 to 1000.", "strengthPct", "Give how strong to play it: 100 is as written.");
241
+ if (at.color !== undefined && at.color !== null && !(typeof at.color === "string" && HEX_COLOR_PATTERN.test(at.color))) refuse("bad_play", "color isn't a colour.", "color", 'Give a colour as six hex digits in lowercase, like "#ff7a1a", or leave it out.');
242
+ if (at.surfaceKind !== undefined && at.surfaceKind !== null && !SURFACE_KINDS.includes(at.surfaceKind)) refuse("bad_play", `surfaceKind is ${JSON.stringify(at.surfaceKind)}, which isn't a surface kind.`, "surfaceKind", `Give one of: ${SURFACE_KINDS.join(", ")}.`);
243
+ const copy = (value) => (value ? { x: value.x, y: value.y, z: value.z } : null);
244
+ return { effectName, positionM: copy(at.positionM), direction: copy(at.direction), normal: copy(at.normal), toPositionM: copy(at.toPositionM), scalePct: at.scalePct ?? null, strengthPct: at.strengthPct ?? null, color: at.color ?? null, surfaceKind: at.surfaceKind ?? null, seedNumber: 0, startedAtMs: 0, keptId: null };
245
+ }
246
+
247
+ /** The weather as the wire carries it, from what setWeather was given: only its own fields, each in range. */
248
+ function weatherOf(values, callName) {
249
+ if (values === null || typeof values !== "object" || Array.isArray(values)) refuse("bad_weather", `${callName} takes the weather as an object.`, "weather", "Give { rainPct: 60, windSpeedMPerSec: 8 }: only what changes.");
250
+ const stated = {};
251
+ for (const [name, value] of Object.entries(values)) {
252
+ const field = WEATHER_FIELDS.find((candidate) => candidate.name === name);
253
+ if (!field) refuse("unknown_argument", `The weather has no "${name}".`, name, `Give only: ${WEATHER_FIELDS.map((candidate) => candidate.name).join(", ")}.`);
254
+ if (!isNumberIn(value, 0, field.maximumNumber)) refuse("bad_weather", `${name} isn't a number from 0 to ${field.maximumNumber}.`, name, `Give a number from 0 to ${field.maximumNumber}.`);
255
+ stated[field.statedName] = value;
256
+ }
257
+ return stated;
258
+ }
259
+ /** The weather as the piece's settings take it, from the wire: what isn't a field in range is left out. */
260
+ function weatherSettings(stated) {
261
+ const values = {};
262
+ if (stated === null || typeof stated !== "object") return values;
263
+ for (const field of WEATHER_FIELDS) if (isNumberIn(stated[field.statedName], 0, field.maximumNumber)) values[field.name] = stated[field.statedName];
264
+ return values;
265
+ }
266
+
267
+ const newSeed = () => (Math.random() * 4294967296) >>> 0;
268
+ const newKeptId = () => ((Math.random() * 4294967295) >>> 0) + 1;
269
+
270
+ /**
271
+ * The effects' kind of sync, made with the online core's defineKind (the game's or the game server's). given:
272
+ * { effectNames, maximumPlaysPerSec, beforePlay }: effectNames closes which effects may be shared (default any
273
+ * name); maximumPlaysPerSec is each player's rate (default 20); beforePlay(play, { playerId, roomState }) runs on
274
+ * the game server before a player's play is passed on, and answers false to refuse it.
275
+ */
276
+ export function effectsKindFrom(defineKind, given = {}) {
277
+ if (given === null || typeof given !== "object" || Array.isArray(given)) refuse("bad_argument", "effectsKind takes its options as an object.", null, "Give { effectNames, maximumPlaysPerSec, beforePlay }, or nothing.");
278
+ for (const field of Object.keys(given)) {
279
+ if (!KIND_FIELDS.includes(field)) refuse("unknown_argument", `effectsKind has no "${field}".`, field, `Give only: ${KIND_FIELDS.join(", ")}.`);
280
+ }
281
+ const effectNames = given.effectNames ?? null;
282
+ if (effectNames !== null && !(Array.isArray(effectNames) && effectNames.length > 0 && effectNames.length <= 400 && effectNames.every(isName))) refuse("bad_argument", "effectNames isn't a list of 1 to 400 effect names.", "effectNames", 'Give the effects a player may share, like ["explosion_large", "magic_bolt"], or leave it out for any.');
283
+ const maximumPlaysPerSec = given.maximumPlaysPerSec ?? 20;
284
+ if (!isNumberIn(maximumPlaysPerSec, 1, 200)) refuse("bad_argument", "maximumPlaysPerSec isn't a number from 1 to 200.", "maximumPlaysPerSec", "Give how many effects a second one player may share: 20 by default.");
285
+ const beforePlay = given.beforePlay ?? null;
286
+ if (beforePlay !== null && typeof beforePlay !== "function") refuse("bad_argument", "beforePlay isn't a function.", "beforePlay", "Give (play, { playerId, roomState }) => false to refuse a play, or leave it out.");
287
+ const isAllowed = (play) => play !== null && (effectNames === null || effectNames.includes(play.effectName));
288
+ /** Rate caps a game server holds, by the room's kind state: in memory only, never in what the room saves. */
289
+ const serverCaps = new WeakMap();
290
+ const capOf = (kindState) => {
291
+ if (!serverCaps.has(kindState)) serverCaps.set(kindState, createRateCap(maximumPlaysPerSec));
292
+ return serverCaps.get(kindState);
293
+ };
294
+ const allMessage = (keptHexes, weather) => ({ all: { kept: keptHexes, weather } });
295
+
296
+ return defineKind({
297
+ name: "effects",
298
+ client(kindContext) {
299
+ const isOnHost = kindContext.authorityKind === "host";
300
+ const cap = createRateCap(maximumPlaysPerSec);
301
+ /** keptId -> { bytes, play, handle }: every effect that keeps playing in the room. */
302
+ const kept = new Map();
303
+ let weather = null;
304
+ let effects = null;
305
+ let knownPlayerIds = new Set(kindContext.playerIds());
306
+
307
+ /** Shows a play in this game, as far in as the room's clock says. Answers its handle, or null before attach. */
308
+ function show(play, entry) {
309
+ if (!effects) return null;
310
+ const start = () => {
311
+ const at = { positionM: play.positionM, seedNumber: play.seedNumber, startedAgoSec: Math.max(kindContext.serverTimeMs() - play.startedAtMs, 0) / 1000 };
312
+ for (const field of ["direction", "normal", "toPositionM", "scalePct", "strengthPct", "color", "surfaceKind"]) if (play[field] !== null) at[field] = play[field];
313
+ return effects.playShared(play.effectName, at);
314
+ };
315
+ if (effects.has(play.effectName)) return start();
316
+ // An effect this game hasn't loaded yet: fetched, then played from where the room's clock has it by then.
317
+ effects
318
+ .load([play.effectName])
319
+ .then(() => {
320
+ if (!entry) start();
321
+ else if (kept.get(play.keptId) === entry && !entry.handle) entry.handle = start();
322
+ })
323
+ .catch(() => {});
324
+ return null;
325
+ }
326
+ function keep(play, bytes) {
327
+ if (kept.has(play.keptId) || kept.size >= MAXIMUM_KEPT_COUNT) return null;
328
+ const entry = { bytes, play, handle: null };
329
+ kept.set(play.keptId, entry);
330
+ entry.handle = show(play, entry);
331
+ return entry;
332
+ }
333
+ function drop(keptId) {
334
+ const entry = kept.get(keptId);
335
+ if (!entry) return false;
336
+ entry.handle?.stop();
337
+ kept.delete(keptId);
338
+ return true;
339
+ }
340
+ function applyWeather(stated) {
341
+ const values = weatherSettings(stated);
342
+ const restated = weatherOf(values, "setWeather");
343
+ // The same weather again (everything kept, told to a newcomer) changes nothing.
344
+ if (Object.entries(restated).every(([statedName, value]) => weather?.[statedName] === value)) return;
345
+ weather = { ...(weather ?? {}), ...restated };
346
+ effects?.settings.set(values);
347
+ }
348
+ /** Whether a message of the room's own (everything kept, the weather) came from who's in charge. */
349
+ const isFromAuthority = (fromPlayerId) => (isOnHost ? fromPlayerId !== null && fromPlayerId === kindContext.authorityPlayerId() : fromPlayerId === null);
350
+
351
+ kindContext.onBytes((bytes, fromPlayerId) => {
352
+ // With a game server, the server held the sender to its rate; on the relay, each game does.
353
+ if (isOnHost && fromPlayerId !== null && !cap.take(fromPlayerId, kindContext.serverTimeMs())) return;
354
+ const stoppedId = decodeStop(bytes);
355
+ if (stoppedId) {
356
+ drop(stoppedId);
357
+ return;
358
+ }
359
+ const play = decodePlay(bytes);
360
+ if (!isAllowed(play)) return;
361
+ if (play.keptId) keep(play, bytes.slice());
362
+ else show(play, null);
363
+ });
364
+ kindContext.onMessage((kindMessage, fromPlayerId) => {
365
+ if (kindMessage === null || typeof kindMessage !== "object" || !isFromAuthority(fromPlayerId)) return;
366
+ if (kindMessage.weather) applyWeather(kindMessage.weather);
367
+ const all = kindMessage.all;
368
+ if (all === null || typeof all !== "object") return;
369
+ if (Array.isArray(all.kept)) {
370
+ for (const hex of all.kept.slice(0, MAXIMUM_KEPT_COUNT)) {
371
+ const bytes = fromHex(hex);
372
+ const play = bytes ? decodePlay(bytes) : null;
373
+ if (isAllowed(play) && play.keptId) keep(play, bytes);
374
+ }
375
+ }
376
+ if (all.weather) applyWeather(all.weather);
377
+ });
378
+ kindContext.onPlayersChanged((playerIds) => {
379
+ // On the relay the host tells a newcomer what keeps playing; the others already have it and let it pass.
380
+ const hasNewcomer = playerIds.some((playerId) => !knownPlayerIds.has(playerId));
381
+ for (const playerId of knownPlayerIds) if (!playerIds.includes(playerId)) cap.forget(playerId);
382
+ knownPlayerIds = new Set(playerIds);
383
+ if (isOnHost && hasNewcomer && kindContext.isAuthority() && (kept.size > 0 || weather)) kindContext.send(allMessage([...kept.values()].map((entry) => toHex(entry.bytes)), weather));
384
+ });
385
+ kindContext.onReset(() => {
386
+ for (const keptId of [...kept.keys()]) drop(keptId);
387
+ weather = null;
388
+ });
389
+
390
+ function share(effectName, at, isKept, callName) {
391
+ if (!effects) refuse("effects_not_attached", `${callName} was called before the game's effects were handed over.`, null, "Call attach(effects) first, with what createEffects answered.");
392
+ const play = playOf(effectName, at ?? {}, effectNames, callName);
393
+ play.seedNumber = newSeed();
394
+ play.startedAtMs = kindContext.serverTimeMs();
395
+ if (isKept) {
396
+ if (kept.size >= MAXIMUM_KEPT_COUNT) refuse("too_many_kept_effects", `A room keeps at most ${MAXIMUM_KEPT_COUNT} effects playing.`, null, "Stop one first (its handle's stop), or play this one in each game with effects.play.");
397
+ play.keptId = newKeptId();
398
+ }
399
+ const bytes = encodePlay(play);
400
+ // A spectator's own picture still shows it; nothing is sent.
401
+ if (!kindContext.isSpectator) kindContext.sendBytes(bytes);
402
+ return { play, bytes };
403
+ }
404
+
405
+ return {
406
+ /** Hands over the game's effects (createEffects' answer): from now on shared effects and the room's weather show in them. */
407
+ attach(effectsPiece) {
408
+ if (!effectsPiece || typeof effectsPiece.playShared !== "function") refuse("bad_argument", "attach takes the game's effects.", "effects", "Give what createEffects answered.");
409
+ effects = effectsPiece;
410
+ for (const entry of kept.values()) if (!entry.handle) entry.handle = show(entry.play, entry);
411
+ if (weather) effects.settings.set(weatherSettings(weather));
412
+ },
413
+ /** Plays an effect here and in every other player's game, the same in each. at: { positionM, direction, normal, toPositionM, scalePct, strengthPct, color, surfaceKind }. Answers this game's handle. */
414
+ play(effectName, at) {
415
+ const { play } = share(effectName, at, false, "play");
416
+ return show(play, null);
417
+ },
418
+ /** Starts an effect that keeps playing for everyone, a late joiner too, until its handle's stop(). */
419
+ start(effectName, at) {
420
+ const { play, bytes } = share(effectName, at, true, "start");
421
+ keep(play, bytes);
422
+ const { keptId } = play;
423
+ return {
424
+ keptId,
425
+ get isEnded() {
426
+ return !kept.has(keptId);
427
+ },
428
+ stop() {
429
+ if (drop(keptId) && !kindContext.isSpectator) kindContext.sendBytes(encodeStop(keptId));
430
+ },
431
+ };
432
+ },
433
+ /** On the relay, by the host: the weather for the whole room, only what changes, kept for late joiners. With a game server, set it there. Answers false where this game isn't in charge. */
434
+ setWeather(values) {
435
+ const stated = weatherOf(values, "setWeather");
436
+ if (!isOnHost || !kindContext.isAuthority()) return false;
437
+ applyWeather(stated);
438
+ kindContext.send({ weather: stated });
439
+ return true;
440
+ },
441
+ /** How many effects the room keeps playing now. */
442
+ get keptCount() {
443
+ return kept.size;
444
+ },
445
+ };
446
+ },
447
+ server: {
448
+ setup: () => ({ kept: {}, weather: null }),
449
+ onJoin(kindState, player, kindContext) {
450
+ const keptHexes = Object.values(kindState.kept);
451
+ if (keptHexes.length > 0 || kindState.weather) kindContext.send(player.id, allMessage(keptHexes, kindState.weather));
452
+ },
453
+ onBack(kindState, player, kindContext) {
454
+ const keptHexes = Object.values(kindState.kept);
455
+ if (keptHexes.length > 0 || kindState.weather) kindContext.send(player.id, allMessage(keptHexes, kindState.weather));
456
+ },
457
+ onLeave(kindState, player) {
458
+ capOf(kindState).forget(player.id);
459
+ },
460
+ onBytes(kindState, player, bytes, kindContext) {
461
+ const nowMs = kindContext.serverTimeMs();
462
+ if (!capOf(kindState).take(player.id, nowMs)) return;
463
+ const stoppedId = decodeStop(bytes);
464
+ if (stoppedId) {
465
+ if (!(stoppedId in kindState.kept)) return;
466
+ delete kindState.kept[stoppedId];
467
+ kindContext.broadcastBytes(bytes, { exceptPlayerId: player.id });
468
+ return;
469
+ }
470
+ const play = decodePlay(bytes);
471
+ if (!isAllowed(play)) return;
472
+ if (beforePlay && beforePlay(structuredClone(play), { playerId: player.id, roomState: kindContext.roomState }) === false) return;
473
+ // The room's clock is the server's: a start a player's game made up is put back on it.
474
+ let passed = bytes;
475
+ if (play.startedAtMs > nowMs + MAXIMUM_START_AHEAD_MS || play.startedAtMs < nowMs - MAXIMUM_START_AGO_MS) {
476
+ play.startedAtMs = nowMs;
477
+ passed = encodePlay(play);
478
+ }
479
+ if (play.keptId) {
480
+ if (play.keptId in kindState.kept || Object.keys(kindState.kept).length >= MAXIMUM_KEPT_COUNT) return;
481
+ kindState.kept[play.keptId] = toHex(passed);
482
+ }
483
+ kindContext.broadcastBytes(passed, { exceptPlayerId: player.id });
484
+ },
485
+ api: (kindState, kindContext) => {
486
+ const send = (effectName, at, isKept, callName) => {
487
+ const play = playOf(effectName, at ?? {}, effectNames, callName);
488
+ play.seedNumber = newSeed();
489
+ play.startedAtMs = kindContext.serverTimeMs();
490
+ if (isKept) {
491
+ if (Object.keys(kindState.kept).length >= MAXIMUM_KEPT_COUNT) refuse("too_many_kept_effects", `A room keeps at most ${MAXIMUM_KEPT_COUNT} effects playing.`, null, "Stop one first with stop(keptId).");
492
+ do play.keptId = newKeptId();
493
+ while (play.keptId in kindState.kept);
494
+ }
495
+ const bytes = encodePlay(play);
496
+ if (isKept) kindState.kept[play.keptId] = toHex(bytes);
497
+ kindContext.broadcastBytes(bytes);
498
+ return play.keptId;
499
+ };
500
+ return {
501
+ /** Plays an effect in every player's game: an explosion the server decided. */
502
+ play(effectName, at) {
503
+ send(effectName, at, false, "play");
504
+ },
505
+ /** Starts an effect that keeps playing for everyone, a late joiner too. Answers its keptId, for stop. */
506
+ start: (effectName, at) => send(effectName, at, true, "start"),
507
+ /** Stops an effect that keeps playing. Answers whether it was playing. */
508
+ stop(keptId) {
509
+ if (!(keptId in kindState.kept)) return false;
510
+ delete kindState.kept[keptId];
511
+ kindContext.broadcastBytes(encodeStop(keptId));
512
+ return true;
513
+ },
514
+ /** The weather for the whole room, only what changes: { rainPct, snowPct, fogPct, windSpeedMPerSec, windDirectionDeg, windGustPct }. Kept for late joiners. */
515
+ setWeather(values) {
516
+ const stated = weatherOf(values, "setWeather");
517
+ kindState.weather = { ...(kindState.weather ?? {}), ...stated };
518
+ kindContext.broadcast({ weather: stated });
519
+ },
520
+ /** How many effects the room keeps playing now. */
521
+ get keptCount() {
522
+ return Object.keys(kindState.kept).length;
523
+ },
524
+ };
525
+ },
526
+ },
527
+ });
528
+ }
package/tables.js ADDED
@@ -0,0 +1,109 @@
1
+ // Two small tables the shaders read, as float pictures. A particle carries only what's its own (where it was born,
2
+ // how fast, when, its seed) and two row numbers: its element's row (how every particle of that element moves and
3
+ // fades, in the look in use) and its play's row (where that play of the effect is now, its size and tint). So a
4
+ // slider in the workbench, or an effect that moves, changes every live particle by writing one row.
5
+ import * as THREE from "three";
6
+
7
+ /** Texels in an element's row: see ELEMENT_ROW in batches/sprites.js for what each holds. */
8
+ export const ELEMENT_ROW_TEXEL_COUNT = 16;
9
+ export const MAXIMUM_ELEMENT_ROW_COUNT = 1024;
10
+ /** Texels in a play's row: place and size, turn, tint and strength, spare. */
11
+ export const PLAY_ROW_TEXEL_COUNT = 4;
12
+ export const MAXIMUM_PLAY_ROW_COUNT = 512;
13
+
14
+ /** A table of rows of float texels, with rows handed out and taken back. */
15
+ export function createTable(texelCount, rowCount) {
16
+ const values = new Float32Array(texelCount * rowCount * 4);
17
+ const texture = new THREE.DataTexture(values, texelCount, rowCount, THREE.RGBAFormat, THREE.FloatType);
18
+ texture.minFilter = THREE.NearestFilter;
19
+ texture.magFilter = THREE.NearestFilter;
20
+ texture.generateMipmaps = false;
21
+ texture.needsUpdate = true;
22
+ const freeRows = [];
23
+ for (let row = rowCount - 1; row >= 0; row -= 1) freeRows.push(row);
24
+
25
+ return {
26
+ texture,
27
+ values,
28
+ get freeRowCount() {
29
+ return freeRows.length;
30
+ },
31
+ /** A free row's number, or -1 when every row is taken. */
32
+ takeRow() {
33
+ return freeRows.length > 0 ? freeRows.pop() : -1;
34
+ },
35
+ giveRow(row) {
36
+ if (row >= 0) freeRows.push(row);
37
+ },
38
+ /** Writes one texel of a row. */
39
+ write(row, texelIndex, first, second, third, fourth) {
40
+ const at = (row * texelCount + texelIndex) * 4;
41
+ values[at] = first;
42
+ values[at + 1] = second;
43
+ values[at + 2] = third;
44
+ values[at + 3] = fourth;
45
+ texture.needsUpdate = true;
46
+ },
47
+ dispose() {
48
+ texture.dispose();
49
+ },
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Ranges of slots handed out from a pool and taken back, joined up again when neighbours are free: each emitter
55
+ * takes one run of particles and keeps it until its last particle is gone.
56
+ */
57
+ export function createSlotPool(slotCount) {
58
+ // Free runs, kept in order of where they start.
59
+ let freeRuns = [{ start: 0, count: slotCount }];
60
+ let freeCount = slotCount;
61
+ return {
62
+ get slotCount() {
63
+ return slotCount;
64
+ },
65
+ get freeCount() {
66
+ return freeCount;
67
+ },
68
+ /** The start of a free run of `count` slots (the first that fits), or -1. */
69
+ take(count) {
70
+ for (let index = 0; index < freeRuns.length; index += 1) {
71
+ const run = freeRuns[index];
72
+ if (run.count < count) continue;
73
+ const start = run.start;
74
+ run.start += count;
75
+ run.count -= count;
76
+ if (run.count === 0) freeRuns.splice(index, 1);
77
+ freeCount -= count;
78
+ return start;
79
+ }
80
+ return -1;
81
+ },
82
+ /** The longest free run's length: the most one emitter can still take. */
83
+ longestFreeCount() {
84
+ let longest = 0;
85
+ for (const run of freeRuns) if (run.count > longest) longest = run.count;
86
+ return longest;
87
+ },
88
+ give(start, count) {
89
+ let index = 0;
90
+ while (index < freeRuns.length && freeRuns[index].start < start) index += 1;
91
+ freeRuns.splice(index, 0, { start, count });
92
+ freeCount += count;
93
+ const next = freeRuns[index + 1];
94
+ if (next && start + count === next.start) {
95
+ freeRuns[index].count += next.count;
96
+ freeRuns.splice(index + 1, 1);
97
+ }
98
+ const before = freeRuns[index - 1];
99
+ if (before && before.start + before.count === start) {
100
+ before.count += freeRuns[index].count;
101
+ freeRuns.splice(index, 1);
102
+ }
103
+ },
104
+ reset() {
105
+ freeRuns = [{ start: 0, count: slotCount }];
106
+ freeCount = slotCount;
107
+ },
108
+ };
109
+ }