littlejsengine 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engineDraw.js CHANGED
@@ -259,8 +259,9 @@ class TextureInfo
259
259
  * @param {boolean} [useWebGL] - Should use WebGL if available?
260
260
  * @param {boolean|Array<number>} [wrap] - Should the texture wrap (REPEAT) or clamp (CLAMP_TO_EDGE)? Or the WebGL
261
261
  * modes across and down, like [gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT], as a glTF sampler gives them
262
+ * @param {boolean} [pixelated] - Hard edged or smooth for this texture alone, undefined follows tilesPixelated
262
263
  */
263
- constructor(image, useWebGL=true, wrap=false)
264
+ constructor(image, useWebGL=true, wrap=false, pixelated)
264
265
  {
265
266
  /** @property {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} - image source */
266
267
  this.image = image;
@@ -275,6 +276,10 @@ class TextureInfo
275
276
  * across and down
276
277
  * @type {boolean|Array<number>} */
277
278
  this.wrap = wrap;
279
+ /** @property {boolean|undefined} - Hard edged or smooth for this texture alone, a soft glow in a pixel art
280
+ * game or pixel art in a smooth one; undefined follows tilesPixelated
281
+ * @type {boolean|undefined} */
282
+ this.pixelated = pixelated;
278
283
  useWebGL && this.createWebGLTexture();
279
284
  }
280
285
 
@@ -305,6 +310,17 @@ class TextureInfo
305
310
  this.wrap = wrap;
306
311
  glSetTextureWrap(this.glTexture, wrap);
307
312
  }
313
+
314
+ /** Make this texture hard edged or smooth on its own, whatever tilesPixelated says for the rest; it is made again
315
+ * with the new filtering
316
+ * @param {boolean} [pixelated] - undefined follows tilesPixelated again */
317
+ setPixelated(pixelated)
318
+ {
319
+ this.pixelated = pixelated;
320
+ if (!this.glTexture) return;
321
+ this.destroyWebGLTexture();
322
+ this.createWebGLTexture();
323
+ }
308
324
  }
309
325
 
310
326
  ///////////////////////////////////////////////////////////////////////////////
@@ -1848,6 +1864,33 @@ class ImageFont
1848
1864
  }
1849
1865
  }
1850
1866
 
1867
+ // how strong a light's glow is at a distance from its middle, 0 there to 1 at the edge: a bell, full in the middle
1868
+ // and nothing at the edge, fading faster the higher the falloff
1869
+ function engineGlowAlpha(r, falloff)
1870
+ {
1871
+ const k = 3.5 * falloff, edge = Math.exp(-k);
1872
+ return (Math.exp(-k * r * r) - edge) / (1 - edge);
1873
+ }
1874
+
1875
+ // the soft round glow of the 2D and 3D lights, one texture for each falloff, rounded to a tenth so a changing falloff
1876
+ // makes only a few, each made once from a canvas; undefined headless or without a canvas
1877
+ const engineGlowTextures = new Map;
1878
+ function engineGlowTexture(falloff=1)
1879
+ {
1880
+ ASSERT(isNumber(falloff) && falloff > 0, 'glowFalloff must be a number above 0');
1881
+ const key = max(round(falloff * 10), 1) / 10;
1882
+ let texture = engineGlowTextures.get(key);
1883
+ if (texture || !glContext || typeof OffscreenCanvas == 'undefined') return texture;
1884
+ const size = 64, context = createCanvasContext(size), steps = 16;
1885
+ const gradient = context.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
1886
+ for (let i = 0; i <= steps; ++i)
1887
+ gradient.addColorStop(i / steps, 'rgba(255,255,255,' + engineGlowAlpha(i / steps, key).toFixed(4) + ')');
1888
+ context.fillStyle = gradient;
1889
+ context.fillRect(0, 0, size, size);
1890
+ engineGlowTextures.set(key, texture = new TextureInfo(context.canvas, true, false, false));
1891
+ return texture;
1892
+ }
1893
+
1851
1894
  // load engine font, called automatically on startup
1852
1895
  async function imageFontInit()
