@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,294 @@
1
+ // The chunk batch: every solid particle, in one draw call. A chunk is a little low-poly solid (a tetrahedron, a
2
+ // cube, a shard) that flies by the same formulas as a sprite, tumbles, and catches the light on flat faces. The
3
+ // faceted look draws every material this way; every look draws stone, wood, metal and glass this way; and the
4
+ // bouncing debris (debris.js) writes its chunks here each frame.
5
+ //
6
+ // All the shapes share one draw: each instance has 60 corners, and reads its shape's corners from a small table by
7
+ // its corner's number, so a tetrahedron and an icosahedron are the same geometry to the graphics chip.
8
+ import * as THREE from "three";
9
+ import { CHUNK_SHAPE_NAMES } from "../looks.js";
10
+ import { MOTION_GLSL } from "../motion.js";
11
+ import { createSlotPool } from "../tables.js";
12
+ import { ELEMENT_ROW } from "./sprites.js";
13
+ import { SHARED_VERTEX_GLSL, fogUniforms } from "./shared.js";
14
+
15
+ const CORNER_COUNT = 60;
16
+ const FLOATS_PER_CHUNK = 12;
17
+
18
+ function makeShapeTable() {
19
+ const solids = {
20
+ tetra: new THREE.TetrahedronGeometry(0.5),
21
+ octa: new THREE.OctahedronGeometry(0.5),
22
+ icosa: new THREE.IcosahedronGeometry(0.5),
23
+ cube: new THREE.BoxGeometry(0.72, 0.72, 0.72),
24
+ shard: new THREE.TetrahedronGeometry(0.5).scale(0.3, 1.1, 0.3),
25
+ plate: new THREE.BoxGeometry(1, 0.1, 0.66),
26
+ };
27
+ const values = new Float32Array(CORNER_COUNT * CHUNK_SHAPE_NAMES.length * 2 * 4);
28
+ const first = new THREE.Vector3();
29
+ const second = new THREE.Vector3();
30
+ const third = new THREE.Vector3();
31
+ const normal = new THREE.Vector3();
32
+ CHUNK_SHAPE_NAMES.forEach((shapeName, shapeIndex) => {
33
+ const flat = solids[shapeName].index ? solids[shapeName].toNonIndexed() : solids[shapeName];
34
+ const positions = flat.getAttribute("position");
35
+ for (let corner = 0; corner < Math.min(positions.count, CORNER_COUNT); corner += 3) {
36
+ first.fromBufferAttribute(positions, corner);
37
+ second.fromBufferAttribute(positions, corner + 1);
38
+ third.fromBufferAttribute(positions, corner + 2);
39
+ normal.subVectors(second, first).cross(third.clone().sub(first)).normalize();
40
+ [first, second, third].forEach((point, offset) => {
41
+ const placeAt = (shapeIndex * 2 * CORNER_COUNT + corner + offset) * 4;
42
+ values.set([point.x, point.y, point.z, 1], placeAt);
43
+ values.set([normal.x, normal.y, normal.z, 0], placeAt + CORNER_COUNT * 4);
44
+ });
45
+ }
46
+ solids[shapeName].dispose();
47
+ });
48
+ const texture = new THREE.DataTexture(values, CORNER_COUNT, CHUNK_SHAPE_NAMES.length * 2, THREE.RGBAFormat, THREE.FloatType);
49
+ texture.minFilter = THREE.NearestFilter;
50
+ texture.magFilter = THREE.NearestFilter;
51
+ texture.needsUpdate = true;
52
+ return texture;
53
+ }
54
+
55
+ const CHUNK_VERTEX = /* glsl */ `
56
+ attribute vec4 aBirth;
57
+ attribute vec4 aVelocity;
58
+ attribute vec4 aSeed;
59
+ uniform highp sampler2D uChunkShapes;
60
+ ${SHARED_VERTEX_GLSL}
61
+ ${MOTION_GLSL}
62
+ varying vec3 vColor;
63
+ #include <fog_pars_vertex>
64
+
65
+ vec3 zaismaTurnRound(vec3 axis, float angle, vec3 point) {
66
+ float cosAngle = cos(angle);
67
+ return point * cosAngle + cross(axis, point) * sin(angle) + axis * dot(axis, point) * (1.0 - cosAngle);
68
+ }
69
+
70
+ void main() {
71
+ int row = int(aSeed.y + 0.5);
72
+ int playRow = int(aSeed.z + 0.5);
73
+ float seed = aSeed.x;
74
+ float age = uTime - aBirth.w;
75
+ float life = aVelocity.w;
76
+ float lifeShare = age / life;
77
+ if (age < 0.0 || lifeShare >= 1.0) {
78
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
79
+ return;
80
+ }
81
+ // A shape with fewer corners than the batch's sixty leaves the rest out, before any of the work below.
82
+ vec4 style = zaismaElement(row, ${ELEMENT_ROW.style});
83
+ int shape = int(style.w + 0.5);
84
+ vec4 cornerHeld = texelFetch(uChunkShapes, ivec2(gl_VertexID, shape * 2), 0);
85
+ if (cornerHeld.w < 0.5) {
86
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
87
+ return;
88
+ }
89
+ vec4 motionA = zaismaElement(row, ${ELEMENT_ROW.motionA});
90
+ vec4 motionB = zaismaElement(row, ${ELEMENT_ROW.motionB});
91
+ vec4 facing = zaismaElement(row, ${ELEMENT_ROW.facing});
92
+ vec4 playPlace = zaismaPlay(playRow, 0);
93
+ vec4 playTurn = zaismaPlay(playRow, 1);
94
+ vec4 playTint = zaismaPlay(playRow, 2);
95
+
96
+ bool isAttached = motionB.w > 0.5;
97
+ vec3 center = isAttached ? vec3(0.0) : playPlace.xyz;
98
+ vec3 axis = isAttached ? vec3(0.0, 1.0, 0.0) : zaismaTurn(playTurn, vec3(0.0, 1.0, 0.0));
99
+ vec3 local = zaismaLocalPlace(aBirth.xyz, aVelocity.xyz, age, life, seed, motionA, motionB, center, axis);
100
+ vec3 world = (isAttached ? playPlace.xyz + zaismaTurn(playTurn, local) : local) + zaismaWorldDrift(age, motionA, uWind);
101
+
102
+ vec4 keyCounts = zaismaElement(row, ${ELEMENT_ROW.keyCounts});
103
+ float size = zaismaOverLife(zaismaElement(row, ${ELEMENT_ROW.sizeKeys}), keyCounts.x, lifeShare);
104
+ size *= playPlace.w * (1.0 + keyCounts.w * (zaismaHash(seed, 1.0) * 2.0 - 1.0));
105
+ // A solid never fades: it shrinks away as its effect would have faded it.
106
+ float opacity = zaismaOverLife(zaismaElement(row, ${ELEMENT_ROW.opacityKeys}), keyCounts.y, lifeShare) * playTint.a;
107
+ size *= sqrt(min(opacity * 1.6, 1.0));
108
+
109
+ vec3 corner = cornerHeld.xyz;
110
+ vec3 normal = texelFetch(uChunkShapes, ivec2(gl_VertexID, shape * 2 + 1), 0).xyz;
111
+ vec3 tumbleAxis = normalize(vec3(zaismaHash(seed, 4.0), zaismaHash(seed, 5.0), zaismaHash(seed, 6.0)) * 2.0 - 1.0 + 1e-3);
112
+ float angle = aSeed.w + facing.z * age * (0.5 + zaismaHash(seed, 3.0));
113
+ if (facing.x > 0.5 && facing.x < 1.5) {
114
+ // Pointing along its own motion, stretched by its streak time.
115
+ float earlier = max(age - 0.02, 0.0);
116
+ vec3 localEarlier = zaismaLocalPlace(aBirth.xyz, aVelocity.xyz, earlier, life, seed, motionA, motionB, center, axis);
117
+ vec3 worldEarlier = (isAttached ? playPlace.xyz + zaismaTurn(playTurn, localEarlier) : localEarlier) + zaismaWorldDrift(earlier, motionA, uWind);
118
+ vec3 velocity = (world - worldEarlier) / max(age - earlier, 1e-4);
119
+ float speed = length(velocity);
120
+ vec3 along = speed > 1e-3 ? velocity / speed : vec3(0.0, 1.0, 0.0);
121
+ vec3 side = normalize(abs(along.y) < 0.99 ? cross(vec3(0.0, 1.0, 0.0), along) : vec3(1.0, 0.0, 0.0));
122
+ vec3 forward = cross(side, along);
123
+ float stretch = max(1.0, speed * facing.y / max(size, 1e-3));
124
+ corner = side * corner.x + along * corner.y * stretch + forward * corner.z;
125
+ normal = normalize(side * normal.x + along * normal.y / stretch + forward * normal.z);
126
+ } else {
127
+ corner = zaismaTurnRound(tumbleAxis, angle, corner);
128
+ normal = zaismaTurnRound(tumbleAxis, angle, normal);
129
+ }
130
+ world += corner * size;
131
+ vec4 mvPosition = viewMatrix * vec4(world, 1.0);
132
+ gl_Position = projectionMatrix * mvPosition;
133
+
134
+ float colorPlace = clamp(lifeShare, 0.0, 1.0) * (keyCounts.z - 1.0);
135
+ float colorIndex = min(floor(colorPlace), max(keyCounts.z - 2.0, 0.0));
136
+ vec4 colorFrom = zaismaElement(row, ${ELEMENT_ROW.colorKeys} + int(colorIndex));
137
+ vec4 colorTo = zaismaElement(row, ${ELEMENT_ROW.colorKeys} + int(min(colorIndex + 1.0, keyCounts.z - 1.0)));
138
+ float glow = zaismaElement(row, ${ELEMENT_ROW.colorKeys}).a;
139
+ float lit = zaismaElement(row, ${ELEMENT_ROW.colorKeys + 2}).a;
140
+ // Each chunk takes its own shade of the colour, so a pile of them reads as separate pieces.
141
+ float shade = 0.82 + 0.36 * zaismaHash(seed, 7.0);
142
+ vColor = mix(colorFrom.rgb, colorTo.rgb, colorPlace - colorIndex) * playTint.rgb * glow * shade * mix(vec3(1.0), zaismaLightAt(world, normal, 0.15), lit);
143
+ #include <fog_vertex>
144
+ }`;
145
+
146
+ const CHUNK_FRAGMENT = /* glsl */ `
147
+ varying vec3 vColor;
148
+ #include <common>
149
+ #include <fog_pars_fragment>
150
+ void main() {
151
+ gl_FragColor = vec4(vColor, 1.0);
152
+ #include <fog_fragment>
153
+ #include <tonemapping_fragment>
154
+ #include <colorspace_fragment>
155
+ }`;
156
+
157
+ /** Makes the batch. Answers { mesh, takeSlab, giveSlab, write, rewrite, update, liveCount, capacity, dispose }. */
158
+ export function createChunkBatch({ chunkCount, sharedUniforms }) {
159
+ const values = new Float32Array(chunkCount * FLOATS_PER_CHUNK);
160
+ const buffer = new THREE.InstancedInterleavedBuffer(values, FLOATS_PER_CHUNK);
161
+ buffer.setUsage(THREE.DynamicDrawUsage);
162
+ const geometry = new THREE.InstancedBufferGeometry();
163
+ // Sixty corners with nothing of their own: each reads its place from the shape table by its number.
164
+ geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(CORNER_COUNT * 3), 3));
165
+ geometry.setAttribute("aBirth", new THREE.InterleavedBufferAttribute(buffer, 4, 0));
166
+ geometry.setAttribute("aVelocity", new THREE.InterleavedBufferAttribute(buffer, 4, 4));
167
+ geometry.setAttribute("aSeed", new THREE.InterleavedBufferAttribute(buffer, 4, 8));
168
+ geometry.instanceCount = 0;
169
+ const shapeTable = makeShapeTable();
170
+ const material = new THREE.ShaderMaterial({
171
+ name: "zaisma_effect_chunks",
172
+ vertexShader: CHUNK_VERTEX,
173
+ fragmentShader: CHUNK_FRAGMENT,
174
+ uniforms: { ...fogUniforms(), ...sharedUniforms, uChunkShapes: { value: shapeTable } },
175
+ fog: true,
176
+ side: THREE.DoubleSide,
177
+ });
178
+ const mesh = new THREE.Mesh(geometry, material);
179
+ mesh.name = "zaisma_effect_chunks";
180
+ mesh.frustumCulled = false;
181
+ mesh.visible = false;
182
+
183
+ const pool = createSlotPool(chunkCount);
184
+ const endSec = new Float32Array(chunkCount);
185
+ const slabs = new Set();
186
+ let dirtyStart = Infinity;
187
+ let dirtyEnd = -1;
188
+ let liveCount = 0;
189
+
190
+ function markDirty(chunkIndex, count) {
191
+ dirtyStart = Math.min(dirtyStart, chunkIndex);
192
+ dirtyEnd = Math.max(dirtyEnd, chunkIndex + count);
193
+ }
194
+
195
+ function takeSlab(wantedCount, owner) {
196
+ const count = Math.min(wantedCount, pool.longestFreeCount());
197
+ if (count <= 0) return null;
198
+ const slab = { start: pool.take(count), capacity: count, nextOffset: 0, liveCount: 0, lastEndSec: 0, owner };
199
+ slabs.add(slab);
200
+ return slab;
201
+ }
202
+
203
+ function giveSlab(slab) {
204
+ if (!slabs.delete(slab)) return;
205
+ const from = slab.start * FLOATS_PER_CHUNK;
206
+ values.fill(0, from, from + slab.capacity * FLOATS_PER_CHUNK);
207
+ for (let offset = 0; offset < slab.capacity; offset += 1) values[from + offset * FLOATS_PER_CHUNK + 3] = 1e9;
208
+ markDirty(slab.start, slab.capacity);
209
+ pool.give(slab.start, slab.capacity);
210
+ }
211
+
212
+ function writeAt(chunkIndex, x, y, z, velocityX, velocityY, velocityZ, birthSec, lifeSec, seedNumber, elementRow, playRow, angleRad) {
213
+ const at = chunkIndex * FLOATS_PER_CHUNK;
214
+ values[at] = x;
215
+ values[at + 1] = y;
216
+ values[at + 2] = z;
217
+ values[at + 3] = birthSec;
218
+ values[at + 4] = velocityX;
219
+ values[at + 5] = velocityY;
220
+ values[at + 6] = velocityZ;
221
+ values[at + 7] = lifeSec;
222
+ values[at + 8] = seedNumber;
223
+ values[at + 9] = elementRow;
224
+ values[at + 10] = playRow;
225
+ values[at + 11] = angleRad;
226
+ endSec[chunkIndex] = birthSec + lifeSec;
227
+ markDirty(chunkIndex, 1);
228
+ }
229
+
230
+ /** Writes one chunk into a slab's ring. */
231
+ function write(slab, x, y, z, velocityX, velocityY, velocityZ, birthSec, lifeSec, seedNumber, elementRow, playRow) {
232
+ const chunkIndex = slab.start + slab.nextOffset;
233
+ slab.nextOffset = (slab.nextOffset + 1) % slab.capacity;
234
+ slab.lastEndSec = Math.max(slab.lastEndSec, birthSec + lifeSec);
235
+ writeAt(chunkIndex, x, y, z, velocityX, velocityY, velocityZ, birthSec, lifeSec, seedNumber, elementRow, playRow, seedNumber * 6.2831853);
236
+ }
237
+
238
+ /** Writes a simulated chunk where it is this frame: its place, its turn, nothing for the shader to work out. */
239
+ function rewrite(slab, offset, x, y, z, birthSec, lifeSec, seedNumber, elementRow, playRow, angleRad) {
240
+ slab.lastEndSec = Math.max(slab.lastEndSec, birthSec + lifeSec);
241
+ writeAt(slab.start + offset, x, y, z, 0, 0, 0, birthSec, lifeSec, seedNumber, elementRow, playRow, angleRad);
242
+ }
243
+
244
+ function update(nowSec) {
245
+ let highest = 0;
246
+ liveCount = 0;
247
+ for (const slab of slabs) {
248
+ if (slab.lastEndSec <= nowSec) continue;
249
+ highest = Math.max(highest, slab.start + slab.capacity);
250
+ for (let offset = 0; offset < slab.capacity; offset += 1) if (endSec[slab.start + offset] > nowSec) liveCount += 1;
251
+ }
252
+ geometry.instanceCount = highest;
253
+ mesh.visible = highest > 0;
254
+ if (dirtyEnd > dirtyStart) {
255
+ buffer.clearUpdateRanges();
256
+ buffer.addUpdateRange(dirtyStart * FLOATS_PER_CHUNK, (dirtyEnd - dirtyStart) * FLOATS_PER_CHUNK);
257
+ buffer.needsUpdate = true;
258
+ dirtyStart = Infinity;
259
+ dirtyEnd = -1;
260
+ }
261
+ }
262
+
263
+ /** Moves every time written here back by a span, as the effects' clock starts over: see index.js. */
264
+ function shiftTime(spanSec) {
265
+ for (let at = 3; at < values.length; at += FLOATS_PER_CHUNK) values[at] -= spanSec;
266
+ for (let index = 0; index < endSec.length; index += 1) endSec[index] -= spanSec;
267
+ for (const slab of slabs) slab.lastEndSec -= spanSec;
268
+ markDirty(0, chunkCount);
269
+ }
270
+
271
+ return {
272
+ mesh,
273
+ takeSlab,
274
+ giveSlab,
275
+ write,
276
+ rewrite,
277
+ update,
278
+ shiftTime,
279
+ get liveCount() {
280
+ return liveCount;
281
+ },
282
+ get capacity() {
283
+ return chunkCount;
284
+ },
285
+ get freeCount() {
286
+ return pool.freeCount;
287
+ },
288
+ dispose() {
289
+ geometry.dispose();
290
+ material.dispose();
291
+ shapeTable.dispose();
292
+ },
293
+ };
294
+ }
@@ -0,0 +1,160 @@
1
+ // The mark batch: what effects leave on surfaces (a scorch, a crack, a splat), in one draw call. A mark is a flat
2
+ // shape laid on the surface where it was made, lit by the scene, that glows while hot and fades as its life ends.
3
+ // They're kept in a ring: when it's full, a new mark takes the oldest one's place.
4
+ import * as THREE from "three";
5
+ import { BLEND_END_GLSL, ONE_BLEND, SHARED_VERTEX_GLSL, fogUniforms } from "./shared.js";
6
+
7
+ const FLOATS_PER_MARK = 20;
8
+
9
+ const MARK_VERTEX = /* glsl */ `
10
+ attribute vec4 aPlace;
11
+ attribute vec4 aFacing;
12
+ attribute vec4 aLife;
13
+ attribute vec4 aTint;
14
+ attribute vec4 aGlow;
15
+ ${SHARED_VERTEX_GLSL}
16
+ varying vec2 vUv;
17
+ varying vec4 vColor;
18
+ varying vec4 vGlow;
19
+ #include <fog_pars_vertex>
20
+
21
+ void main() {
22
+ float age = uTime - aLife.x;
23
+ float life = aLife.y;
24
+ if (age < 0.0 || age >= life) {
25
+ gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
26
+ return;
27
+ }
28
+ vec3 normal = aFacing.xyz;
29
+ vec3 side = normalize(abs(normal.y) < 0.99 ? cross(vec3(0.0, 1.0, 0.0), normal) : vec3(1.0, 0.0, 0.0));
30
+ vec3 forward = cross(normal, side);
31
+ float cosTurn = cos(aFacing.w);
32
+ float sinTurn = sin(aFacing.w);
33
+ vec2 corner = position.xy;
34
+ vec2 turned = vec2(corner.x * cosTurn - corner.y * sinTurn, corner.x * sinTurn + corner.y * cosTurn);
35
+ vec3 world = aPlace.xyz + (side * turned.x + forward * turned.y) * aPlace.w * 0.5 + normal * 0.012;
36
+ vec4 mvPosition = viewMatrix * vec4(world, 1.0);
37
+ gl_Position = projectionMatrix * mvPosition;
38
+ vUv = aLife.zw + (corner * 0.5 + 0.5) * 0.98 * ${(1 / 8).toFixed(4)} + 0.00125;
39
+ // It settles in over a moment, and fades out over the last of its life.
40
+ float fade = min(age / 0.06, 1.0) * clamp((life - age) / min(life * 0.25, 2.0), 0.0, 1.0);
41
+ vColor = vec4(aTint.rgb * zaismaLightAt(world, normal, 0.0), aTint.a * fade);
42
+ float hot = aGlow.a > 0.0 ? max(1.0 - age / aGlow.a, 0.0) : 0.0;
43
+ vGlow = vec4(aGlow.rgb, hot * hot);
44
+ #include <fog_vertex>
45
+ }`;
46
+
47
+ const MARK_FRAGMENT = /* glsl */ `
48
+ uniform sampler2D uAtlas;
49
+ varying vec2 vUv;
50
+ varying vec4 vColor;
51
+ varying vec4 vGlow;
52
+ #include <common>
53
+ #include <fog_pars_fragment>
54
+ void main() {
55
+ vec4 held = texture2D(uAtlas, vUv);
56
+ float zaismaAddShare = 0.0;
57
+ gl_FragColor = vec4(vColor.rgb * (0.7 + 0.3 * held.b) + vGlow.rgb * vGlow.a * held.b * 3.0, held.g * vColor.a);
58
+ ${BLEND_END_GLSL}
59
+ }`;
60
+
61
+ /** Makes the batch. Answers { mesh, setCapacity, add, clear, liveCount, dispose }. */
62
+ export function createMarkBatch({ markCount, sharedUniforms }) {
63
+ const geometry = new THREE.InstancedBufferGeometry();
64
+ geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]), 3));
65
+ geometry.setIndex([0, 1, 2, 2, 1, 3]);
66
+ let values;
67
+ let buffer;
68
+ let capacity = 0;
69
+ let nextIndex = 0;
70
+ let writtenCount = 0;
71
+ const endSec = [];
72
+
73
+ function setCapacity(newCapacity) {
74
+ capacity = newCapacity;
75
+ values = new Float32Array(Math.max(capacity, 1) * FLOATS_PER_MARK);
76
+ buffer = new THREE.InstancedInterleavedBuffer(values, FLOATS_PER_MARK);
77
+ buffer.setUsage(THREE.DynamicDrawUsage);
78
+ ["aPlace", "aFacing", "aLife", "aTint", "aGlow"].forEach((name, index) => geometry.setAttribute(name, new THREE.InterleavedBufferAttribute(buffer, 4, index * 4)));
79
+ nextIndex = 0;
80
+ writtenCount = 0;
81
+ endSec.length = 0;
82
+ geometry.instanceCount = 0;
83
+ }
84
+ setCapacity(markCount);
85
+
86
+ const material = new THREE.ShaderMaterial({
87
+ name: "zaisma_effect_marks",
88
+ vertexShader: MARK_VERTEX,
89
+ fragmentShader: MARK_FRAGMENT,
90
+ uniforms: { ...fogUniforms(), ...sharedUniforms },
91
+ fog: true,
92
+ polygonOffset: true,
93
+ polygonOffsetFactor: -2,
94
+ polygonOffsetUnits: -2,
95
+ ...ONE_BLEND,
96
+ });
97
+ const mesh = new THREE.Mesh(geometry, material);
98
+ mesh.name = "zaisma_effect_marks";
99
+ mesh.frustumCulled = false;
100
+ mesh.renderOrder = 800;
101
+ mesh.visible = false;
102
+
103
+ /**
104
+ * Lays a mark: { x, y, z, normalX, normalY, normalZ, sizeM, turnRad, birthSec, lifeSec, cellU, cellV, color: Color,
105
+ * opacityShare, glowColor: Color, glowDurationSec }.
106
+ */
107
+ function add(mark) {
108
+ if (capacity === 0) return;
109
+ const at = nextIndex * FLOATS_PER_MARK;
110
+ values.set([mark.x, mark.y, mark.z, mark.sizeM, mark.normalX, mark.normalY, mark.normalZ, mark.turnRad, mark.birthSec, mark.lifeSec, mark.cellU, mark.cellV, mark.color.r, mark.color.g, mark.color.b, mark.opacityShare, mark.glowColor.r, mark.glowColor.g, mark.glowColor.b, mark.glowDurationSec], at);
111
+ endSec[nextIndex] = mark.birthSec + mark.lifeSec;
112
+ buffer.addUpdateRange(at, FLOATS_PER_MARK);
113
+ buffer.needsUpdate = true;
114
+ nextIndex = (nextIndex + 1) % capacity;
115
+ writtenCount = Math.min(writtenCount + 1, capacity);
116
+ geometry.instanceCount = writtenCount;
117
+ }
118
+
119
+ let liveCount = 0;
120
+ function update(nowSec) {
121
+ liveCount = 0;
122
+ for (let index = 0; index < writtenCount; index += 1) if (endSec[index] > nowSec) liveCount += 1;
123
+ mesh.visible = liveCount > 0;
124
+ }
125
+
126
+ /** Moves every time written here back by a span, as the effects' clock starts over: see index.js. */
127
+ function shiftTime(spanSec) {
128
+ for (let index = 0; index < writtenCount; index += 1) {
129
+ values[index * FLOATS_PER_MARK + 8] -= spanSec;
130
+ endSec[index] -= spanSec;
131
+ }
132
+ if (writtenCount > 0) {
133
+ buffer.clearUpdateRanges();
134
+ buffer.addUpdateRange(0, writtenCount * FLOATS_PER_MARK);
135
+ buffer.needsUpdate = true;
136
+ }
137
+ }
138
+
139
+ return {
140
+ mesh,
141
+ setCapacity,
142
+ add,
143
+ update,
144
+ shiftTime,
145
+ clear() {
146
+ setCapacity(capacity);
147
+ mesh.visible = false;
148
+ },
149
+ get liveCount() {
150
+ return liveCount;
151
+ },
152
+ get capacity() {
153
+ return capacity;
154
+ },
155
+ dispose() {
156
+ geometry.dispose();
157
+ material.dispose();
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,233 @@
1
+ // The ribbon batch: trails and beams, in one draw call. A ribbon is a strip laid along the path of what it follows
2
+ // (a blade's edge, a projectile), fading from its head to its tail. A beam is a strip between two places, straight
3
+ // or jagged like lightning. Both are rebuilt each frame from a handful of points, which costs little: there are
4
+ // never many, and each is a few dozen points.
5
+ import * as THREE from "three";
6
+ import { hashNumbers, randomFrom, valueOverLife } from "../format.js";
7
+ import { BLEND_END_GLSL, ONE_BLEND, fogUniforms } from "./shared.js";
8
+
9
+ const FLOATS_PER_CORNER = 9;
10
+ const MAXIMUM_CORNER_COUNT = 8192;
11
+ const MAXIMUM_POINT_COUNT = 64;
12
+
13
+ const RIBBON_VERTEX = /* glsl */ `
14
+ attribute vec4 aColor;
15
+ attribute vec2 aAcross;
16
+ varying vec4 vColor;
17
+ varying vec2 vAcross;
18
+ #include <fog_pars_vertex>
19
+ void main() {
20
+ vec4 mvPosition = viewMatrix * vec4(position, 1.0);
21
+ gl_Position = projectionMatrix * mvPosition;
22
+ vColor = aColor;
23
+ vAcross = aAcross;
24
+ #include <fog_vertex>
25
+ }`;
26
+
27
+ const RIBBON_FRAGMENT = /* glsl */ `
28
+ varying vec4 vColor;
29
+ varying vec2 vAcross;
30
+ #include <common>
31
+ #include <fog_pars_fragment>
32
+ void main() {
33
+ // Brightest along its middle, soft toward its edges.
34
+ float middle = 1.0 - vAcross.x * vAcross.x;
35
+ float zaismaAddShare = vAcross.y;
36
+ gl_FragColor = vec4(vColor.rgb * (0.6 + 0.6 * middle), vColor.a * middle);
37
+ ${BLEND_END_GLSL}
38
+ }`;
39
+
40
+ const head = new THREE.Vector3();
41
+ const edge = new THREE.Vector3();
42
+ const along = new THREE.Vector3();
43
+ const toCamera = new THREE.Vector3();
44
+ const side = new THREE.Vector3();
45
+ const color = new THREE.Color();
46
+
47
+ function colorOverLength(colors, sharePct, into) {
48
+ const place = Math.min(Math.max(sharePct / 100, 0), 1) * (colors.length - 1);
49
+ const index = Math.min(Math.floor(place), Math.max(colors.length - 2, 0));
50
+ return into.copy(colors[index]).lerp(colors[Math.min(index + 1, colors.length - 1)], place - index);
51
+ }
52
+
53
+ /** Makes the batch. Answers { mesh, addRibbon, addBeam, update, liveCount, dispose }. */
54
+ export function createRibbonBatch() {
55
+ const values = new Float32Array(MAXIMUM_CORNER_COUNT * FLOATS_PER_CORNER);
56
+ const buffer = new THREE.InterleavedBuffer(values, FLOATS_PER_CORNER);
57
+ buffer.setUsage(THREE.DynamicDrawUsage);
58
+ const geometry = new THREE.BufferGeometry();
59
+ geometry.setAttribute("position", new THREE.InterleavedBufferAttribute(buffer, 3, 0));
60
+ geometry.setAttribute("aColor", new THREE.InterleavedBufferAttribute(buffer, 4, 3));
61
+ geometry.setAttribute("aAcross", new THREE.InterleavedBufferAttribute(buffer, 2, 7));
62
+ const indices = new Uint16Array((MAXIMUM_CORNER_COUNT / 2) * 6);
63
+ const index = new THREE.BufferAttribute(indices, 1);
64
+ index.setUsage(THREE.DynamicDrawUsage);
65
+ geometry.setIndex(index);
66
+ geometry.setDrawRange(0, 0);
67
+ const material = new THREE.ShaderMaterial({ name: "zaisma_effect_ribbons", vertexShader: RIBBON_VERTEX, fragmentShader: RIBBON_FRAGMENT, uniforms: fogUniforms(), fog: true, side: THREE.DoubleSide, ...ONE_BLEND });
68
+ const mesh = new THREE.Mesh(geometry, material);
69
+ mesh.name = "zaisma_effect_ribbons";
70
+ mesh.frustumCulled = false;
71
+ mesh.renderOrder = 910;
72
+ mesh.visible = false;
73
+
74
+ const ribbons = new Set();
75
+ const beams = new Set();
76
+ let cornerCount = 0;
77
+ let indexCount = 0;
78
+
79
+ function corner(x, y, z, rgb, opacity, across, addShare) {
80
+ const at = cornerCount * FLOATS_PER_CORNER;
81
+ values[at] = x;
82
+ values[at + 1] = y;
83
+ values[at + 2] = z;
84
+ values[at + 3] = rgb.r;
85
+ values[at + 4] = rgb.g;
86
+ values[at + 5] = rgb.b;
87
+ values[at + 6] = opacity;
88
+ values[at + 7] = across;
89
+ values[at + 8] = addShare;
90
+ cornerCount += 1;
91
+ }
92
+
93
+ /** Joins the last two pairs of corners written with two triangles. */
94
+ function joinLastPairs() {
95
+ const last = cornerCount - 4;
96
+ indices.set([last, last + 1, last + 2, last + 2, last + 1, last + 3], indexCount);
97
+ indexCount += 6;
98
+ }
99
+
100
+ /**
101
+ * A ribbon: { play, lifeSec, widthKeys (m), colors: Color[], opacityKeys (0 to 100), glowShare, addShare,
102
+ * minimumStepM, fromOffset: Vector3, toOffset: Vector3, isBlade, startSec }. It follows its play's place and turn.
103
+ */
104
+ function addRibbon(ribbon) {
105
+ ribbon.points = [];
106
+ ribbons.add(ribbon);
107
+ return ribbon;
108
+ }
109
+
110
+ /**
111
+ * A beam: { play, to: Vector3, lifeSec, widthM, segmentCount, jitterM, rejitterPerSec, reachM, spreadRad,
112
+ * tipWidthShare, colors: Color[], opacityKeys, glowShare, addShare, startSec, seedNumber }. It runs from its play's
113
+ * place to `to` when the play was given an end; without one, reachM out along the play's direction, each path
114
+ * turned off it by up to spreadRad, worked out each frame so it rides with a moving play.
115
+ */
116
+ function addBeam(beam) {
117
+ beams.add(beam);
118
+ return beam;
119
+ }
120
+
121
+ function writeRibbon(ribbon, nowSec, cameraPosition) {
122
+ const { play, points } = ribbon;
123
+ const isFollowing = !play.isEnded && (play.stopSec === null || nowSec < play.stopSec);
124
+ if (isFollowing) {
125
+ head.copy(ribbon.fromOffset).multiplyScalar(play.scaleShare).applyQuaternion(play.turn).add(play.place);
126
+ edge.copy(ribbon.toOffset).multiplyScalar(play.scaleShare).applyQuaternion(play.turn).add(play.place);
127
+ const now = { x: head.x, y: head.y, z: head.z, edgeX: edge.x, edgeY: edge.y, edgeZ: edge.z, bornSec: nowSec };
128
+ // The newest point rides with what's followed; once that has moved a step from the point behind it, it stays
129
+ // where it is and a new one rides on.
130
+ const behind = points[1];
131
+ if (!behind || Math.hypot(head.x - behind.x, head.y - behind.y, head.z - behind.z) >= ribbon.minimumStepM) {
132
+ points.unshift(now);
133
+ if (points.length > MAXIMUM_POINT_COUNT) points.pop();
134
+ } else points[0] = now;
135
+ }
136
+ while (points.length > 0 && nowSec - points[points.length - 1].bornSec >= ribbon.lifeSec) points.pop();
137
+ if (points.length < 2) return points.length > 0 || isFollowing;
138
+ if (cornerCount + points.length * 2 > MAXIMUM_CORNER_COUNT) return true;
139
+ for (let number = 0; number < points.length; number += 1) {
140
+ const point = points[number];
141
+ const sharePct = ((nowSec - point.bornSec) / ribbon.lifeSec) * 100;
142
+ const opacity = (valueOverLife(ribbon.opacityKeys, sharePct) / 100) * play.strengthShare;
143
+ colorOverLength(ribbon.colors, sharePct, color).multiply(play.tint).multiplyScalar(ribbon.glowShare);
144
+ if (ribbon.isBlade) {
145
+ corner(point.x, point.y, point.z, color, opacity, -0.6, ribbon.addShare);
146
+ corner(point.edgeX, point.edgeY, point.edgeZ, color, opacity, 0.6, ribbon.addShare);
147
+ } else {
148
+ const neighbour = points[Math.min(number + 1, points.length - 1)];
149
+ const earlier = points[Math.max(number - 1, 0)];
150
+ along.set(earlier.x - neighbour.x, earlier.y - neighbour.y, earlier.z - neighbour.z);
151
+ toCamera.set(cameraPosition.x - point.x, cameraPosition.y - point.y, cameraPosition.z - point.z);
152
+ side.crossVectors(along, toCamera);
153
+ if (side.lengthSq() < 1e-10) side.set(1, 0, 0);
154
+ side.normalize().multiplyScalar(valueOverLife(ribbon.widthKeys, sharePct) * 0.5 * play.scaleShare);
155
+ corner(point.x - side.x, point.y - side.y, point.z - side.z, color, opacity, -1, ribbon.addShare);
156
+ corner(point.x + side.x, point.y + side.y, point.z + side.z, color, opacity, 1, ribbon.addShare);
157
+ }
158
+ if (number > 0) joinLastPairs();
159
+ }
160
+ return true;
161
+ }
162
+
163
+ function writeBeam(beam, nowSec, cameraPosition) {
164
+ const sinceSec = nowSec - beam.startSec;
165
+ if (sinceSec >= beam.lifeSec || beam.play.isEnded) return false;
166
+ if (sinceSec < 0) return true;
167
+ const pointCount = beam.segmentCount + 1;
168
+ if (cornerCount + pointCount * 2 > MAXIMUM_CORNER_COUNT) return true;
169
+ const sharePct = (sinceSec / beam.lifeSec) * 100;
170
+ const opacity = (valueOverLife(beam.opacityKeys, sharePct) / 100) * beam.play.strengthShare;
171
+ colorOverLength(beam.colors, sharePct, color).multiply(beam.play.tint).multiplyScalar(beam.glowShare);
172
+ // Its jagged path follows from its seed and which path it's on, so every player sees the same bolt.
173
+ const next = randomFrom(hashNumbers(beam.seedNumber, Math.floor(sinceSec * beam.rejitterPerSec)));
174
+ const from = beam.play.place;
175
+ if (beam.play.hasEnd) along.subVectors(beam.to, from);
176
+ else {
177
+ // A direction inside the cone, evenly over its area, from the same seed as the path.
178
+ const cosTurn = 1 - next() * (1 - Math.cos(beam.spreadRad));
179
+ const sinTurn = Math.sqrt(Math.max(1 - cosTurn * cosTurn, 0));
180
+ const roundRad = next() * Math.PI * 2;
181
+ along.set(sinTurn * Math.cos(roundRad), cosTurn, sinTurn * Math.sin(roundRad)).applyQuaternion(beam.play.turn).multiplyScalar(beam.reachM * beam.play.scaleShare);
182
+ }
183
+ const halfWidthM = beam.widthM * 0.5 * beam.play.scaleShare;
184
+ for (let number = 0; number < pointCount; number += 1) {
185
+ const share = number / beam.segmentCount;
186
+ head.copy(from).addScaledVector(along, share);
187
+ if (beam.jitterM > 0 && number > 0 && number < beam.segmentCount) {
188
+ head.x += (next() - 0.5) * 2 * beam.jitterM;
189
+ head.y += (next() - 0.5) * 2 * beam.jitterM;
190
+ head.z += (next() - 0.5) * 2 * beam.jitterM;
191
+ }
192
+ toCamera.subVectors(cameraPosition, head);
193
+ side.crossVectors(along, toCamera);
194
+ if (side.lengthSq() < 1e-10) side.set(1, 0, 0);
195
+ side.normalize().multiplyScalar(halfWidthM * (1 - (1 - beam.tipWidthShare) * share));
196
+ corner(head.x - side.x, head.y - side.y, head.z - side.z, color, opacity, -1, beam.addShare);
197
+ corner(head.x + side.x, head.y + side.y, head.z + side.z, color, opacity, 1, beam.addShare);
198
+ if (number > 0) joinLastPairs();
199
+ }
200
+ return true;
201
+ }
202
+
203
+ function update(nowSec, cameraPosition) {
204
+ cornerCount = 0;
205
+ indexCount = 0;
206
+ for (const ribbon of ribbons) if (!writeRibbon(ribbon, nowSec, cameraPosition)) ribbons.delete(ribbon);
207
+ for (const beam of beams) if (!writeBeam(beam, nowSec, cameraPosition)) beams.delete(beam);
208
+ geometry.setDrawRange(0, indexCount);
209
+ mesh.visible = indexCount > 0;
210
+ if (indexCount > 0) {
211
+ buffer.clearUpdateRanges();
212
+ buffer.addUpdateRange(0, cornerCount * FLOATS_PER_CORNER);
213
+ buffer.needsUpdate = true;
214
+ index.clearUpdateRanges();
215
+ index.addUpdateRange(0, indexCount);
216
+ index.needsUpdate = true;
217
+ }
218
+ }
219
+
220
+ return {
221
+ mesh,
222
+ addRibbon,
223
+ addBeam,
224
+ update,
225
+ get liveCount() {
226
+ return ribbons.size + beams.size;
227
+ },
228
+ dispose() {
229
+ geometry.dispose();
230
+ material.dispose();
231
+ },
232
+ };
233
+ }