@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
@@ -0,0 +1,222 @@
1
+ // The warp batch: effects that bend the picture (a shockwave's ripple, a bulge, the shimmer over heat), in one draw
2
+ // call. Warps are drawn last. Just before, the picture drawn so far is copied once; each warp then redraws its own
3
+ // patch of it, pulled out of place. So the copy is made only on frames with a warp alive, and only a warp's own
4
+ // pixels cost anything.
5
+ //
6
+ // The copy can't be made from a picture that's drawn with smoothed edges into a render target (the lighting effects'
7
+ // at high quality); the game then calls effects.drawWarps(camera) after its last draw, and they're laid on the screen.
8
+ import * as THREE from "three";
9
+ import { valueOverLife } from "../format.js";
10
+
11
+ const FLOATS_PER_WARP = 8;
12
+ const MAXIMUM_WARP_COUNT = 32;
13
+ const WARP_KIND_NUMBERS = { ripple: 0, pulse: 1, haze: 2 };
14
+ // three took the picture first and the texture second until r165.
15
+ const IS_TEXTURE_FIRST = Number(THREE.REVISION) >= 165;
16
+
17
+ const WARP_VERTEX = /* glsl */ `
18
+ attribute vec4 aPlace;
19
+ attribute vec4 aBend;
20
+ uniform float uIsReady;
21
+ varying vec2 vLocal;
22
+ varying vec4 vBend;
23
+ varying float vRadiusOnScreen;
24
+ void main() {
25
+ if (uIsReady < 0.5 || aBend.x <= 0.0) {
26
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
27
+ return;
28
+ }
29
+ vec4 mvPosition = viewMatrix * vec4(aPlace.xyz, 1.0);
30
+ mvPosition.xy += position.xy * aPlace.w * 1.15;
31
+ gl_Position = projectionMatrix * mvPosition;
32
+ vLocal = position.xy * 1.15;
33
+ vBend = aBend;
34
+ // How big the warp's radius is on screen, as a share of the picture's height.
35
+ vRadiusOnScreen = aPlace.w * projectionMatrix[1][1] * 0.5 / max(-mvPosition.z, 0.05);
36
+ }`;
37
+
38
+ const WARP_FRAGMENT = /* glsl */ `
39
+ uniform sampler2D uPicture;
40
+ uniform vec2 uPictureSizePx;
41
+ uniform float uTime;
42
+ varying vec2 vLocal;
43
+ varying vec4 vBend;
44
+ varying float vRadiusOnScreen;
45
+
46
+ float warpNoise(vec2 p) {
47
+ vec2 cell = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f);
48
+ vec4 corners = fract(sin(vec4(dot(cell, vec2(127.1, 311.7)), dot(cell + vec2(1.0, 0.0), vec2(127.1, 311.7)), dot(cell + vec2(0.0, 1.0), vec2(127.1, 311.7)), dot(cell + vec2(1.0, 1.0), vec2(127.1, 311.7)))) * 43758.5453);
49
+ return mix(mix(corners.x, corners.y, f.x), mix(corners.z, corners.w, f.x), f.y);
50
+ }
51
+
52
+ void main() {
53
+ float fromMiddle = length(vLocal);
54
+ vec2 outward = fromMiddle > 1e-4 ? vLocal / fromMiddle : vec2(0.0);
55
+ vec2 pull;
56
+ float amount;
57
+ if (vBend.z < 0.5) {
58
+ // A ripple: a ring at its radius that pushes the picture outward as it passes.
59
+ float across = (fromMiddle - 1.0) / max(vBend.y, 0.02);
60
+ amount = exp(-across * across * 4.0);
61
+ pull = -outward * amount * across * vBend.y * 1.2;
62
+ } else if (vBend.z < 1.5) {
63
+ // A pulse: the picture swells from its middle.
64
+ amount = clamp(1.0 - fromMiddle * fromMiddle, 0.0, 1.0);
65
+ pull = -outward * amount * fromMiddle * 0.3;
66
+ } else {
67
+ // A haze: the picture wavers, rising.
68
+ amount = clamp(1.0 - fromMiddle * fromMiddle, 0.0, 1.0);
69
+ vec2 drift = vLocal * 4.0 + vec2(vBend.w * 7.0, -uTime * 2.2);
70
+ pull = (vec2(warpNoise(drift), warpNoise(drift + 17.3)) - 0.5) * amount * 0.2;
71
+ }
72
+ vec2 onScreen = gl_FragCoord.xy / uPictureSizePx;
73
+ vec2 bent = onScreen + pull * vBend.x * vRadiusOnScreen * vec2(uPictureSizePx.y / uPictureSizePx.x, 1.0);
74
+ gl_FragColor = vec4(texture2D(uPicture, clamp(bent, 0.001, 0.999)).rgb, smoothstep(0.0, 0.06, amount));
75
+ }`;
76
+
77
+ const sizePx = new THREE.Vector2();
78
+ const place = new THREE.Vector3();
79
+
80
+ /** Makes the batch. Answers { mesh, add, update, drawOnScreen, liveCount, dispose }. */
81
+ export function createWarpBatch({ sharedUniforms }) {
82
+ const values = new Float32Array(MAXIMUM_WARP_COUNT * FLOATS_PER_WARP);
83
+ const buffer = new THREE.InstancedInterleavedBuffer(values, FLOATS_PER_WARP);
84
+ buffer.setUsage(THREE.DynamicDrawUsage);
85
+ const geometry = new THREE.InstancedBufferGeometry();
86
+ geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]), 3));
87
+ geometry.setIndex([0, 1, 2, 2, 1, 3]);
88
+ geometry.setAttribute("aPlace", new THREE.InterleavedBufferAttribute(buffer, 4, 0));
89
+ geometry.setAttribute("aBend", new THREE.InterleavedBufferAttribute(buffer, 4, 4));
90
+ geometry.instanceCount = 0;
91
+ let picture = new THREE.FramebufferTexture(1, 1);
92
+ const uniforms = { uPicture: { value: picture }, uPictureSizePx: { value: new THREE.Vector2(1, 1) }, uIsReady: { value: 0 }, uTime: sharedUniforms.uTime };
93
+ const material = new THREE.ShaderMaterial({ name: "zaisma_effect_warps", vertexShader: WARP_VERTEX, fragmentShader: WARP_FRAGMENT, uniforms, transparent: true, depthWrite: false, toneMapped: false, fog: false });
94
+ const mesh = new THREE.Mesh(geometry, material);
95
+ mesh.name = "zaisma_effect_warps";
96
+ mesh.frustumCulled = false;
97
+ mesh.renderOrder = 1000;
98
+ mesh.visible = false;
99
+
100
+ const warps = new Set();
101
+ let isDeferred = false;
102
+ let hasCopyFailed = false;
103
+
104
+ /** Copies the picture drawn so far, when it can be copied. Answers whether it was. */
105
+ function copyPicture(renderer) {
106
+ const target = renderer.getRenderTarget();
107
+ if (hasCopyFailed || (target && target.samples > 0)) return false;
108
+ if (target) sizePx.set(target.width, target.height);
109
+ else renderer.getDrawingBufferSize(sizePx);
110
+ const typeNumber = target ? target.texture.type : THREE.UnsignedByteType;
111
+ if (picture.image.width !== sizePx.x || picture.image.height !== sizePx.y || picture.type !== typeNumber) {
112
+ picture.dispose();
113
+ picture = new THREE.FramebufferTexture(sizePx.x, sizePx.y);
114
+ picture.type = typeNumber;
115
+ uniforms.uPicture.value = picture;
116
+ }
117
+ try {
118
+ if (IS_TEXTURE_FIRST) renderer.copyFramebufferToTexture(picture);
119
+ else renderer.copyFramebufferToTexture(new THREE.Vector2(0, 0), picture);
120
+ } catch (error) {
121
+ hasCopyFailed = true;
122
+ console.error("@zaisma/effects: the picture couldn't be copied for warps, so they're off.", error);
123
+ return false;
124
+ }
125
+ uniforms.uPictureSizePx.value.copy(sizePx);
126
+ return true;
127
+ }
128
+
129
+ mesh.onBeforeRender = (renderer) => {
130
+ const isCopied = copyPicture(renderer);
131
+ // A picture that can't be copied here waits for drawOnScreen.
132
+ isDeferred = !isCopied && !hasCopyFailed;
133
+ uniforms.uIsReady.value = isCopied ? 1 : 0;
134
+ material.uniformsNeedUpdate = true;
135
+ };
136
+
137
+ /**
138
+ * A warp: { play, warpKind, startSec, lifeSec, radiusKeys (m), strengthKeys (0 to 100), thicknessShare,
139
+ * loopDurationSec (0 when it plays once), seedNumber }.
140
+ */
141
+ function add(warp) {
142
+ if (warps.size >= MAXIMUM_WARP_COUNT) return null;
143
+ warps.add(warp);
144
+ return warp;
145
+ }
146
+
147
+ function update(nowSec, isEnabled) {
148
+ let count = 0;
149
+ for (const warp of warps) {
150
+ let sinceSec = nowSec - warp.startSec;
151
+ const isHeld = warp.loopDurationSec > 0;
152
+ if (warp.play.isEnded || (!isHeld && sinceSec >= warp.lifeSec)) {
153
+ warps.delete(warp);
154
+ continue;
155
+ }
156
+ if (sinceSec < 0 || !isEnabled) continue;
157
+ // In a looping effect a haze holds while it plays, and a ripple starts over with it.
158
+ let sharePct = (sinceSec / warp.lifeSec) * 100;
159
+ if (isHeld) {
160
+ if (warp.play.stopSec !== null && nowSec > warp.play.stopSec) continue;
161
+ sinceSec %= warp.loopDurationSec;
162
+ sharePct = warp.warpKind === "haze" ? 50 : (sinceSec / warp.lifeSec) * 100;
163
+ if (sharePct >= 100) continue;
164
+ }
165
+ place.copy(warp.play.place);
166
+ const at = count * FLOATS_PER_WARP;
167
+ values[at] = place.x;
168
+ values[at + 1] = place.y;
169
+ values[at + 2] = place.z;
170
+ values[at + 3] = valueOverLife(warp.radiusKeys, sharePct) * warp.play.scaleShare;
171
+ values[at + 4] = (valueOverLife(warp.strengthKeys, sharePct) / 100) * warp.play.strengthShare;
172
+ values[at + 5] = warp.thicknessShare;
173
+ values[at + 6] = WARP_KIND_NUMBERS[warp.warpKind];
174
+ values[at + 7] = warp.seedNumber;
175
+ count += 1;
176
+ }
177
+ geometry.instanceCount = count;
178
+ mesh.visible = count > 0;
179
+ if (count > 0) {
180
+ buffer.clearUpdateRanges();
181
+ buffer.addUpdateRange(0, count * FLOATS_PER_WARP);
182
+ buffer.needsUpdate = true;
183
+ }
184
+ }
185
+
186
+ /** Lays the warps on the screen after the game's last draw, when they couldn't be drawn with the scene. */
187
+ function drawOnScreen(renderer, camera) {
188
+ if (!isDeferred || !mesh.visible) return;
189
+ const parent = mesh.parent;
190
+ const earlierAutoClear = renderer.autoClear;
191
+ const earlierCallback = mesh.onBeforeRender;
192
+ renderer.autoClear = false;
193
+ mesh.onBeforeRender = () => {};
194
+ if (copyPicture(renderer)) {
195
+ uniforms.uIsReady.value = 1;
196
+ material.depthTest = false;
197
+ const alone = new THREE.Scene();
198
+ alone.add(mesh);
199
+ renderer.render(alone, camera);
200
+ parent?.add(mesh);
201
+ material.depthTest = true;
202
+ }
203
+ mesh.onBeforeRender = earlierCallback;
204
+ renderer.autoClear = earlierAutoClear;
205
+ isDeferred = false;
206
+ }
207
+
208
+ return {
209
+ mesh,
210
+ add,
211
+ update,
212
+ drawOnScreen,
213
+ get liveCount() {
214
+ return warps.size;
215
+ },
216
+ dispose() {
217
+ geometry.dispose();
218
+ material.dispose();
219
+ picture.dispose();
220
+ },
221
+ };
222
+ }
package/budget.js ADDED
@@ -0,0 +1,115 @@
1
+ // What a device may draw, and who gives way when that's spent. Three things hold the frame rate: a fixed count of
2
+ // particles per quality level (never passed: an emitter takes its run of particles from a pool, and a pool gives
3
+ // only what it has), a share of every effect's particles drawn at lower quality (some of the same ones, so an
4
+ // effect keeps its shape), and a guard on how much of the screen see-through particles cover, which is what smoke
5
+ // really costs a phone. No engine here.
6
+
7
+ export const QUALITY_ORDER = ["low", "medium", "high"];
8
+
9
+ /**
10
+ * What each quality level draws. keptPct is the share of an effect's particles drawn; fillScreenCount is how many
11
+ * screens' worth of see-through particles may be drawn over each other before the guard thins them.
12
+ */
13
+ export const QUALITY_BUDGETS = {
14
+ low: { particleCount: 2000, markCount: 64, debrisCount: 60, flashLightCount: 0, hasWarps: false, hasRainShelter: false, hasSunShadows: false, keptPct: 45, fillScreenCount: 2.5, atlasSizePx: 1024 },
15
+ medium: { particleCount: 6000, markCount: 256, debrisCount: 150, flashLightCount: 2, hasWarps: true, hasRainShelter: true, hasSunShadows: false, keptPct: 75, fillScreenCount: 4, atlasSizePx: 1024 },
16
+ high: { particleCount: 20000, markCount: 512, debrisCount: 300, flashLightCount: 4, hasWarps: true, hasRainShelter: true, hasSunShadows: true, keptPct: 100, fillScreenCount: 8, atlasSizePx: 2048 },
17
+ };
18
+
19
+ /** The share of the particle budget solid chunks may take: each is up to sixty corners, where a sprite is four. */
20
+ export const CHUNK_BUDGET_SHARE = 0.3;
21
+ /** The share of what's free that one emitter may take, by its effect's importance: the rest is kept for what comes next. */
22
+ export const IMPORTANCE_FREE_SHARE = { low: 0.4, normal: 0.7, high: 1 };
23
+ /** Beyond this far from the camera an effect draws fewer particles, down to a quarter. */
24
+ export const FULL_COUNT_DISTANCE_M = 60;
25
+ const MINIMUM_DISTANCE_SHARE = 0.25;
26
+ const MINIMUM_FILL_SHARE = 0.25;
27
+
28
+ /** How many particles a level's budget holds, with the game's own scale on it. */
29
+ export function particleBudget(qualityLevel, particleBudgetPct) {
30
+ return Math.max(Math.round((QUALITY_BUDGETS[qualityLevel].particleCount * particleBudgetPct) / 100), 16);
31
+ }
32
+
33
+ /**
34
+ * How many particles an emitter gets and what share of its particles it draws. wanted: how many it would hold alive
35
+ * at once drawing every particle. Answers { slotCount, keptShare }; slotCount 0 means it draws nothing now.
36
+ * A burst of three or fewer with no flow is never thinned: one missing of three is seen.
37
+ */
38
+ export function planEmitter({ wantedCount, isNeverThinned, qualityLevel, importance, distanceM, freeCount, longestFreeCount, lookCountShare, fillShare }) {
39
+ let keptShare = 1;
40
+ if (!isNeverThinned) {
41
+ keptShare = Math.min(lookCountShare, 1) * (QUALITY_BUDGETS[qualityLevel].keptPct / 100);
42
+ if (distanceM > FULL_COUNT_DISTANCE_M) keptShare *= Math.max(FULL_COUNT_DISTANCE_M / distanceM, MINIMUM_DISTANCE_SHARE);
43
+ keptShare *= fillShare;
44
+ }
45
+ // A little room over the count, since lives differ: the ring takes the oldest when it's short.
46
+ let slotCount = Math.ceil(wantedCount * keptShare * 1.15) + 2;
47
+ const allowedCount = Math.min(Math.floor(freeCount * IMPORTANCE_FREE_SHARE[importance]), longestFreeCount);
48
+ if (slotCount > allowedCount) {
49
+ if (allowedCount < 1) return { slotCount: 0, keptShare: 0 };
50
+ if (!isNeverThinned) keptShare *= allowedCount / slotCount;
51
+ slotCount = allowedCount;
52
+ }
53
+ return { slotCount, keptShare };
54
+ }
55
+
56
+ /**
57
+ * The fill guard. Each frame it's told how many screens the see-through particles cover; while that's over the
58
+ * level's limit, new particles of big see-through effects are drawn thinner, and it lets go as the screen clears.
59
+ */
60
+ export function createFillGuard() {
61
+ let fillShare = 1;
62
+ return {
63
+ get fillShare() {
64
+ return fillShare;
65
+ },
66
+ /** Answers the share now. */
67
+ count(coveredScreenCount, qualityLevel) {
68
+ const limit = QUALITY_BUDGETS[qualityLevel].fillScreenCount;
69
+ if (coveredScreenCount > limit) fillShare = Math.max(fillShare * 0.94, MINIMUM_FILL_SHARE);
70
+ else if (coveredScreenCount < limit * 0.7) fillShare = Math.min(fillShare * 1.02, 1);
71
+ return fillShare;
72
+ },
73
+ };
74
+ }
75
+
76
+ // The lighting piece's rule, so a game without it steps down the same way: frames averaging slower than this over
77
+ // the window step quality down one level. A gap longer than the maximum is a hidden tab or a pause, not a slow frame.
78
+ const SLOW_FRAME_DURATION_MS = 40;
79
+ const SLOW_FRAME_WINDOW_COUNT = 90;
80
+ const MAXIMUM_COUNTED_FRAME_DURATION_MS = 500;
81
+
82
+ /** Watches frames; count(nowMs) answers true when quality should step down a level. */
83
+ export function createFrameWatcher() {
84
+ let lastFrameMs = null;
85
+ let totalMs = 0;
86
+ let frameCount = 0;
87
+ return {
88
+ count(nowMs) {
89
+ if (lastFrameMs !== null) {
90
+ const durationMs = nowMs - lastFrameMs;
91
+ if (durationMs > 0 && durationMs < MAXIMUM_COUNTED_FRAME_DURATION_MS) {
92
+ totalMs += durationMs;
93
+ frameCount += 1;
94
+ }
95
+ }
96
+ lastFrameMs = nowMs;
97
+ if (frameCount < SLOW_FRAME_WINDOW_COUNT) return false;
98
+ const averageMs = totalMs / frameCount;
99
+ totalMs = 0;
100
+ frameCount = 0;
101
+ return averageMs > SLOW_FRAME_DURATION_MS;
102
+ },
103
+ };
104
+ }
105
+
106
+ /** Whether this device is a phone or a tablet: a touch screen with no mouse. False where there's no window. */
107
+ export function isTouchDevice() {
108
+ if (typeof matchMedia !== "function") return false;
109
+ return matchMedia("(pointer: coarse)").matches && !matchMedia("(any-pointer: fine)").matches;
110
+ }
111
+
112
+ /** The quality level auto starts at on this device: medium on phones and tablets, high elsewhere. */
113
+ export function startingQualityLevel() {
114
+ return isTouchDevice() ? "medium" : "high";
115
+ }
package/debris.js ADDED
@@ -0,0 +1,173 @@
1
+ // Bouncing debris: the few chunks that can't fly by a formula, because they hit the level. Each is stepped here in
2
+ // small fixed steps (gravity, then a ray along its way to see what it meets), bounces with what its element says it
3
+ // keeps, slides to rest, and is written to the chunk batch where it is each frame. There are never many (the
4
+ // quality level's count), and one at rest costs nothing.
5
+ //
6
+ // A chunk's throw follows from its play's seed like any particle, so every player sees the same pieces fly; where
7
+ // each comes to rest follows from each player's own level, which is the same level.
8
+ import { hashNumbers, randomFrom } from "./format.js";
9
+ import { makeParticle } from "./emit.js";
10
+ import { GRAVITY_M_PER_SEC2 } from "./motion.js";
11
+
12
+ const STEP_SEC = 1 / 60;
13
+ const MAXIMUM_STEPS_PER_FRAME = 4;
14
+ const REST_SPEED_M_PER_SEC = 0.35;
15
+
16
+ const born = { x: 0, y: 0, z: 0, velocityX: 0, velocityY: 0, velocityZ: 0, lifeSec: 0, seedNumber: 0 };
17
+
18
+ /**
19
+ * Makes the debris. chunks(): the chunk batch in use. findSurface(fromX, fromY, fromZ, wayX, wayY, wayZ, distanceM, into)
20
+ * answers whether a ray meets the level, writing { x, y, z, normalX, normalY, normalZ } into `into`.
21
+ * onLanded(chunk) is called the first time a chunk lands. Answers { setCapacity, throwChunks, update, liveCount,
22
+ * capacity }.
23
+ */
24
+ export function createDebris({ chunks, findSurface, onLanded }) {
25
+ let slab = null;
26
+ let capacity = 0;
27
+ /** Every place in the slab, a chunk or null. */
28
+ let held = [];
29
+ let nextOffset = 0;
30
+ let liveCount = 0;
31
+ let leftoverSec = 0;
32
+ const met = { x: 0, y: 0, z: 0, normalX: 0, normalY: 1, normalZ: 0 };
33
+
34
+ function setCapacity(newCapacity) {
35
+ if (slab) chunks().giveSlab(slab);
36
+ for (const chunk of held) if (chunk) chunk.play.debrisCount -= 1;
37
+ capacity = newCapacity;
38
+ slab = capacity > 0 ? chunks().takeSlab(capacity, null) : null;
39
+ if (slab) capacity = slab.capacity;
40
+ else capacity = 0;
41
+ held = new Array(capacity).fill(null);
42
+ nextOffset = 0;
43
+ liveCount = 0;
44
+ }
45
+
46
+ /**
47
+ * Throws an element's chunks. thrower: { emitter (as emit.js takes it, its speed and spread), count, play,
48
+ * playSeedNumber, startSec, gravityMPerSec2, bounceShare, gripShare, sizeM, sizeVariationShare, lifeSec,
49
+ * spinRadPerSec, elementRows (one per colour), nowSec }. Answers how many were thrown.
50
+ */
51
+ function throwChunks(thrower) {
52
+ if (capacity === 0) return 0;
53
+ const { play, emitter } = thrower;
54
+ let thrownCount = 0;
55
+ for (let number = 0; number < thrower.count; number += 1) {
56
+ makeParticle(emitter, thrower.playSeedNumber, number, born);
57
+ const next = randomFrom(hashNumbers(thrower.playSeedNumber, emitter.elementIndex, number, 11));
58
+ const offset = nextOffset;
59
+ nextOffset = (nextOffset + 1) % capacity;
60
+ const scale = play.scaleShare;
61
+ // The play's turn takes its own space (+y its direction) to the world's.
62
+ const place = play.turnPoint(born.x * scale, born.y * scale, born.z * scale);
63
+ const x = play.place.x + place.x;
64
+ const y = play.place.y + place.y;
65
+ const z = play.place.z + place.z;
66
+ const velocity = play.turnPoint(born.velocityX * scale, born.velocityY * scale, born.velocityZ * scale);
67
+ const chunk = {
68
+ offset,
69
+ play,
70
+ x,
71
+ y,
72
+ z,
73
+ velocityX: velocity.x,
74
+ velocityY: velocity.y,
75
+ velocityZ: velocity.z,
76
+ angleRad: next() * Math.PI * 2,
77
+ spinRadPerSec: thrower.spinRadPerSec * (0.5 + next()),
78
+ halfSizeM: thrower.sizeM * scale * 0.5,
79
+ birthSec: thrower.startSec,
80
+ lifeSec: thrower.lifeSec * (0.75 + next() * 0.5),
81
+ seedNumber: born.seedNumber,
82
+ elementRow: thrower.elementRows[Math.floor(next() * thrower.elementRows.length) % thrower.elementRows.length],
83
+ gravityMPerSec2: thrower.gravityMPerSec2,
84
+ bounceShare: thrower.bounceShare,
85
+ gripShare: thrower.gripShare,
86
+ bounceEffectName: thrower.bounceEffectName,
87
+ isResting: false,
88
+ hasLanded: false,
89
+ isWritten: false,
90
+ };
91
+ if (held[offset]) held[offset].play.debrisCount -= 1;
92
+ held[offset] = chunk;
93
+ play.debrisCount += 1;
94
+ thrownCount += 1;
95
+ }
96
+ return thrownCount;
97
+ }
98
+
99
+ function step(chunk) {
100
+ chunk.velocityY -= chunk.gravityMPerSec2 * STEP_SEC;
101
+ const moveX = chunk.velocityX * STEP_SEC;
102
+ const moveY = chunk.velocityY * STEP_SEC;
103
+ const moveZ = chunk.velocityZ * STEP_SEC;
104
+ const distanceM = Math.hypot(moveX, moveY, moveZ);
105
+ if (distanceM < 1e-6) return;
106
+ const reachM = distanceM + chunk.halfSizeM;
107
+ if (!findSurface(chunk.x, chunk.y, chunk.z, moveX / distanceM, moveY / distanceM, moveZ / distanceM, reachM, met)) {
108
+ chunk.x += moveX;
109
+ chunk.y += moveY;
110
+ chunk.z += moveZ;
111
+ chunk.angleRad += chunk.spinRadPerSec * STEP_SEC;
112
+ return;
113
+ }
114
+ // It met the level: it sits on the surface, loses the speed into it but for its bounce, and some along it.
115
+ chunk.x = met.x + met.normalX * chunk.halfSizeM;
116
+ chunk.y = met.y + met.normalY * chunk.halfSizeM;
117
+ chunk.z = met.z + met.normalZ * chunk.halfSizeM;
118
+ const intoSpeed = chunk.velocityX * met.normalX + chunk.velocityY * met.normalY + chunk.velocityZ * met.normalZ;
119
+ if (intoSpeed < 0) {
120
+ const alongX = chunk.velocityX - intoSpeed * met.normalX;
121
+ const alongY = chunk.velocityY - intoSpeed * met.normalY;
122
+ const alongZ = chunk.velocityZ - intoSpeed * met.normalZ;
123
+ const kept = 1 - chunk.gripShare * 0.6;
124
+ chunk.velocityX = alongX * kept - intoSpeed * chunk.bounceShare * met.normalX;
125
+ chunk.velocityY = alongY * kept - intoSpeed * chunk.bounceShare * met.normalY;
126
+ chunk.velocityZ = alongZ * kept - intoSpeed * chunk.bounceShare * met.normalZ;
127
+ chunk.spinRadPerSec *= 0.6;
128
+ }
129
+ if (!chunk.hasLanded) {
130
+ chunk.hasLanded = true;
131
+ onLanded(chunk, met);
132
+ }
133
+ // Slow on a surface it can lie on: it stays there.
134
+ if (Math.hypot(chunk.velocityX, chunk.velocityY, chunk.velocityZ) < REST_SPEED_M_PER_SEC && met.normalY > 0.5) chunk.isResting = true;
135
+ }
136
+
137
+ /** Steps what's moving and writes it. toBatchSec turns a time on the effects' clock into the batch's own. */
138
+ function update(nowSec, frameSec, toBatchSec) {
139
+ liveCount = 0;
140
+ if (capacity === 0) return;
141
+ leftoverSec = Math.min(leftoverSec + frameSec, STEP_SEC * MAXIMUM_STEPS_PER_FRAME);
142
+ const stepCount = Math.floor(leftoverSec / STEP_SEC);
143
+ leftoverSec -= stepCount * STEP_SEC;
144
+ const batch = chunks();
145
+ for (let offset = 0; offset < capacity; offset += 1) {
146
+ const chunk = held[offset];
147
+ if (!chunk) continue;
148
+ if (nowSec - chunk.birthSec >= chunk.lifeSec || chunk.play.isEnded) {
149
+ held[offset] = null;
150
+ chunk.play.debrisCount -= 1;
151
+ batch.rewrite(slab, offset, 0, 0, 0, -1e9, 1, 0, 0, 0, 0);
152
+ continue;
153
+ }
154
+ liveCount += 1;
155
+ if (chunk.isResting && chunk.isWritten) continue;
156
+ if (!chunk.isResting && nowSec >= chunk.birthSec) for (let count = 0; count < stepCount && !chunk.isResting; count += 1) step(chunk);
157
+ batch.rewrite(slab, offset, chunk.x, chunk.y, chunk.z, toBatchSec(chunk.birthSec), chunk.lifeSec, chunk.seedNumber, chunk.elementRow, chunk.play.row, chunk.angleRad);
158
+ chunk.isWritten = true;
159
+ }
160
+ }
161
+
162
+ return {
163
+ setCapacity,
164
+ throwChunks,
165
+ update,
166
+ get liveCount() {
167
+ return liveCount;
168
+ },
169
+ get capacity() {
170
+ return capacity;
171
+ },
172
+ };
173
+ }
package/emit.js ADDED
@@ -0,0 +1,143 @@
1
+ // Which particles an emitter has given off by a moment, and what each is like as it's born. Everything follows
2
+ // from the play's seed and a particle's number: no state, no clock, no random numbers of the device's own. So the
3
+ // same play gives the same particles on every player's screen whatever its frame rate, a device that draws fewer
4
+ // draws some of the same ones, and a player who joins late works out exactly the ones still alive. No engine here.
5
+ import { hashNumbers, randomFrom } from "./format.js";
6
+
7
+ const TWO_PI = Math.PI * 2;
8
+
9
+ /**
10
+ * How many particles one run of an emitter gives off: its burst and what its flow adds while it emits.
11
+ * emitter: { burstCount, perSec, emitDurationSec, loopDurationSec (0 when the effect plays once) }.
12
+ */
13
+ export function particleCountPerRun(emitter) {
14
+ const flowSec = emitter.loopDurationSec > 0 ? Math.min(emitter.emitDurationSec, emitter.loopDurationSec) : emitter.emitDurationSec;
15
+ return emitter.burstCount + Math.floor(flowSec * emitter.perSec);
16
+ }
17
+
18
+ /** How many particles the emitter has given off by a time since it started, in seconds. */
19
+ export function bornCountAt(emitter, sinceStartSec) {
20
+ if (sinceStartSec < 0) return 0;
21
+ if (emitter.loopDurationSec > 0) {
22
+ const runCount = Math.floor(sinceStartSec / emitter.loopDurationSec);
23
+ const intoRunSec = sinceStartSec - runCount * emitter.loopDurationSec;
24
+ return runCount * particleCountPerRun(emitter) + emitter.burstCount + Math.floor(Math.min(intoRunSec, emitter.emitDurationSec, emitter.loopDurationSec) * emitter.perSec);
25
+ }
26
+ return emitter.burstCount + Math.floor(Math.min(sinceStartSec, emitter.emitDurationSec) * emitter.perSec);
27
+ }
28
+
29
+ /** When a particle is born, by its number, in seconds since the emitter started. */
30
+ export function birthSecOf(emitter, particleNumber) {
31
+ let startSec = 0;
32
+ let numberInRun = particleNumber;
33
+ if (emitter.loopDurationSec > 0) {
34
+ const perRun = particleCountPerRun(emitter);
35
+ const runCount = Math.floor(particleNumber / perRun);
36
+ startSec = runCount * emitter.loopDurationSec;
37
+ numberInRun = particleNumber - runCount * perRun;
38
+ }
39
+ return numberInRun < emitter.burstCount ? startSec : startSec + (numberInRun - emitter.burstCount + 1) / emitter.perSec;
40
+ }
41
+
42
+ /** Whether a particle is one of the share a device draws: a lower share draws some of the same particles. */
43
+ export function isParticleKept(playSeedNumber, elementIndex, particleNumber, keptShare) {
44
+ return keptShare >= 1 || hashNumbers(playSeedNumber, elementIndex, particleNumber, 7) / 4294967296 < keptShare;
45
+ }
46
+
47
+ function randomDirection(next, into) {
48
+ const height = next() * 2 - 1;
49
+ const angle = next() * TWO_PI;
50
+ const flat = Math.sqrt(1 - height * height);
51
+ into.x = Math.cos(angle) * flat;
52
+ into.y = height;
53
+ into.z = Math.sin(angle) * flat;
54
+ }
55
+
56
+ const offset = { x: 0, y: 0, z: 0 };
57
+ const way = { x: 0, y: 0, z: 0 };
58
+
59
+ /**
60
+ * One particle as it's born, in the effect's own space (its direction is +y, its place the origin), written into
61
+ * `into`: { x, y, z, velocityX, velocityY, velocityZ, lifeSec, seedNumber }. emitter adds: { elementIndex, fromKind,
62
+ * fromRadiusM, fromSizeM, isFromEdge, directionKind, spreadRad, speedMPerSec, speedVariationShare, lifeSec,
63
+ * lifeVariationShare }.
64
+ */
65
+ export function makeParticle(emitter, playSeedNumber, particleNumber, into) {
66
+ const next = randomFrom(hashNumbers(playSeedNumber, emitter.elementIndex, particleNumber));
67
+ offset.x = 0;
68
+ offset.y = 0;
69
+ offset.z = 0;
70
+ let hasOffset = false;
71
+ if (emitter.fromKind === "sphere" && emitter.fromRadiusM > 0) {
72
+ randomDirection(next, offset);
73
+ const far = emitter.fromRadiusM * (emitter.isFromEdge ? 1 : Math.cbrt(next()));
74
+ offset.x *= far;
75
+ offset.y *= far;
76
+ offset.z *= far;
77
+ hasOffset = true;
78
+ } else if (emitter.fromKind === "ring" && emitter.fromRadiusM > 0) {
79
+ const angle = next() * TWO_PI;
80
+ const far = emitter.fromRadiusM * (emitter.isFromEdge ? 1 : Math.sqrt(next()));
81
+ offset.x = Math.cos(angle) * far;
82
+ offset.z = Math.sin(angle) * far;
83
+ hasOffset = true;
84
+ } else if (emitter.fromKind === "box") {
85
+ offset.x = (next() - 0.5) * emitter.fromSizeM[0];
86
+ offset.y = (next() - 0.5) * emitter.fromSizeM[1];
87
+ offset.z = (next() - 0.5) * emitter.fromSizeM[2];
88
+ hasOffset = true;
89
+ } else if (emitter.fromKind === "line") {
90
+ offset.y = (next() * 2 - 1) * emitter.fromRadiusM;
91
+ }
92
+
93
+ if (emitter.directionKind === "along" || emitter.directionKind === "up") {
94
+ way.x = 0;
95
+ way.y = 1;
96
+ way.z = 0;
97
+ } else if (emitter.directionKind === "random" || !hasOffset || emitter.fromKind === "box") {
98
+ // From nowhere in particular, outward and inward have no meaning: it sets off any way.
99
+ randomDirection(next, way);
100
+ } else {
101
+ const far = Math.hypot(offset.x, offset.y, offset.z) || 1;
102
+ const sign = emitter.directionKind === "inward" ? -1 : 1;
103
+ way.x = (offset.x / far) * sign;
104
+ way.y = (offset.y / far) * sign;
105
+ way.z = (offset.z / far) * sign;
106
+ }
107
+ if (emitter.spreadRad > 0 && (emitter.directionKind === "along" || emitter.directionKind === "up" || hasOffset)) {
108
+ // Anywhere inside a cone round its direction, evenly over the cone's cap.
109
+ const cosAway = 1 - next() * (1 - Math.cos(emitter.spreadRad));
110
+ const sinAway = Math.sqrt(Math.max(1 - cosAway * cosAway, 0));
111
+ const round = next() * TWO_PI;
112
+ // Two directions square to the way.
113
+ const isSteep = Math.abs(way.y) > 0.99;
114
+ let sideX = isSteep ? 1 : -way.z;
115
+ let sideY = 0;
116
+ let sideZ = isSteep ? 0 : way.x;
117
+ const sideLength = Math.hypot(sideX, sideY, sideZ);
118
+ sideX /= sideLength;
119
+ sideZ /= sideLength;
120
+ const otherX = way.y * sideZ - way.z * sideY;
121
+ const otherY = way.z * sideX - way.x * sideZ;
122
+ const otherZ = way.x * sideY - way.y * sideX;
123
+ const cosRound = Math.cos(round) * sinAway;
124
+ const sinRound = Math.sin(round) * sinAway;
125
+ const x = way.x * cosAway + sideX * cosRound + otherX * sinRound;
126
+ const y = way.y * cosAway + sideY * cosRound + otherY * sinRound;
127
+ const z = way.z * cosAway + sideZ * cosRound + otherZ * sinRound;
128
+ way.x = x;
129
+ way.y = y;
130
+ way.z = z;
131
+ }
132
+
133
+ const speed = emitter.speedMPerSec * (1 + emitter.speedVariationShare * (next() * 2 - 1));
134
+ into.x = offset.x;
135
+ into.y = offset.y;
136
+ into.z = offset.z;
137
+ into.velocityX = way.x * speed;
138
+ into.velocityY = way.y * speed;
139
+ into.velocityZ = way.z * speed;
140
+ into.lifeSec = emitter.lifeSec * (1 + emitter.lifeVariationShare * (next() * 2 - 1));
141
+ into.seedNumber = next();
142
+ return into;
143
+ }