1853
1896
  {
@@ -432,12 +432,21 @@ function editorSetBaseline(record, written)
432
432
  // save a map as Tiled JSON: where the browser lets a page write files, Chrome and Edge, to a file picked once and
433
433
  // written again on each Save after, even after a reload once the browser gives permission, or picked again with
434
434
  // Save As; elsewhere as a download under the name of the file it came from; resolves to how it saved, undefined
435
- // when the picker was closed
435
+ // when the picker was closed; saves of a map run one at a time in the order asked, so the file ends with the last
436
436
  async function editorSave(record, pickAgain=false)
437
437
  {
438
438
  if (!record) return;
439
439
  editorStrokeEnd();
440
- const text = editorMapJSON(record), picker = /** @type {any} */ (globalThis).showSaveFilePicker;
440
+ const text = editorMapJSON(record); // the map as it is now, later edits wait for a later save
441
+ const saved = (async ()=> { await record.saving; return editorSaveText(record, text, pickAgain); })();
442
+ record.saving = saved.catch(()=> {});
443
+ return saved;
444
+ }
445
+
446
+ // write one save of a map, the one before it done
447
+ async function editorSaveText(record, text, pickAgain)
448
+ {
449
+ const picker = /** @type {any} */ (globalThis).showSaveFilePicker;
441
450
  if (picker)
442
451
  {
443
452
  try
@@ -335,6 +335,8 @@ export
335
335
  glFlush,
336
336
  glCopyToContext,
337
337
  glSetAntialias,
338
+ glMaxTextureSize,
339
+ glClampTextureSize,
338
340
  glDraw,
339
341
  glDrawUntextured,
340
342
  glDrawPointsTransform,
@@ -165,6 +165,13 @@ class ParticleEmitter extends EngineObject
165
165
  this.localSpace = localSpace;
166
166
  /** @property {number} - If non zero the particle is drawn as a trail, stretched in the direction of velocity */
167
167
  this.trailScale = 0;
168
+ /** @property {number} - Grows the whole effect as each particle is born: the spawn area, the particles' sizes,
169
+ * speed and fall, so it looks the same only bigger; 1 is as made, and a particle keeps the scale it was born
170
+ * with, so a change never moves the ones already out */
171
+ this.scale = 1;
172
+ /** @property {number} - The effect's own fall, added to each particle's velocity y every frame, on top of the
173
+ * world's gravity times gravityScale; an effect that sets its own looks the same in any game */
174
+ this.gravity = 0;
168
175
  /** @property {ParticleCallback|undefined} - Callback when particle is created
169
176
  * @type {ParticleCallback|undefined} */
170
177
  this.particleCreateCallback = undefined;
@@ -251,9 +258,9 @@ class ParticleEmitter extends EngineObject
251
258
  {
252
259
  // show emitter bounds
253
260
  if (this.emitCircle)
254
- debugCircle(this.pos, this.emitSize.x, '#0f0', 0, false, false);
261
+ debugCircle(this.pos, this.emitSize.x * this.scale, '#0f0', 0, false, false);
255
262
  else
256
- debugRect(this.pos, this.emitSize, '#0f0', 0, this.angle, false, false);
263
+ debugRect(this.pos, this.emitSize.scale(this.scale), '#0f0', 0, this.angle, false, false);
257
264
  }
258
265
  }
259
266
 
@@ -262,10 +269,11 @@ class ParticleEmitter extends EngineObject
262
269
  emitParticle()
263
270
  {
264
271
  // spawn a particle
272
+ const scale = this.scale; // grows the spawn area, the sizes and the speed of each particle born
265
273
  let pos = this.emitCircle ? // check if circle emitter
266
- randInCircle(this.emitSize.x/2) // circle emitter
267
- : vec2(rand(-.5,.5), rand(-.5,.5)) // box emitter
268
- .multiply(this.emitSize);
274
+ randInCircle(this.emitSize.x/2 * scale) // circle emitter
275
+ : vec2(rand(-.5,.5) * this.emitSize.x * scale, // box emitter, one vector made
276
+ rand(-.5,.5) * this.emitSize.y * scale);
269
277
  let angle = rand(this.particleConeAngle, -this.particleConeAngle);
270
278
  if (!this.localSpace)
271
279
  {
@@ -282,9 +290,9 @@ class ParticleEmitter extends EngineObject
282
290
 
283
291
  // randomize particle settings
284
292
  const particleTime = randomizeScale(this.particleTime);
285
- const sizeStart = randomizeScale(this.sizeStart);
286
- const sizeEnd = randomizeScale(this.sizeEnd);
287
- const speed = randomizeScale(this.speed);
293
+ const sizeStart = randomizeScale(this.sizeStart) * scale;
294
+ const sizeEnd = randomizeScale(this.sizeEnd) * scale;
295
+ const speed = randomizeScale(this.speed) * scale;
288
296
  const angleSpeed = randomizeScale(this.angleSpeed) * randSign();
289
297
  const coneAngle = rand(this.emitConeAngle, -this.emitConeAngle);
290
298
  const colorStart = randColor(this.colorStartA, this.colorStartB, this.randomColorLinear);
@@ -318,9 +326,13 @@ class ParticleEmitter extends EngineObject
318
326
  render()
319
327
  {
320
328
  // render all particles, the blend switched once for them all, not around each one
329
+ // and the tile's draw worked out once for them all, fresh each frame so a tile changed in place draws changed
321
330
  this.additive && setAdditiveBlendMode();
331
+ particleTile = null; // none yet, undefined is the untextured tile
332
+ particleTileBatch = true;
322
333
  for (const particle of this.particles)
323
334
  particle.render();
335
+ particleTileBatch = false;
324
336
  this.additive && setAdditiveBlendMode(false);
325
337
  }
326
338
 
@@ -347,6 +359,39 @@ class ParticleEmitter extends EngineObject
347
359
  // scratch vectors reused by Particle.render and the tile collision to avoid per-frame allocations
348
360
  const particleDrawPos = new Vector2, particleDrawSize = new Vector2, particleCollidePos = new Vector2;
349
361
 
362
+ // the WebGL draw of the tile particles draw with, what drawTile works out for each sprite: kept while an emitter
363
+ // renders its particles, so each one only writes its own values into the batch
364
+ let particleTile, particleTileBatch = false, particleTileTextured = false, particleTileEmpty = false;
365
+ let particleTileU0 = 0, particleTileV0 = 0, particleTileU1 = 0, particleTileV1 = 0;
366
+ function particleTileSet(tileInfo)
367
+ {
368
+ particleTile = tileInfo;
369
+ const textureInfo = tileInfo?.textureInfo;
370
+ particleTileTextured = !!textureInfo;
371
+ particleTileEmpty = !!textureInfo && !(tileInfo.size.x && tileInfo.size.y); // like a sprite still loading
372
+ if (!textureInfo || particleTileEmpty) return;
373
+
374
+ ASSERT(!!textureInfo.glTexture, 'texture has no WebGL texture, draw it with useWebGL false');
375
+ glSetTexture(textureInfo.glTexture); // bound, and its mipmaps brought up to date, once for the emitter
376
+ const sizeInverse = textureInfo.sizeInverse, bleed = tileInfo.bleed;
377
+ const x = tileInfo.pos.x * sizeInverse.x;
378
+ const y = tileInfo.pos.y * sizeInverse.y;
379
+ const w = tileInfo.size.x * sizeInverse.x;
380
+ const h = tileInfo.size.y * sizeInverse.y;
381
+ if (bleed)
382
+ {
383
+ const bleedX = sizeInverse.x*bleed;
384
+ const bleedY = sizeInverse.y*bleed;
385
+ particleTileU0 = x + bleedX; particleTileV0 = y + bleedY;
386
+ particleTileU1 = x - bleedX + w; particleTileV1 = y - bleedY + h;
387
+ }
388
+ else
389
+ {
390
+ particleTileU0 = x; particleTileV0 = y;
391
+ particleTileU1 = x + w; particleTileV1 = y + h;
392
+ }
393
+ }
394
+
350
395
  // tests if a particle collides with tiles at x, y, through its emitter's collide callback if it has one
351
396
  function particleCollideTest(particle, collideCallback, x, y)
352
397
  {
@@ -382,6 +427,8 @@ class Particle
382
427
  {
383
428
  /** @property {ParticleEmitter} - The emitter this particle came from */
384
429
  this.emitter = emitter;
430
+ /** @property {number} - The emitter's scale when it was made, which grows its fall */
431
+ this.scale = emitter.scale ?? 1; // a hand made emitter-like object may have none
385
432
  /** @property {Vector2} - Position, world space or local to the emitter when localSpace is set */
386
433
  this.pos = pos;
387
434
  /** @property {number} - Angle in radians */
@@ -444,7 +491,10 @@ class Particle
444
491
  // apply physics; only the tile collision needs where the particle was
445
492
  const solve = enablePhysicsSolver && collideLevel;
446
493
  const oldX = this.pos.x, oldY = this.pos.y;
447
- let gravityX = gravity.x * gravityScale, gravityY = gravity.y * gravityScale;
494
+ // the world's gravity times gravityScale plus the emitter's own, grown by the particle's scale
495
+ const fall = this.scale;
496
+ let gravityX = gravity.x * gravityScale * fall;
497
+ let gravityY = (gravity.y * gravityScale + (emitter.gravity || 0)) * fall;
448
498
  if (emitter.localSpace && emitter.angle)
449
499
  {
450
500
  // world gravity turned into the emitter's space, the render turns it back
@@ -498,7 +548,9 @@ class Particle
498
548
  }
499
549
  if (isBlockedY || !isBlockedX)
500
550
  {
501
- const wasFalling = this.velocity.y < 0 && gravity.y < 0 || this.velocity.y > 0 && gravity.y > 0;
551
+ // down is the world's gravity, or the emitter's own fall in a world with none
552
+ const down = gravity.y || emitter.gravity || 0;
553
+ const wasFalling = this.velocity.y < 0 && down < 0 || this.velocity.y > 0 && down > 0;
502
554
  if (wasFalling)
503
555
  this.groundObject = hitLayer;
504
556
 
@@ -577,7 +629,24 @@ class Particle
577
629
  angle = atan2(velocity.x, velocity.y);
578
630
  }
579
631
  }
580
- drawTile(pos, size, this.tileInfo, this.color, angle, this.mirror, undefined, glEnable, false);
632
+ if (glEnable && !headlessMode)
633
+ {
634
+ // straight into the batch, the tile's draw worked out once for the emitter's particles
635
+ const tileInfo = this.tileInfo;
636
+ if (!particleTileBatch || tileInfo !== particleTile)
637
+ particleTileSet(tileInfo);
638
+ if (!particleTileTextured)
639
+ glDrawUntextured(pos.x, pos.y, size.x, size.y, angle, this.color.rgbaInt());
640
+ else if (!particleTileEmpty)
641
+ {
642
+ const texture = tileInfo.textureInfo.glTexture;
643
+ glActiveTexture === texture || glSetTexture(texture); // bound again only if a draw between changed it
644
+ glDraw(pos.x, pos.y, this.mirror ? -size.x : size.x, size.y, angle,
645
+ particleTileU0, particleTileV0, particleTileU1, particleTileV1, this.color.rgbaInt());
646
+ }
647
+ }
648
+ else
649
+ drawTile(pos, size, this.tileInfo, this.color, angle, this.mirror, undefined, false, false);
581
650
  additive && setAdditiveBlendMode(false);
582
651
  debugParticles && debugRect(pos, size, '#f005', 0, angle, false, false);
583
652
  }
@@ -26,6 +26,19 @@ let glCanvas;
26
26
  * @memberof WebGL */
27
27
  let glContext;
28
28
 
29
+ /** The largest texture this device makes, in pixels across, 0 until WebGL starts; at least 2048 with WebGL2
30
+ * @type {number}
31
+ * @memberof WebGL */
32
+ let glMaxTextureSize = 0;
33
+
34
+ /** A texture size this device can make: the size asked for, or the largest it supports when that is smaller
35
+ * - The engine sizes the textures it makes itself through this, the shadow maps and the like, so a size a device
36
+ * does not have falls back instead of failing
37
+ * @param {number} size - Pixels across
38
+ * @return {number}
39
+ * @memberof WebGL */
40
+ function glClampTextureSize(size) { return glMaxTextureSize ? min(size, glMaxTextureSize) : size; }
41
+
29
42
  /** Should WebGL be setup with anti-aliasing? must be set before calling engineInit
30
43
  * @type {boolean}
31
44
  * @memberof WebGL */
@@ -115,7 +128,7 @@ function glInit(rootElement)
115
128
  // startup webgl, and make the textures of any texture infos made before it
116
129
  initWebGL();
117
130
  for (const info of glTextureInfos)
118
- info.glTexture ||= glCreateTexture(info.image, info.wrap);
131
+ info.glTexture ||= glCreateTexture(info.image, info.wrap, info.pixelated);
119
132
 
120
133
  // setup context lost and restore handlers
121
134
  glCanvas.addEventListener('webglcontextlost', (e)=>
@@ -155,7 +168,7 @@ function glInit(rootElement)
155
168
  glPremultipliedTextures = new WeakSet; // the tile layers draw into their new textures again below
156
169
  initWebGL();
157
170
  for (const info of glTextureInfos)
158
- info.glTexture = glCreateTexture(info.image, info.wrap);
171
+ info.glTexture = glCreateTexture(info.image, info.wrap, info.pixelated);
159
172
  pluginList.forEach(plugin=>plugin.glContextRestored?.());
160
173
 
161
174
  // a tile layer drawn on the GPU only had its tiles in the lost texture, it draws them again
@@ -165,6 +178,8 @@ function glInit(rootElement)
165
178
 
166
179
  function initWebGL()
167
180
  {
181
+ glMaxTextureSize = glContext.getParameter(glContext.MAX_TEXTURE_SIZE) | 0;
182
+
168
183
  // setup instanced rendering shader program
169
184
  glShader = glCreateProgram(gl_VERTEX_SOURCE,
170
185
  '#version 300 es\n' + // specify GLSL ES version
@@ -488,9 +503,10 @@ function glShaderProgram(shader)
488
503
  * Restores the active texture when done
489
504
  * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} [image]
490
505
  * @param {boolean|Array<number>} [wrap] - true for REPEAT, false for CLAMP_TO_EDGE, or the WebGL modes across and down
506
+ * @param {boolean} [pixelated] - Hard edged or smooth, undefined follows tilesPixelated
491
507
  * @return {WebGLTexture}
492
508
  * @memberof WebGL */
493
- function glCreateTexture(image, wrap=false)
509
+ function glCreateTexture(image, wrap=false, pixelated=tilesPixelated)
494
510
  {
495
511
  if (!glContext) return;
496
512
 
@@ -499,10 +515,10 @@ function glCreateTexture(image, wrap=false)
499
515
  let mipMap = false;
500
516
  if (image?.width)
501
517
  {
502
- glSetTextureData(texture, image);
518
+ glSetTextureData(texture, image, pixelated);
503
519
  glContext.bindTexture(glContext.TEXTURE_2D, texture);
504
520
  // WebGL2 makes mipmaps at any size, a texture that becomes a render target keeps them only at powers of two
505
- mipMap = !tilesPixelated;
521
+ mipMap = !pixelated;
506
522
  if (mipMap && !(isPowerOfTwo(image.width) && isPowerOfTwo(image.height)))
507
523
  glMipmapsUntilTarget.add(texture);
508
524
  }
@@ -515,7 +531,7 @@ function glCreateTexture(image, wrap=false)
515
531
  }
516
532
 
517
533
  // set texture filtering
518
- const magFilter = tilesPixelated ? glContext.NEAREST : glContext.LINEAR;
534
+ const magFilter = pixelated ? glContext.NEAREST : glContext.LINEAR;
519
535
  const minFilter = mipMap ? glContext.LINEAR_MIPMAP_LINEAR : magFilter;
520
536
  glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MAG_FILTER, magFilter);
521
537
  glContext.texParameteri(glContext.TEXTURE_2D, glContext.TEXTURE_MIN_FILTER, minFilter);
@@ -546,8 +562,9 @@ function glDeleteTexture(texture)
546
562
  /** Set WebGL texture data from an image, restores the active texture when done
547
563
  * @param {WebGLTexture} texture
548
564
  * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap} image
565
+ * @param {boolean} [pixelated] - Hard edged or smooth, undefined follows tilesPixelated
549
566
  * @memberof WebGL */
550
- function glSetTextureData(texture, image)
567
+ function glSetTextureData(texture, image, pixelated=tilesPixelated)
551
568
  {
552
569
  if (!glContext) return;
553
570
 
@@ -565,7 +582,7 @@ function glSetTextureData(texture, image)
565
582
  }
566
583
  // smooth filtering mixes a texel with its see through neighbors, right only for premultiplied color, or the
567
584
  // edges go dark; pixel art is sampled a texel at a time, and uploads straight color as it always has
568
- const premultiply = !tilesPixelated;
585
+ const premultiply = !pixelated;
569
586
  glContext.pixelStorei(glContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiply);
570
587
  glContext.texImage2D(glContext.TEXTURE_2D, 0, glContext.RGBA, glContext.RGBA, glContext.UNSIGNED_BYTE, image);
571
588
  glContext.pixelStorei(glContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
@@ -596,9 +613,9 @@ function glRegisterTextureInfo(textureInfo)
596
613
 
597
614
  // create or set the texture data
598
615
  if (textureInfo.glTexture)
599
- glSetTextureData(textureInfo.glTexture, textureInfo.image);
616
+ glSetTextureData(textureInfo.glTexture, textureInfo.image, textureInfo.pixelated);
600
617
  else
601
- textureInfo.glTexture = glCreateTexture(textureInfo.image, textureInfo.wrap);
618
+ textureInfo.glTexture = glCreateTexture(textureInfo.image, textureInfo.wrap, textureInfo.pixelated);
602
619
  }
603
620
 
604
621
  /** Internal: tells WebGL to destroy the glTexture and stop tracking it, TextureInfo calls it