thrunium 1.2.0-rc.2 → 1.2.0-rc.4

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/dist/thrunium.js CHANGED
@@ -1,11 +1,37 @@
1
- /*! THRUNIUM v1.2.0-rc.2 | (c) Infobits ApS | MIT License */
1
+ /*! THRUNIUM v1.2.0-rc.4 | (c) Infobits ApS | MIT License */
2
2
  "use strict";
3
3
  (() => {
4
4
  var __defProp = Object.defineProperty;
5
+ var __defProps = Object.defineProperties;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __typeError = (msg) => {
11
+ throw TypeError(msg);
12
+ };
13
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __spreadValues = (a, b) => {
15
+ for (var prop in b || (b = {}))
16
+ if (__hasOwnProp.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ if (__getOwnPropSymbols)
19
+ for (var prop of __getOwnPropSymbols(b)) {
20
+ if (__propIsEnum.call(b, prop))
21
+ __defNormalProp(a, prop, b[prop]);
22
+ }
23
+ return a;
24
+ };
25
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
5
26
  var __export = (target, all) => {
6
27
  for (var name in all)
7
28
  __defProp(target, name, { get: all[name], enumerable: true });
8
29
  };
30
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
31
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
32
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
34
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
35
 
10
36
  // src/namespace.ts
11
37
  window.THRUNIUM || (window.THRUNIUM = {});
@@ -60,8 +86,629 @@
60
86
  }
61
87
  }
62
88
 
89
+ // src/input.ts
90
+ var InputSet = class {
91
+ constructor() {
92
+ this.down = /* @__PURE__ */ new Set();
93
+ /** What went down since the previous frame. */
94
+ this.pressed = /* @__PURE__ */ new Set();
95
+ /** What came up since the previous frame. */
96
+ this.released = /* @__PURE__ */ new Set();
97
+ }
98
+ /**
99
+ * What is down right now. Read-only.
100
+ *
101
+ * @example
102
+ * ```js
103
+ * var game = new THRUNIUM.Game(400, 400);
104
+ * game.keys.held.has('KeyW');
105
+ * game.mouse.held.has(0);
106
+ * ```
107
+ */
108
+ get held() {
109
+ return this.down;
110
+ }
111
+ /**
112
+ * Marks `key` as down. A repeat while it is already down (keyboard auto-repeat) is not a new press.
113
+ *
114
+ * @internal
115
+ */
116
+ press(key) {
117
+ if (this.down.has(key)) return;
118
+ this.down.add(key);
119
+ this.pressed.add(key);
120
+ }
121
+ /**
122
+ * Marks `key` as up. Releasing something that was not down does nothing.
123
+ *
124
+ * @internal
125
+ */
126
+ release(key) {
127
+ if (!this.down.delete(key)) return;
128
+ this.released.add(key);
129
+ }
130
+ /**
131
+ * Releases everything that is held, for example when the window loses focus.
132
+ *
133
+ * @internal
134
+ */
135
+ releaseAll() {
136
+ for (const key of [...this.down]) this.release(key);
137
+ }
138
+ /**
139
+ * Clears the "was pressed" and "was released" sets. The game loop calls it at the end of every frame.
140
+ *
141
+ * @internal
142
+ */
143
+ endFrame() {
144
+ this.pressed.clear();
145
+ this.released.clear();
146
+ }
147
+ };
148
+ var Keys = class extends InputSet {
149
+ /**
150
+ * Returns `true` while the key is held. All held keys are released when the window loses focus, so a key never sticks after alt-tab.
151
+ * @param code The `KeyboardEvent.code` of the key.
152
+ * @example
153
+ * ```js
154
+ * if (game.keys.isDown('ArrowLeft')) player.x -= 3;
155
+ * ```
156
+ */
157
+ isDown(code) {
158
+ return this.held.has(code);
159
+ }
160
+ /**
161
+ * Returns `true` for the one frame after the key went down. Holding the key does not repeat it.
162
+ * @param code The `KeyboardEvent.code` of the key.
163
+ * @example
164
+ * ```js
165
+ * if (game.keys.wasPressed('Space')) shoot();
166
+ * ```
167
+ */
168
+ wasPressed(code) {
169
+ return this.pressed.has(code);
170
+ }
171
+ /**
172
+ * Returns `true` for the one frame after the key came up.
173
+ * @param code The `KeyboardEvent.code` of the key.
174
+ * @example
175
+ * ```js
176
+ * if (game.keys.wasReleased('Space')) stopCharging();
177
+ * ```
178
+ */
179
+ wasReleased(code) {
180
+ return this.released.has(code);
181
+ }
182
+ };
183
+ var Mouse = class extends InputSet {
184
+ constructor() {
185
+ super(...arguments);
186
+ /**
187
+ * Pointer x in game coordinates, the same as `game.mouseX`.
188
+ *
189
+ * @example
190
+ * ```js
191
+ * var game = new THRUNIUM.Game(400, 400);
192
+ * game.mouse.x;
193
+ * ```
194
+ */
195
+ this.x = 0;
196
+ /**
197
+ * Pointer y in game coordinates, the same as `game.mouseY`.
198
+ *
199
+ * @example
200
+ * ```js
201
+ * var game = new THRUNIUM.Game(400, 400);
202
+ * game.mouse.y;
203
+ * ```
204
+ */
205
+ this.y = 0;
206
+ }
207
+ /**
208
+ * Returns `true` while the button is held.
209
+ * @param button The button number, `0` (left, and touch) by default.
210
+ * @example
211
+ * ```js
212
+ * if (game.mouse.isDown()) drag(game.mouse.x, game.mouse.y);
213
+ * ```
214
+ */
215
+ isDown(button = 0) {
216
+ return this.held.has(button);
217
+ }
218
+ /**
219
+ * Returns `true` for the one frame after the button went down.
220
+ * @param button The button number, `0` (left, and touch) by default.
221
+ * @example
222
+ * ```js
223
+ * if (game.mouse.wasPressed()) fireAt(game.mouse.x, game.mouse.y);
224
+ * ```
225
+ */
226
+ wasPressed(button = 0) {
227
+ return this.pressed.has(button);
228
+ }
229
+ /**
230
+ * Returns `true` for the one frame after the button came up.
231
+ * @param button The button number, `0` (left, and touch) by default.
232
+ * @example
233
+ * ```js
234
+ * if (game.mouse.wasReleased()) drop();
235
+ * ```
236
+ */
237
+ wasReleased(button = 0) {
238
+ return this.released.has(button);
239
+ }
240
+ };
241
+
242
+ // src/timers.ts
243
+ var ScheduledTimer = class {
244
+ constructor(timers, due, interval, fn, owner) {
245
+ this.timers = timers;
246
+ this.due = due;
247
+ this.interval = interval;
248
+ this.fn = fn;
249
+ this.owner = owner;
250
+ /** Cleared by `Timers` when the timer is cancelled or has finished. */
251
+ this.scheduled = true;
252
+ }
253
+ get active() {
254
+ return this.scheduled;
255
+ }
256
+ cancel() {
257
+ this.timers.remove(this);
258
+ }
259
+ };
260
+ var Timers = class {
261
+ constructor() {
262
+ /** Game seconds advanced so far. */
263
+ this.now = 0;
264
+ /** Active timers in creation order; finished and cancelled ones are removed. */
265
+ this.list = [];
266
+ }
267
+ /** Calls `fn` once, `s` game seconds from now. `owner` is the scene it belongs to, or `null`. */
268
+ after(s, fn, owner) {
269
+ return this.add(new ScheduledTimer(this, this.now + s, null, fn, owner));
270
+ }
271
+ /** Calls `fn` every `s` game seconds, at most once per `advance`. */
272
+ every(s, fn, owner) {
273
+ return this.add(new ScheduledTimer(this, this.now + s, s, fn, owner));
274
+ }
275
+ /** Moves game time on by `dt` seconds and fires the timers that came due, oldest first. */
276
+ advance(dt) {
277
+ this.now += dt;
278
+ for (const t of this.list.slice()) {
279
+ if (!t.scheduled || t.due > this.now) continue;
280
+ if (t.interval === null) {
281
+ this.remove(t);
282
+ } else if (t.interval > 0) {
283
+ t.due += (Math.floor((this.now - t.due) / t.interval) + 1) * t.interval;
284
+ if (t.due <= this.now) t.due = this.now + t.interval;
285
+ } else {
286
+ t.due = this.now;
287
+ }
288
+ t.fn();
289
+ }
290
+ }
291
+ /** Cancels every timer that belongs to `owner`. */
292
+ cancelOwner(owner) {
293
+ this.list = this.list.filter((t) => {
294
+ if (t.owner !== owner) return true;
295
+ t.scheduled = false;
296
+ return false;
297
+ });
298
+ }
299
+ /** Number of active timers. */
300
+ get count() {
301
+ return this.list.length;
302
+ }
303
+ /** Unschedules `t`; does nothing if it is not scheduled. */
304
+ remove(t) {
305
+ if (!t.scheduled) return;
306
+ t.scheduled = false;
307
+ this.list.splice(this.list.indexOf(t), 1);
308
+ }
309
+ add(t) {
310
+ this.list.push(t);
311
+ return t;
312
+ }
313
+ };
314
+
315
+ // src/fonts.ts
316
+ function googleFamilies(url) {
317
+ var _a2;
318
+ const query = (_a2 = url.split("?")[1]) != null ? _a2 : "";
319
+ const families = [];
320
+ for (const part of query.split("&")) {
321
+ if (!part.startsWith("family=")) continue;
322
+ const name = decodeURIComponent(part.slice("family=".length).split(":")[0].replace(/\+/g, " "));
323
+ if (name) families.push(name);
324
+ }
325
+ return families;
326
+ }
327
+ function loadFonts(specs, manifest, built, dev = false) {
328
+ let settled = 0;
329
+ const sources = [];
330
+ const pending = [];
331
+ const track = (label, loaders) => {
332
+ pending.push(
333
+ Promise.allSettled(loaders).then((results) => {
334
+ for (const r of results) {
335
+ if (r.status === "rejected") console.warn(`Font "${label}" failed to load; using the fallback font.`, r.reason);
336
+ }
337
+ settled++;
338
+ })
339
+ );
340
+ };
341
+ const addFace = (family, src, descriptors) => {
342
+ const face = new FontFace(family, `url(${src})`, descriptors);
343
+ return face.load().then(() => {
344
+ document.fonts.add(face);
345
+ return face;
346
+ });
347
+ };
348
+ for (const spec of specs) {
349
+ if (typeof spec === "object" && "family" in spec) {
350
+ sources.push({ family: spec.family, source: "file" });
351
+ track(spec.family, [addFace(spec.family, spec.src, { weight: spec.weight, style: spec.style })]);
352
+ continue;
353
+ }
354
+ const url = typeof spec === "string" ? spec : spec.url;
355
+ const cdn = typeof spec === "object" && spec.cdn === true;
356
+ const files = cdn ? void 0 : manifest == null ? void 0 : manifest[url];
357
+ const families = googleFamilies(url);
358
+ if (files) {
359
+ for (const f of files) sources.push({ family: f.family, source: "bundled" });
360
+ track(
361
+ families.join(", ") || url,
362
+ files.map((f) => addFace(f.family, f.src, { weight: f.weight, style: f.style, unicodeRange: f.unicodeRange }))
363
+ );
364
+ continue;
365
+ }
366
+ if (!cdn && built) {
367
+ console.warn(
368
+ dev ? `Font ${url} is loaded from Google; thrunium dev could not download it or did not find it in the bundle.` : `Font ${url} is loaded from Google; it was not found when the game was built.`
369
+ );
370
+ }
371
+ for (const family of families) sources.push({ family, source: "google" });
372
+ const link = document.createElement("link");
373
+ link.rel = "stylesheet";
374
+ link.href = url;
375
+ const sheet = new Promise((resolve, reject) => {
376
+ link.addEventListener("load", () => resolve());
377
+ link.addEventListener("error", () => reject(new Error(`could not load ${url}`)));
378
+ });
379
+ document.head.appendChild(link);
380
+ const ready2 = sheet.then(
381
+ () => Promise.all(
382
+ families.map(
383
+ (family) => document.fonts.load(`1em "${family}"`).then((found) => {
384
+ if (found.length === 0) throw new Error(`no font face found for "${family}"`);
385
+ })
386
+ )
387
+ )
388
+ );
389
+ track(families.join(", ") || url, [ready2]);
390
+ }
391
+ return {
392
+ total: specs.length,
393
+ loaded: () => settled,
394
+ done: Promise.all(pending).then(() => void 0),
395
+ sources
396
+ };
397
+ }
398
+
399
+ // src/internals.ts
400
+ var internals = /* @__PURE__ */ new WeakMap();
401
+ function setInternals(game3, value) {
402
+ internals.set(game3, value);
403
+ }
404
+ function getInternals(game3) {
405
+ const value = internals.get(game3);
406
+ if (!value) throw new Error("THRUNIUM: not a Game made by this engine.");
407
+ return value;
408
+ }
409
+
410
+ // src/debug.ts
411
+ var GRAPH_FRAMES = 120;
412
+ var TEXT_INTERVAL = 250;
413
+ var GRAPH_MAX_MS = 50;
414
+ var GRAPH_HEIGHT = 30;
415
+ var Debug = class {
416
+ /** @internal */
417
+ constructor(game3) {
418
+ /**
419
+ * Whether the panel is shown while `enabled`. Starts `true`; the backquote key toggles it.
420
+ *
421
+ * @example
422
+ * ```js
423
+ * var game = new THRUNIUM.Game(400, 400);
424
+ * game.debug.visible = false; // starts hidden; press ` to show it
425
+ * ```
426
+ */
427
+ this.visible = true;
428
+ this.watches = /* @__PURE__ */ new Map();
429
+ this.frameTimes = [];
430
+ this.lastFrame = 0;
431
+ this.lastText = -Infinity;
432
+ this.root = null;
433
+ this.game = game3;
434
+ }
435
+ /**
436
+ * `true` shows the panel (and lets the backquote key hide it); `false` removes it. Until you set it, it is `true` under `thrunium dev` and `false` otherwise. Setting it in your code always wins.
437
+ *
438
+ * @example
439
+ * ```js
440
+ * var game = new THRUNIUM.Game(400, 400);
441
+ * game.debug.enabled = true;
442
+ * ```
443
+ */
444
+ get enabled() {
445
+ var _a2;
446
+ return (_a2 = this.override) != null ? _a2 : typeof window !== "undefined" && window.THRUNIUM_DEV === true;
447
+ }
448
+ set enabled(value) {
449
+ this.override = value;
450
+ }
451
+ /**
452
+ * Adds a line `label: value` to the panel; `read` is called to get the value. Watching a label again replaces its function.
453
+ *
454
+ * @param label The text before the value.
455
+ * @param read Returns the value to show.
456
+ * @example
457
+ * ```js
458
+ * game.debug.watch('meteors', function() { return meteors.length; });
459
+ * ```
460
+ */
461
+ watch(label, read) {
462
+ this.watches.set(label, read);
463
+ this.lastText = -Infinity;
464
+ }
465
+ /**
466
+ * Removes the line added by `watch(label, ...)`.
467
+ *
468
+ * @param label The label passed to `watch`.
469
+ * @example
470
+ * ```js
471
+ * game.debug.unwatch('meteors');
472
+ * ```
473
+ */
474
+ unwatch(label) {
475
+ this.watches.delete(label);
476
+ this.lastText = -Infinity;
477
+ }
478
+ /**
479
+ * Called by the game loop once per frame, after the game has drawn.
480
+ *
481
+ * @internal
482
+ */
483
+ update() {
484
+ var _a2;
485
+ if (!this.enabled) {
486
+ this.remove();
487
+ return;
488
+ }
489
+ if (getInternals(this.game).keys.wasPressed("Backquote")) this.visible = !this.visible;
490
+ const now = performance.now();
491
+ if (this.lastFrame) this.frameTimes.push(now - this.lastFrame);
492
+ if (this.frameTimes.length > GRAPH_FRAMES) this.frameTimes.shift();
493
+ this.lastFrame = now;
494
+ const root = (_a2 = this.root) != null ? _a2 : this.build();
495
+ root.style.display = this.visible ? "block" : "none";
496
+ if (!this.visible) return;
497
+ this.drawGraph();
498
+ this.stepButton.style.display = this.game.paused ? "inline-block" : "none";
499
+ this.pauseButton.textContent = this.game.paused ? "resume" : "pause";
500
+ this.pauseButton.title = this.game.paused ? "Resume scenes and timers" : "Pause scenes and timers";
501
+ if (now - this.lastText >= TEXT_INTERVAL) {
502
+ this.lastText = now;
503
+ this.info.textContent = this.lines().join("\n");
504
+ }
505
+ }
506
+ /** Removes the panel; the next enabled frame builds a fresh one. */
507
+ remove() {
508
+ var _a2;
509
+ (_a2 = this.root) == null ? void 0 : _a2.remove();
510
+ this.root = null;
511
+ this.frameTimes = [];
512
+ this.lastFrame = 0;
513
+ }
514
+ /** Creates the panel elements and appends them to the page. */
515
+ build() {
516
+ const root = document.createElement("div");
517
+ root.id = "thrunium-debug";
518
+ root.style.cssText = "position:fixed;left:0;top:0;z-index:2147483646;padding:6px;margin:0;pointer-events:none;background:rgba(0,0,0,0.7);color:#fff;font:11px/1.3 ui-monospace,Menlo,Consolas,monospace;";
519
+ this.graph = document.createElement("div");
520
+ this.graph.style.cssText = `display:flex;align-items:flex-end;width:${GRAPH_FRAMES}px;height:${GRAPH_HEIGHT}px;margin-bottom:4px;`;
521
+ this.info = document.createElement("pre");
522
+ this.info.style.cssText = "margin:0;font:inherit;white-space:pre;";
523
+ const controls = document.createElement("div");
524
+ controls.style.cssText = "margin-top:4px;";
525
+ this.pauseButton = this.makeButton("pause", "Pause scenes and timers", () => {
526
+ this.game.paused = !this.game.paused;
527
+ this.lastText = -Infinity;
528
+ });
529
+ this.stepButton = this.makeButton("step", "Run scenes and timers for one frame (1/60 s)", () => {
530
+ this.game.stepOnce = true;
531
+ });
532
+ this.stepButton.style.display = "none";
533
+ controls.append(this.pauseButton, this.stepButton);
534
+ root.append(this.graph, this.info, controls);
535
+ document.body.appendChild(root);
536
+ this.root = root;
537
+ return root;
538
+ }
539
+ /**
540
+ * A small button that accepts pointer events while the rest of the panel does not. It never
541
+ * keeps keyboard focus: a focused button would be clicked again by Space or Enter while the
542
+ * developer plays, toggling pause.
543
+ */
544
+ makeButton(label, title, onClick) {
545
+ const b = document.createElement("button");
546
+ b.type = "button";
547
+ b.textContent = label;
548
+ b.title = title;
549
+ b.style.cssText = "pointer-events:auto;margin-right:4px;font:inherit;padding:1px 6px;cursor:pointer;";
550
+ b.addEventListener("mousedown", (e) => e.preventDefault());
551
+ b.addEventListener("click", () => {
552
+ onClick();
553
+ b.blur();
554
+ });
555
+ return b;
556
+ }
557
+ /** Sets one bar per recorded frame time; bars are created on demand, never more than the graph length. */
558
+ drawGraph() {
559
+ const bars = this.graph.children;
560
+ while (bars.length < this.frameTimes.length) {
561
+ const bar = document.createElement("div");
562
+ bar.setAttribute("data-bar", "");
563
+ bar.style.cssText = "width:1px;background:#6f6;";
564
+ this.graph.appendChild(bar);
565
+ }
566
+ this.frameTimes.forEach((ms, i) => {
567
+ const bar = bars[i];
568
+ bar.style.height = `${Math.max(1, Math.min(ms / GRAPH_MAX_MS, 1) * GRAPH_HEIGHT)}px`;
569
+ bar.style.background = ms > 33 ? "#f66" : "#6f6";
570
+ });
571
+ }
572
+ /** The text lines for the current frame. */
573
+ lines() {
574
+ var _a2;
575
+ const g = this.game;
576
+ const own = getInternals(g);
577
+ const f = (n) => n.toFixed(2);
578
+ const state = g.state;
579
+ const kind = typeof g.states[state] === "object" ? "scene" : "function";
580
+ const fonts = ((_a2 = g.fontStatus) == null ? void 0 : _a2.sources.map((s) => `${s.family} (${s.source})`).join(", ")) || "none";
581
+ const lines = [
582
+ `${Math.round(g.fps)} fps`,
583
+ `state: ${state} (${kind})`,
584
+ `paused: ${g.paused} dt: ${f(own.dt())} speed: ${f(g.runSpeed)} time: ${f(own.time())}`,
585
+ `timers: ${g.timerCount}`,
586
+ `assets: ${g.loadedAssets}/${g.assetsToLoad}${g.failedAssets > 0 ? `, failed ${g.failedAssets}` : ""}`,
587
+ `fonts: ${fonts}`,
588
+ `mouse: ${Math.round(g.mouseX)}, ${Math.round(g.mouseY)} buttons: ${[...own.mouse.held].join(",") || "-"}`,
589
+ `keys: ${[...own.keys.held].join(",") || "-"}`,
590
+ `canvas: ${g.width}x${g.height} scale: ${f(g.scale)}`,
591
+ `thrunium ${"1.2.0-rc.4"}`
592
+ ];
593
+ for (const [label, read] of this.watches) {
594
+ let value;
595
+ try {
596
+ value = String(read());
597
+ } catch (e) {
598
+ value = "(error)";
599
+ }
600
+ lines.push(`${label}: ${value}`);
601
+ }
602
+ return lines;
603
+ }
604
+ };
605
+
606
+ // src/font-string.ts
607
+ var GENERIC_FAMILIES = /* @__PURE__ */ new Set([
608
+ "serif",
609
+ "sans-serif",
610
+ "monospace",
611
+ "cursive",
612
+ "fantasy",
613
+ "system-ui",
614
+ "ui-serif",
615
+ "ui-sans-serif",
616
+ "ui-monospace",
617
+ "ui-rounded",
618
+ "math",
619
+ "emoji",
620
+ "fangsong"
621
+ ]);
622
+ function quoteFamily(family) {
623
+ const f = family.trim();
624
+ if (/^(["']).*\1$/.test(f) || f.includes(",") || GENERIC_FAMILIES.has(f.toLowerCase())) return family;
625
+ return '"' + f.replace(/[\\"]/g, "\\$&") + '"';
626
+ }
627
+ function fontString(weight, size, family) {
628
+ const px = typeof size === "number" ? size + "px" : size;
629
+ return (weight ? weight + " " : "") + px + " " + quoteFamily(family);
630
+ }
631
+
632
+ // src/button.ts
633
+ var Button = class {
634
+ /** @internal Use `game.button()`. */
635
+ constructor(game3, drawn, text, x, y, options = {}) {
636
+ /** The clickable box as of the last `draw()`, in game coordinates. */
637
+ this.box = { left: 0, top: 0, right: 0, bottom: 0 };
638
+ this.game = game3;
639
+ this.drawn = drawn;
640
+ this.text = text;
641
+ this.x = x;
642
+ this.y = y;
643
+ this.options = options;
644
+ }
645
+ /** `true` while the pointer is over a button that was drawn in the previous frame too. */
646
+ get hovered() {
647
+ if (!this.drawn.previous.has(this)) return false;
648
+ const { x, y } = getInternals(this.game).mouse;
649
+ const b = this.box;
650
+ return x >= b.left && x <= b.right && y >= b.top && y <= b.bottom;
651
+ }
652
+ /** `true` for the one frame in which the left button (or a touch) came up over a button that was drawn in the previous frame too. */
653
+ get clicked() {
654
+ return this.hovered && getInternals(this.game).mouse.wasReleased(0);
655
+ }
656
+ /**
657
+ * Draws the button, and keeps it clickable: call it every frame, even while the game is paused. While the pointer is over it, the text uses `hoverColor`, the canvas cursor becomes a pointer and `onHover` is called.
658
+ *
659
+ * @example
660
+ * ```js
661
+ * play.draw();
662
+ * ```
663
+ */
664
+ draw() {
665
+ var _a2;
666
+ const game3 = this.game;
667
+ const o = this.options;
668
+ this.measure();
669
+ this.drawn.current.add(this);
670
+ const hovered = this.hovered;
671
+ game3.drawText(this.text, this.x, this.y, hovered && o.hoverColor ? __spreadProps(__spreadValues({}, o), { color: o.hoverColor }) : o);
672
+ if (hovered) {
673
+ game3.canvas.style.cursor = "pointer";
674
+ (_a2 = o.onHover) == null ? void 0 : _a2.call(o, this);
675
+ }
676
+ }
677
+ /** Works out the clickable box from the text's measured size, placed the way `drawText` places the text. */
678
+ measure() {
679
+ var _a2, _b2, _c, _d, _e;
680
+ const { ctx } = this.game;
681
+ const o = this.options;
682
+ const padding = (_a2 = o.padding) != null ? _a2 : 8;
683
+ const size = (_b2 = o.size) != null ? _b2 : this.game.textSize;
684
+ const baseline = (_c = o.baseline) != null ? _c : "alphabetic";
685
+ ctx.save();
686
+ ctx.font = fontString(o.weight, size, (_d = o.font) != null ? _d : this.game.font);
687
+ if (o.baseline) ctx.textBaseline = o.baseline;
688
+ const m = ctx.measureText(this.text);
689
+ ctx.restore();
690
+ const width = m.width;
691
+ const align = (_e = o.align) != null ? _e : "left";
692
+ const left = align === "center" ? this.x - width / 2 : align === "right" || align === "end" ? this.x - width : this.x;
693
+ let top;
694
+ let bottom;
695
+ if (typeof m.actualBoundingBoxAscent === "number" && typeof m.actualBoundingBoxDescent === "number") {
696
+ top = this.y - m.actualBoundingBoxAscent;
697
+ bottom = this.y + m.actualBoundingBoxDescent;
698
+ } else if (typeof m.fontBoundingBoxAscent === "number" && typeof m.fontBoundingBoxDescent === "number") {
699
+ top = this.y - m.fontBoundingBoxAscent;
700
+ bottom = this.y + m.fontBoundingBoxDescent;
701
+ } else {
702
+ const px = typeof size === "number" ? size : parseFloat(size) || 0;
703
+ top = baseline === "middle" ? this.y - px / 2 : baseline === "top" || baseline === "hanging" ? this.y : this.y - px;
704
+ bottom = top + px;
705
+ }
706
+ this.box = { left: left - padding, top: top - padding, right: left + width + padding, bottom: bottom + padding };
707
+ }
708
+ };
709
+
63
710
  // src/game.ts
64
- var _a;
711
+ var _a, _keys, _mouse, _debug, _timers, _drawnButtons, _time, _dt, _shownTime, _shownDt, _Game_instances, showTime_fn, showDt_fn;
65
712
  _a = Symbol.toStringTag;
66
713
  var Game = class {
67
714
  /**
@@ -74,7 +721,26 @@
74
721
  * ```
75
722
  */
76
723
  constructor(width, height) {
724
+ __privateAdd(this, _Game_instances);
77
725
  this[_a] = "THRUNIUM.Game";
726
+ // The engine's own state. The public `keys`, `mouse` and `debug` start out as these objects,
727
+ // and `time` and `dt` mirror these counters, but a v1 game may use those names (or
728
+ // `timers`, `drawnButtons`) for its own data. So the loop, the listeners, timers, buttons
729
+ // and the debug menu only ever use the private ones, and overwriting a public one only
730
+ // changes what the game's own code sees. Declared first: the public fields below start
731
+ // from them.
732
+ __privateAdd(this, _keys, new Keys());
733
+ __privateAdd(this, _mouse, new Mouse());
734
+ __privateAdd(this, _debug, new Debug(this));
735
+ __privateAdd(this, _timers, new Timers());
736
+ /** The buttons drawn this frame and last frame; rotated by `endFrame()`. */
737
+ __privateAdd(this, _drawnButtons, { current: /* @__PURE__ */ new Set(), previous: /* @__PURE__ */ new Set() });
738
+ /** Engine game time and step; see `time` and `dt`. */
739
+ __privateAdd(this, _time, 0);
740
+ __privateAdd(this, _dt, 0);
741
+ /** What the engine last wrote to the public `time` and `dt`, or `null` once the game assigned its own value there. */
742
+ __privateAdd(this, _shownTime, 0);
743
+ __privateAdd(this, _shownDt, 0);
78
744
  /**
79
745
  * Density of real canvas pixels per game pixel (device pixel ratio times `fitScale`). Adjusted automatically to keep the game sharp. Read-only.
80
746
  *
@@ -110,6 +776,28 @@
110
776
  * ```
111
777
  */
112
778
  this.delta = 0;
779
+ /**
780
+ * Seconds the scenes advanced by in the last frame: `delta` capped at `0.1`, so a long hitch does not make things jump. Scenes get it as `update(dt)`; timers and `time` use it too. Updated every frame; if your code assigns its own value, the engine leaves it alone from then on and keeps its own count.
781
+ *
782
+ * @category Scenes
783
+ * @example
784
+ * ```js
785
+ * var game = new THRUNIUM.Game(400, 400);
786
+ * game.dt;
787
+ * ```
788
+ */
789
+ this.dt = 0;
790
+ /**
791
+ * Game time in seconds: the sum of `dt` over the frames that were not paused, from the end of the loading screen. Timers run on the same clock. Updated every frame; if your code assigns its own value (a game written before 1.2.0 may keep its own `time`), the engine leaves it alone from then on, and its timers keep their own clock.
792
+ *
793
+ * @category Scenes
794
+ * @example
795
+ * ```js
796
+ * var game = new THRUNIUM.Game(400, 400);
797
+ * game.drawText('Time: ' + Math.floor(game.time), 10, 30);
798
+ * ```
799
+ */
800
+ this.time = 0;
113
801
  /**
114
802
  * Frames per second of the game loop. Updated every frame. Read-only: an overwritten value is replaced on the next frame.
115
803
  *
@@ -123,7 +811,7 @@
123
811
  this.fps = 0;
124
812
  // Before 1.2.0 this was the string (fps / 60).toFixed(2); it is now a number.
125
813
  /**
126
- * Current frames per second divided by 60, as a number with two decimals (for example `1`). Use it to correct game speed on devices that run below 60 fps. Updated every frame. Read-only.
814
+ * Current frames per second divided by 60, as a number with two decimals (for example `1`). Use it to correct game speed on devices that run below 60 fps. Starts at `1`, so it is safe to use from the first frame, and is updated every frame from the second. Read-only.
127
815
  *
128
816
  * @category Variables
129
817
  * @example
@@ -132,7 +820,7 @@
132
820
  * game.runSpeed;
133
821
  * ```
134
822
  */
135
- this.runSpeed = 0;
823
+ this.runSpeed = 1;
136
824
  /**
137
825
  * Unix timestamp in milliseconds of the last time the game loop ran, or `null` before the first frame. Updated every frame. Read-only.
138
826
  *
@@ -166,6 +854,18 @@
166
854
  * ```
167
855
  */
168
856
  this.showFPS = false;
857
+ /**
858
+ * The debug menu: a panel over the page with fps, a frame-time graph, state, timers, assets, fonts, input and your own `watch` lines. It is off unless you set `game.debug.enabled = true`, except under `thrunium dev` where it starts on. Press the backquote key to show or hide it.
859
+ *
860
+ * @category Variables
861
+ * @example
862
+ * ```js
863
+ * var game = new THRUNIUM.Game(400, 400);
864
+ * game.debug.enabled = true;
865
+ * game.debug.watch('score', function() { return score; });
866
+ * ```
867
+ */
868
+ this.debug = __privateGet(this, _debug);
169
869
  /**
170
870
  * Free-form name for the game. The engine does not use it, so it is available for your own bookkeeping, for example to prefix saved data. Default is an empty string.
171
871
  *
@@ -200,16 +900,43 @@
200
900
  */
201
901
  this.mouseY = 0;
202
902
  /**
203
- * Name of the state the game loop is currently running (a key of `states`). It starts as the built-in loading screen, `"startup"`, and switches to `startState` once everything has loaded. Assign a new name to change state.
903
+ * The keyboard: which keys are held, and which went down or up since the previous frame. Keys are `KeyboardEvent.code` values such as `'KeyW'`. The engine listens for you, and your `keydown` and `keyup` handlers still run.
204
904
  *
205
- * @category Variables
905
+ * @category Input
906
+ * @example
907
+ * ```js
908
+ * var game = new THRUNIUM.Game(400, 400);
909
+ * game.states.play = function() {
910
+ * if (game.keys.isDown('KeyW')) player.y -= 2;
911
+ * };
912
+ * ```
913
+ */
914
+ this.keys = __privateGet(this, _keys);
915
+ /**
916
+ * The mouse: pointer position in game coordinates, and which buttons are held or went down or up since the previous frame. A touch counts as button 0.
917
+ *
918
+ * @category Input
206
919
  * @example
207
920
  * ```js
208
921
  * var game = new THRUNIUM.Game(400, 400);
209
- * game.state = 'game'; // run game.states['game'] each frame
922
+ * game.states.play = function() {
923
+ * if (game.mouse.wasPressed()) fireAt(game.mouse.x, game.mouse.y);
924
+ * };
210
925
  * ```
211
926
  */
212
- this.state = "startup";
927
+ this.mouse = __privateGet(this, _mouse);
928
+ /**
929
+ * Asset indexes (paths, or the `index` of an entry with a `spriteMap`) whose load has finished.
930
+ *
931
+ * @internal
932
+ */
933
+ this._loadedIndexes = /* @__PURE__ */ new Set();
934
+ /** The last name assigned to `state`; the loop switches to it at the start of the next frame. */
935
+ this._requestedState = "startup";
936
+ /** The state the loop is running this frame. */
937
+ this._runningState = "startup";
938
+ /** The scene whose `enter()` has started and whose `exit()` has not; timers made now belong to it. */
939
+ this._scene = null;
213
940
  /**
214
941
  * Name of the state to run after the loading screen. Used once, so set it before `init()`. Default is `null`, so you have to set it.
215
942
  *
@@ -222,8 +949,11 @@
222
949
  */
223
950
  this.startState = null;
224
951
  // Indexed by state name; kept as an array to match 1.0.0.
952
+ // `Scene & object` is the same type as `Scene`, but written this way TypeScript
953
+ // still infers a generic function assigned here (such as vitest's `vi.fn()`)
954
+ // from `() => void`, as it did when states were functions only.
225
955
  /**
226
- * Your game states: an object of functions keyed by name. The function named by `state` is called every frame. Change `state` to switch between them.
956
+ * Your game states, keyed by name. Each is a function, called every frame while it is the current state, or a `Scene` object with optional `enter`, `update`, `draw` and `exit`. Change `state` to switch between them.
227
957
  *
228
958
  * @category Variables
229
959
  * @example
@@ -232,9 +962,32 @@
232
962
  * game.states['game'] = function() {
233
963
  * // your code, run every frame
234
964
  * };
965
+ * game.states['play'] = {
966
+ * update: function(dt) { player.x += 100 * dt; },
967
+ * draw: function() { game.drawImage(game.image('player.png'), player.x, 100); },
968
+ * };
235
969
  * ```
236
970
  */
237
971
  this.states = [];
972
+ /**
973
+ * Set to `true` to pause the game: scenes stop getting `update`, and timers and `time` stop, while `draw` keeps running. A function state is still called every frame, since it is its own update and draw. Default is `false`.
974
+ *
975
+ * @category Scenes
976
+ * @example
977
+ * ```js
978
+ * var game = new THRUNIUM.Game(400, 400);
979
+ * game.keydown = function(e) {
980
+ * if (e.code === 'KeyP') game.paused = !game.paused;
981
+ * };
982
+ * ```
983
+ */
984
+ this.paused = false;
985
+ /**
986
+ * When `true` while paused, the next frame runs the scene's `update(1/60)` and advances timers by 1/60, then sets it back to `false`. Used by the debug menu's step button.
987
+ *
988
+ * @internal
989
+ */
990
+ this.stepOnce = false;
238
991
  /**
239
992
  * Background color drawn behind every frame. Accepts any CSS color (hex, rgb, rgba, hsl, hsla). Default is `"#fff"`.
240
993
  *
@@ -284,6 +1037,40 @@
284
1037
  // Typed for strict consumers: entries going in are strings or AssetEntry, and
285
1038
  // after init() the same array is read by key, which the Record part allows.
286
1039
  this.assets = [];
1040
+ /**
1041
+ * Fonts to load on the loading screen. Set it before `init()`. Each entry is a Google Fonts URL (a string, or `{ url, cdn? }`), or a font file `{ family, src, weight?, style? }`. `thrunium build` and `thrunium dev` ship Google Fonts with the game; `cdn: true` always loads from Google instead. The loading bar counts the fonts and the start state only runs once every font has loaded or failed; a failed font logs a warning and the game uses the fallback font.
1042
+ *
1043
+ * @category Assets
1044
+ * @example
1045
+ * ```js
1046
+ * var game = new THRUNIUM.Game(400, 400);
1047
+ * game.fonts = [
1048
+ * 'https://fonts.googleapis.com/css2?family=Lobster',
1049
+ * { family: 'Pixel', src: 'fonts/pixel.woff2' }
1050
+ * ];
1051
+ * game.startState = 'game';
1052
+ * game.states['game'] = function() {
1053
+ * game.ctx.font = '30px Lobster';
1054
+ * game.ctx.fillText('Hello', 20, 50);
1055
+ * };
1056
+ * game.init();
1057
+ * game.start();
1058
+ * ```
1059
+ */
1060
+ this.fonts = [];
1061
+ /**
1062
+ * Progress of the declared `fonts`, or `null` before `init()`: `total`, `loaded()`, `done` and the `sources` of each font.
1063
+ *
1064
+ * @category Variables
1065
+ * @example
1066
+ * ```js
1067
+ * var game = new THRUNIUM.Game(400, 400);
1068
+ * game.fonts = ['https://fonts.googleapis.com/css2?family=Lobster'];
1069
+ * game.init();
1070
+ * game.fontStatus.total; // 1
1071
+ * ```
1072
+ */
1073
+ this.fontStatus = null;
287
1074
  /**
288
1075
  * Whether `loadAssets()` has run, so the entries of `assets` have been turned into loadable elements. Use `loadedAssets` to see how many have actually finished loading.
289
1076
  *
@@ -317,6 +1104,8 @@
317
1104
  * ```
318
1105
  */
319
1106
  this.assetsToLoad = 0;
1107
+ /** @internal The indexes of assets that failed to load. */
1108
+ this._failedIndexes = /* @__PURE__ */ new Set();
320
1109
  /**
321
1110
  * Font family used by `drawText`. Default is `"Arial"`.
322
1111
  *
@@ -574,13 +1363,72 @@
574
1363
  * @internal
575
1364
  */
576
1365
  this._resize = (evt) => {
577
- var _a3, _b;
1366
+ var _a2, _b2;
578
1367
  this.updateFitScale();
579
1368
  this.updateScale();
580
- const elems = (_b = (_a3 = T.Elem) == null ? void 0 : _a3.elemsList) != null ? _b : [];
1369
+ const elems = (_b2 = (_a2 = T.Elem) == null ? void 0 : _a2.elemsList) != null ? _b2 : [];
581
1370
  for (let i = 0; i < elems.length; i++) elems[i].resize();
582
1371
  this.rezise(evt);
583
1372
  };
1373
+ /**
1374
+ * Internal keydown listener feeding `keys`.
1375
+ *
1376
+ * @internal
1377
+ */
1378
+ this._keysDown = (evt) => {
1379
+ __privateGet(this, _keys).press(evt.code);
1380
+ };
1381
+ /**
1382
+ * Internal keyup listener feeding `keys`.
1383
+ *
1384
+ * @internal
1385
+ */
1386
+ this._keysUp = (evt) => {
1387
+ __privateGet(this, _keys).release(evt.code);
1388
+ };
1389
+ /**
1390
+ * Internal mousedown listener feeding `mouse`.
1391
+ *
1392
+ * @internal
1393
+ */
1394
+ this._mouseDown = (evt) => {
1395
+ __privateGet(this, _mouse).press(evt.button);
1396
+ };
1397
+ /**
1398
+ * Internal mouseup listener feeding `mouse`.
1399
+ *
1400
+ * @internal
1401
+ */
1402
+ this._mouseUp = (evt) => {
1403
+ __privateGet(this, _mouse).release(evt.button);
1404
+ };
1405
+ /**
1406
+ * Internal touchstart listener: a touch is mouse button 0 at the touch position.
1407
+ *
1408
+ * @internal
1409
+ */
1410
+ this._mouseTouchDown = (evt) => {
1411
+ this.getMouseCords(evt);
1412
+ __privateGet(this, _mouse).press(0);
1413
+ };
1414
+ /**
1415
+ * Internal touchend and touchcancel listener: releases mouse button 0.
1416
+ *
1417
+ * @internal
1418
+ */
1419
+ this._mouseTouchUp = (evt) => {
1420
+ this.getMouseCords(evt);
1421
+ __privateGet(this, _mouse).release(0);
1422
+ };
1423
+ /**
1424
+ * Internal blur listener: releases every held key and button so nothing sticks after alt-tab.
1425
+ *
1426
+ * @internal
1427
+ */
1428
+ this._releaseAllInput = () => {
1429
+ __privateGet(this, _keys).releaseAll();
1430
+ __privateGet(this, _mouse).releaseAll();
1431
+ };
584
1432
  // Arrow field: used as an onload handler, so it must keep `this` = the Game.
585
1433
  /**
586
1434
  * Internal onload handler that counts a loaded asset.
@@ -621,20 +1469,54 @@
621
1469
  this.lastRun = Date.now();
622
1470
  this.fps = 1 / this.delta;
623
1471
  this.runSpeed = Math.round(this.fps / 60 * 100) / 100;
1472
+ __privateSet(this, _dt, Math.min(this.delta, 0.1));
1473
+ __privateMethod(this, _Game_instances, showDt_fn).call(this);
1474
+ this.switchState();
624
1475
  this.ctx.clearRect(0, 0, this.width, this.height);
625
1476
  this.canvas.style.cursor = "default";
626
1477
  this.drawRect(0, 0, this.width, this.height);
627
1478
  this.setFillColor(this.backgroundColor);
628
1479
  this.fill();
629
- if (this.state == "startup") this.startup();
630
- else this.states[this.state]();
1480
+ this.runState();
631
1481
  if (this.showFPS) this.drawFPS();
1482
+ __privateGet(this, _debug).update();
1483
+ this.endFrame();
632
1484
  if (this.gameRunning && !T.error) this.requestFrame(this.gameLoop);
633
1485
  };
634
1486
  this.width = width;
635
1487
  this.height = height;
1488
+ setInternals(this, { keys: __privateGet(this, _keys), mouse: __privateGet(this, _mouse), time: () => __privateGet(this, _time), dt: () => __privateGet(this, _dt) });
636
1489
  this.contruct();
637
1490
  }
1491
+ /**
1492
+ * Name of the state the game is in (a key of `states`). It starts as the built-in loading screen, `"startup"`, and switches to `startState` once everything has loaded. Assign a new name to change state: the switch happens at the start of the next frame (the rest of this frame stays in the old state), but reading `state` returns the new name straight away. On the switch the old scene's `exit()` runs, then the new scene's `enter()`. If the name is still not in `states` when the switch happens, the next frame throws an error listing the names that are.
1493
+ *
1494
+ * @category Variables
1495
+ * @example
1496
+ * ```js
1497
+ * var game = new THRUNIUM.Game(400, 400);
1498
+ * game.state = 'game'; // run game.states['game'] from the next frame
1499
+ * ```
1500
+ */
1501
+ get state() {
1502
+ return this._requestedState;
1503
+ }
1504
+ set state(name) {
1505
+ this._requestedState = name;
1506
+ }
1507
+ /**
1508
+ * Number of assets whose load failed (a missing file or a network error). A failed asset is not counted in `loadedAssets`, so the loading screen stays up, as it always has. Read-only.
1509
+ *
1510
+ * @category Variables
1511
+ * @example
1512
+ * ```js
1513
+ * var game = new THRUNIUM.Game(400, 400);
1514
+ * if (game.failedAssets > 0) console.log('some assets did not load');
1515
+ * ```
1516
+ */
1517
+ get failedAssets() {
1518
+ return this._failedIndexes.size;
1519
+ }
638
1520
  /**
639
1521
  * Updates `mouseX` and `mouseY` (in game coordinates) from a mouse or touch event. The engine calls it for you before the mouse and touch handlers run, so you only need it to read the position of an event you handle yourself. Since 1.1.0 it uses this game instead of a global variable named `game`, and handles touch-end events that have no `touches`.
640
1522
  * @param evt The mouse or touch event to read the position from.
@@ -659,6 +1541,8 @@
659
1541
  const sy = this.canvas.scrollHeight / this.height;
660
1542
  this.mouseX = (point.clientX - rect.left) / sx;
661
1543
  this.mouseY = (point.clientY - rect.top) / sy;
1544
+ __privateGet(this, _mouse).x = this.mouseX;
1545
+ __privateGet(this, _mouse).y = this.mouseY;
662
1546
  }
663
1547
  /**
664
1548
  * Sizes the canvas backing store for the device pixel ratio and fit scale.
@@ -699,7 +1583,9 @@
699
1583
  * ```
700
1584
  */
701
1585
  contruct() {
702
- document.body.style.background = "#333";
1586
+ const bodyStyle = getComputedStyle(document.body);
1587
+ const hasCssBackground = !["", "transparent", "rgba(0, 0, 0, 0)"].includes(bodyStyle.backgroundColor) || !["", "none"].includes(bodyStyle.backgroundImage);
1588
+ if (!hasCssBackground) document.body.style.background = "#333";
703
1589
  const container = document.createElement("div");
704
1590
  container.style.position = "relative";
705
1591
  container.style.display = "block";
@@ -727,6 +1613,8 @@
727
1613
  */
728
1614
  init() {
729
1615
  if (!this.assetsLoaded) this.loadAssets();
1616
+ const fonts = Array.isArray(this.fonts) ? this.fonts : [];
1617
+ this.fontStatus = loadFonts(fonts, window.THRUNIUM_FONTS, window.THRUNIUM_FONTS !== void 0, window.THRUNIUM_DEV === true);
730
1618
  this._resize();
731
1619
  this.canvas.addEventListener("click", this.click, false);
732
1620
  this.canvas.addEventListener("mousedown", this.mousedown, false);
@@ -739,6 +1627,24 @@
739
1627
  this.canvas.addEventListener("mousemove", this._mousetouchmove, false);
740
1628
  window.addEventListener("deviceorientation", this._deviceorientation);
741
1629
  window.addEventListener("devicemotion", this._devicemotion);
1630
+ document.addEventListener("keydown", this._keysDown, false);
1631
+ document.addEventListener("keyup", this._keysUp, false);
1632
+ this.canvas.addEventListener("mousedown", this._mouseDown, false);
1633
+ this.canvas.addEventListener("mouseup", this._mouseUp, false);
1634
+ window.addEventListener("mouseup", this._mouseUp, false);
1635
+ this.canvas.addEventListener("touchstart", this._mouseTouchDown, false);
1636
+ this.canvas.addEventListener("touchend", this._mouseTouchUp, false);
1637
+ this.canvas.addEventListener("touchcancel", this._mouseTouchUp, false);
1638
+ window.addEventListener("blur", this._releaseAllInput);
1639
+ }
1640
+ /**
1641
+ * Clears the "was pressed" and "was released" sets of `keys` and `mouse`. The game loop calls it at the end of every frame, after the state ran.
1642
+ *
1643
+ * @internal
1644
+ */
1645
+ endFrameInput() {
1646
+ __privateGet(this, _keys).endFrame();
1647
+ __privateGet(this, _mouse).endFrame();
742
1648
  }
743
1649
  /**
744
1650
  * Creates an `Image` or `Audio` element for every entry of `assets` and starts loading it, then replaces `assets` with an object-like array keyed by each entry's index. `init()` calls it for you, so you rarely need it directly. Unknown entries and file types are logged to the console and skipped.
@@ -754,6 +1660,8 @@
754
1660
  */
755
1661
  loadAssets() {
756
1662
  this.assetsToLoad = this.assets.length;
1663
+ this._loadedIndexes.clear();
1664
+ this._failedIndexes.clear();
757
1665
  const tempAssets = [];
758
1666
  const byIndex = tempAssets;
759
1667
  for (let i = 0; i < this.assets.length; i++) {
@@ -788,12 +1696,116 @@
788
1696
  el.dataset.spriteWidth = String(spriteMap.width);
789
1697
  el.dataset.spriteHeight = String(spriteMap.height);
790
1698
  }
791
- el.onload = spriteMap !== null ? this.initAssetSpriteMap : this.assetLoaded;
1699
+ const onLoaded = spriteMap !== null ? this.initAssetSpriteMap : this.assetLoaded;
1700
+ const loadedIndexes = this._loadedIndexes;
1701
+ let counted = false;
1702
+ const markLoaded = function() {
1703
+ if (counted) return;
1704
+ counted = true;
1705
+ loadedIndexes.add(index);
1706
+ onLoaded.call(this);
1707
+ };
1708
+ el.onload = markLoaded;
1709
+ if (el instanceof HTMLAudioElement) {
1710
+ el.preload = "auto";
1711
+ el.addEventListener("canplaythrough", markLoaded);
1712
+ el.addEventListener("loadeddata", markLoaded);
1713
+ }
1714
+ const failedIndexes = this._failedIndexes;
1715
+ el.onerror = () => {
1716
+ failedIndexes.add(index);
1717
+ };
792
1718
  el.src = src;
793
1719
  }
794
1720
  this.assets = tempAssets;
795
1721
  this.assetsLoaded = true;
796
1722
  }
1723
+ /**
1724
+ * Looks up a loaded asset by its index and checks that it is of the kind the caller wants.
1725
+ *
1726
+ * @internal
1727
+ */
1728
+ _getAsset(path, want) {
1729
+ const assets = this.assets;
1730
+ const known = Object.keys(assets).filter((k) => assets[k] !== null && assets[k] !== void 0);
1731
+ const entry = Object.prototype.hasOwnProperty.call(assets, path) ? assets[path] : void 0;
1732
+ if (entry === void 0 || entry === null) {
1733
+ throw new Error(
1734
+ 'No asset "' + path + '". Loaded assets: ' + (known.length > 0 ? known.join(", ") : "(none)") + "."
1735
+ );
1736
+ }
1737
+ if (this._failedIndexes.has(path)) {
1738
+ throw new Error('Asset "' + path + '" failed to load. Check that the file exists and the path is right.');
1739
+ }
1740
+ if (!this._loadedIndexes.has(path)) {
1741
+ throw new Error('Asset "' + path + '" is still loading. Use it from a state that runs after the loading screen.');
1742
+ }
1743
+ const isSprite = T.Sprite !== void 0 && entry instanceof T.Sprite;
1744
+ const isImage = !isSprite && entry instanceof HTMLImageElement;
1745
+ const isSound = entry instanceof HTMLAudioElement;
1746
+ if (want === "image" && isSprite) {
1747
+ throw new Error('Asset "' + path + '" is a sprite map, not an image. Use game.sprite("' + path + '").');
1748
+ }
1749
+ if (want === "image" && !isImage) throw new Error('Asset "' + path + '" is not an image.');
1750
+ if (want === "sound" && !isSound) throw new Error('Asset "' + path + '" is not a sound.');
1751
+ if (want === "sprite" && !isSprite) {
1752
+ throw new Error('Asset "' + path + '" is not a sprite. Give its assets entry a spriteMap to get a sprite.');
1753
+ }
1754
+ return entry;
1755
+ }
1756
+ /**
1757
+ * Returns a loaded image asset. It throws an `Error` naming the path when the path is unknown (listing what is loaded), still loading, failed to load, or not an image. Use it instead of `game.assets[path]` to get the right type and a clear error.
1758
+ *
1759
+ * @category Assets
1760
+ * @param path The path of the image, as given in `assets`.
1761
+ * @example
1762
+ * ```js
1763
+ * var game = new THRUNIUM.Game(400, 400);
1764
+ * game.assets = ['images/ship.png'];
1765
+ * game.startState = 'play';
1766
+ * game.states.play = function() {
1767
+ * game.drawImage(game.image('images/ship.png'), 100, 100);
1768
+ * };
1769
+ * ```
1770
+ */
1771
+ image(path) {
1772
+ return this._getAsset(path, "image");
1773
+ }
1774
+ /**
1775
+ * Returns a loaded sound asset. It throws an `Error` naming the path when the path is unknown (listing what is loaded), still loading, failed to load, or not a sound.
1776
+ *
1777
+ * @category Assets
1778
+ * @param path The path of the sound, as given in `assets`.
1779
+ * @example
1780
+ * ```js
1781
+ * var game = new THRUNIUM.Game(400, 400);
1782
+ * game.assets = ['sounds/laser.wav'];
1783
+ * game.click = function() {
1784
+ * game.sound('sounds/laser.wav').play();
1785
+ * };
1786
+ * ```
1787
+ */
1788
+ sound(path) {
1789
+ return this._getAsset(path, "sound");
1790
+ }
1791
+ /**
1792
+ * Returns a loaded sprite: an `assets` entry that has a `spriteMap`, by its `index`. It throws an `Error` naming the index when it is unknown (listing what is loaded), still loading, failed to load, or not a sprite.
1793
+ *
1794
+ * @category Assets
1795
+ * @param index The `index` of the assets entry.
1796
+ * @example
1797
+ * ```js
1798
+ * var game = new THRUNIUM.Game(400, 400);
1799
+ * game.assets = [{ src: 'images/tiles.png', index: 'tiles', spriteMap: { width: 32, height: 32 } }];
1800
+ * game.startState = 'play';
1801
+ * game.states.play = function() {
1802
+ * game.sprite('tiles').draw(0, 100, 100);
1803
+ * };
1804
+ * ```
1805
+ */
1806
+ sprite(index) {
1807
+ return this._getAsset(index, "sprite");
1808
+ }
797
1809
  /**
798
1810
  * Returns the text after the last dot of a file name, or `undefined`.
799
1811
  *
@@ -906,21 +1918,35 @@
906
1918
  this.ctx.closePath();
907
1919
  }
908
1920
  /**
909
- * Draws text at (x, y) using `font` and `textSize` and the fill color.
1921
+ * Draws text at (x, y) using `font` and `textSize` and the fill color. Pass `options` to change the size, alignment, baseline, color or font for this one call; the canvas state is restored afterwards.
910
1922
  *
911
1923
  * @category Drawing
912
1924
  * @param text The text to draw.
913
1925
  * @param x X coordinate of the text.
914
1926
  * @param y Y coordinate of the text.
1927
+ * @param options Optional settings for this call only.
915
1928
  * @example
916
1929
  * ```js
917
1930
  * var game = new THRUNIUM.Game(400, 400);
918
1931
  * game.drawText('Hello World!', 100, 100);
1932
+ * game.drawText('Score', 200, 50, { size: 24, align: 'center', color: '#fff' });
919
1933
  * ```
920
1934
  */
921
- drawText(text, x, y) {
922
- this.ctx.font = this.textSize + " " + this.font;
923
- this.ctx.fillText(text, x, y);
1935
+ drawText(text, x, y, options) {
1936
+ var _a2, _b2;
1937
+ if (!options) {
1938
+ this.ctx.font = this.textSize + " " + this.font;
1939
+ this.ctx.fillText(text, x, y);
1940
+ return;
1941
+ }
1942
+ const ctx = this.ctx;
1943
+ ctx.save();
1944
+ ctx.font = fontString(options.weight, (_a2 = options.size) != null ? _a2 : this.textSize, (_b2 = options.font) != null ? _b2 : this.font);
1945
+ if (options.align) ctx.textAlign = options.align;
1946
+ if (options.baseline) ctx.textBaseline = options.baseline;
1947
+ if (options.color) ctx.fillStyle = options.color;
1948
+ ctx.fillText(text, x, y);
1949
+ ctx.restore();
924
1950
  }
925
1951
  /**
926
1952
  * Traces a rectangle path, with rounded corners if `radius` is given. It only builds the path: call `fill()` or `stroke()` afterwards to draw it.
@@ -976,14 +2002,14 @@
976
2002
  this.ctx.closePath();
977
2003
  }
978
2004
  /**
979
- * Draws an image at (x, y), scaled to `width` by `height` when both are given.
2005
+ * Draws an image or sprite at (x, y). Give `width` and `height` to scale it, or an options object to also rotate, flip, fade or centre it. A sprite draws the frame `drawAnim()` is showing (frame 0 when idle). The canvas state is restored afterwards.
980
2006
  *
981
2007
  * @category Drawing
982
- * @param img The image to draw, for example a loaded entry of `assets`.
983
- * @param x X coordinate of the left edge.
984
- * @param y Y coordinate of the top edge.
985
- * @param width Width to draw at. Needs `height` as well; leave out for the natural size.
986
- * @param height Height to draw at. Needs `width` as well; leave out for the natural size.
2008
+ * @param img The image to draw, for example a loaded entry of `assets`, or a `Sprite`.
2009
+ * @param x X coordinate of the left edge, or of the centre with `anchor: 'center'`.
2010
+ * @param y Y coordinate of the top edge, or of the centre with `anchor: 'center'`.
2011
+ * @param widthOrOptions Width to draw at (needs `height` as well; leave out for the natural size), or a `DrawImageOptions` object.
2012
+ * @param height Height to draw at. Needs `width` as well; ignored when an options object is given.
987
2013
  * @example
988
2014
  * ```js
989
2015
  * var game = new THRUNIUM.Game(400, 400);
@@ -991,16 +2017,124 @@
991
2017
  * game.init();
992
2018
  * game.drawImage(game.assets['image.png'], 100, 100);
993
2019
  * game.drawImage(game.assets['image.png'], 100, 100, 200, 200);
2020
+ * game.drawImage(game.assets['image.png'], 100, 100, { angle: Math.PI / 4, anchor: 'center', alpha: 0.5 });
994
2021
  * ```
995
2022
  */
996
- drawImage(img, x, y, width = null, height = null) {
997
- this.ctx.beginPath();
998
- if (width !== null && height !== null) {
999
- this.ctx.drawImage(img, x, y, width, height);
1000
- } else {
1001
- this.ctx.drawImage(img, x, y);
2023
+ drawImage(img, x, y, widthOrOptions = null, height = null) {
2024
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
2025
+ const ctx = this.ctx;
2026
+ const options = typeof widthOrOptions === "object" && widthOrOptions !== null ? widthOrOptions : null;
2027
+ const width = options ? (_a2 = options.width) != null ? _a2 : null : widthOrOptions;
2028
+ const h = options ? (_b2 = options.height) != null ? _b2 : null : height;
2029
+ const source = T.Sprite && img instanceof T.Sprite ? img : null;
2030
+ const image = source ? source.image : img;
2031
+ const frame = source ? source.frameRect() : null;
2032
+ if (!options && !frame) {
2033
+ ctx.beginPath();
2034
+ if (width !== null && h !== null) ctx.drawImage(image, x, y, width, h);
2035
+ else ctx.drawImage(image, x, y);
2036
+ ctx.closePath();
2037
+ return;
1002
2038
  }
1003
- this.ctx.closePath();
2039
+ const natural = image;
2040
+ const w = (_d = (_c = width != null ? width : frame == null ? void 0 : frame.sw) != null ? _c : natural.width) != null ? _d : 0;
2041
+ const hh = (_f = (_e = h != null ? h : frame == null ? void 0 : frame.sh) != null ? _e : natural.height) != null ? _f : 0;
2042
+ const draw = (dx, dy) => {
2043
+ if (frame) ctx.drawImage(image, frame.sx, frame.sy, frame.sw, frame.sh, dx, dy, w, hh);
2044
+ else ctx.drawImage(image, dx, dy, w, hh);
2045
+ };
2046
+ const center = (options == null ? void 0 : options.anchor) === "center";
2047
+ const angle = (_g = options == null ? void 0 : options.angle) != null ? _g : 0;
2048
+ const alpha = options == null ? void 0 : options.alpha;
2049
+ const flipX = (_h = options == null ? void 0 : options.flipX) != null ? _h : false;
2050
+ const flipY = (_i = options == null ? void 0 : options.flipY) != null ? _i : false;
2051
+ if (!angle && alpha === void 0 && !flipX && !flipY) {
2052
+ if (!options) return draw(x, y);
2053
+ return center ? draw(x - w / 2, y - hh / 2) : draw(x, y);
2054
+ }
2055
+ ctx.save();
2056
+ if (alpha !== void 0) ctx.globalAlpha = alpha;
2057
+ ctx.translate(x, y);
2058
+ if (angle) ctx.rotate(angle);
2059
+ if (flipX || flipY) ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1);
2060
+ draw(center ? -w / 2 : flipX ? -w : 0, center ? -hh / 2 : flipY ? -hh : 0);
2061
+ ctx.restore();
2062
+ }
2063
+ // buttons
2064
+ /**
2065
+ * Makes a clickable text button. Create it once, then call its `draw()` every frame (in a scene's `draw`, for example): it counts as hovered or clicked only if it was drawn in the previous frame too, so a button made anew each frame is never clickable. It keeps working while the game is `paused`.
2066
+ *
2067
+ * @category Drawing
2068
+ * @param text The label.
2069
+ * @param x X coordinate of the label, placed by `options.align`.
2070
+ * @param y Y coordinate of the label, placed by `options.baseline`.
2071
+ * @param options Text options for `drawText`, plus `hoverColor`, `padding` and `onHover`.
2072
+ * @returns The button; read `hovered` and `clicked` from it.
2073
+ * @example
2074
+ * ```js
2075
+ * var game = new THRUNIUM.Game(400, 400);
2076
+ * var play = game.button('Play', 200, 200, { size: 28, align: 'center', baseline: 'middle', hoverColor: '#ff0' });
2077
+ * game.states.menu = {
2078
+ * draw: function() {
2079
+ * play.draw();
2080
+ * if (play.clicked) game.state = 'level1';
2081
+ * }
2082
+ * };
2083
+ * ```
2084
+ */
2085
+ button(text, x, y, options) {
2086
+ return new Button(this, __privateGet(this, _drawnButtons), text, x, y, options);
2087
+ }
2088
+ // timers
2089
+ /**
2090
+ * Calls `fn` once, after `seconds` of game time. Game time stops while `paused`, and a long frame counts as at most 0.1 seconds. A timer made while a scene is the current state belongs to it and is cancelled when the scene exits; others run until they fire or are cancelled.
2091
+ * @param seconds Game seconds to wait.
2092
+ * @param fn The function to call.
2093
+ * @returns The timer, with `cancel()` and `active`.
2094
+ *
2095
+ * @category Timers
2096
+ * @example
2097
+ * ```js
2098
+ * var game = new THRUNIUM.Game(400, 400);
2099
+ * game.states.play = {
2100
+ * enter: function() {
2101
+ * game.after(3, function() { game.state = 'gameover'; });
2102
+ * },
2103
+ * };
2104
+ * ```
2105
+ */
2106
+ after(seconds, fn) {
2107
+ return __privateGet(this, _timers).after(seconds, fn, this._scene);
2108
+ }
2109
+ /**
2110
+ * Calls `fn` every `seconds` of game time, until cancelled. It fires at most once per frame: calls missed in a long frame are dropped, not caught up. Like `after()`, a timer made while a scene is current is cancelled when that scene exits.
2111
+ * @param seconds Game seconds between calls.
2112
+ * @param fn The function to call.
2113
+ * @returns The timer, with `cancel()` and `active`.
2114
+ *
2115
+ * @category Timers
2116
+ * @example
2117
+ * ```js
2118
+ * var game = new THRUNIUM.Game(400, 400);
2119
+ * var spawner = game.every(2, function() { enemies.push(newEnemy()); });
2120
+ * spawner.cancel(); // stop spawning
2121
+ * ```
2122
+ */
2123
+ every(seconds, fn) {
2124
+ return __privateGet(this, _timers).every(seconds, fn, this._scene);
2125
+ }
2126
+ /**
2127
+ * Number of active timers made with `after()` and `every()`: ones that have not fired (for `after`) or been cancelled. Read-only.
2128
+ *
2129
+ * @category Timers
2130
+ * @example
2131
+ * ```js
2132
+ * var game = new THRUNIUM.Game(400, 400);
2133
+ * console.log(game.timerCount + ' timers running');
2134
+ * ```
2135
+ */
2136
+ get timerCount() {
2137
+ return __privateGet(this, _timers).count;
1004
2138
  }
1005
2139
  // loop control
1006
2140
  /**
@@ -1038,6 +2172,7 @@
1038
2172
  * @internal
1039
2173
  */
1040
2174
  startup() {
2175
+ var _a2, _b2, _c, _d;
1041
2176
  this.drawRect(0, 0, this.width, this.height);
1042
2177
  this.setFillColor("#000");
1043
2178
  this.fill();
@@ -1049,12 +2184,14 @@
1049
2184
  this.drawRect(this.width / 2 - 100, this.height / 2, 200, 20, 10);
1050
2185
  this.setStrokeColor("#fff");
1051
2186
  this.stroke();
1052
- let loaded = 200 / this.assetsToLoad * this.loadedAssets;
2187
+ const fontsTotal = (_b2 = (_a2 = this.fontStatus) == null ? void 0 : _a2.total) != null ? _b2 : 0;
2188
+ const fontsLoaded = (_d = (_c = this.fontStatus) == null ? void 0 : _c.loaded()) != null ? _d : 0;
2189
+ let loaded = 200 / (this.assetsToLoad + fontsTotal) * (this.loadedAssets + fontsLoaded);
1053
2190
  if (loaded < 20) loaded = 20;
1054
2191
  this.drawRect(this.width / 2 - 100, this.height / 2, loaded, 20, 10);
1055
2192
  this.setFillColor("#fff");
1056
2193
  this.fill();
1057
- if (this.assetsToLoad == this.loadedAssets && T.pageLoaded && T.fontsLoaded) {
2194
+ if (this.assetsToLoad == this.loadedAssets && fontsTotal == fontsLoaded && T.pageLoaded && T.fontsLoaded) {
1058
2195
  this._resize();
1059
2196
  this.state = this.startState;
1060
2197
  }
@@ -1071,6 +2208,97 @@
1071
2208
  this.ctx.textBaseline = "top";
1072
2209
  this.ctx.fillText(Math.round(this.fps) + " fps - scale: " + this.scale, 5, 5);
1073
2210
  }
2211
+ /** The state named `name`; throws an error listing the known names if there is none. */
2212
+ stateNamed(name) {
2213
+ const s = this.states[name];
2214
+ if (typeof s !== "function" && (typeof s !== "object" || s === null)) {
2215
+ throw new Error('Unknown state "' + name + '". Known states: ' + Object.keys(this.states).join(", ") + ".");
2216
+ }
2217
+ return s;
2218
+ }
2219
+ /** Switches to the requested state if it changed: the old scene's `exit()`, then the new scene's `enter()`. */
2220
+ switchState() {
2221
+ var _a2, _b2;
2222
+ const next = this._requestedState;
2223
+ if (next === this._runningState) return;
2224
+ const s = next === "startup" ? null : this.stateNamed(next);
2225
+ const old = this._scene;
2226
+ if (old) {
2227
+ this._scene = null;
2228
+ __privateGet(this, _timers).cancelOwner(old);
2229
+ (_a2 = old.exit) == null ? void 0 : _a2.call(old);
2230
+ }
2231
+ this._runningState = next;
2232
+ if (s && typeof s !== "function") {
2233
+ this._scene = s;
2234
+ (_b2 = s.enter) == null ? void 0 : _b2.call(s);
2235
+ }
2236
+ }
2237
+ /**
2238
+ * Runs one frame of the current state. A scene gets `update(dt)` and the timers advance unless paused (or a `stepOnce` advances both by 1/60); then it draws. A function state is called as it is, and timers advance unless paused.
2239
+ */
2240
+ runState() {
2241
+ var _a2, _b2, _c;
2242
+ const name = this._runningState;
2243
+ const s = name === "startup" ? null : this.stateNamed(name);
2244
+ if (s === null || typeof s === "function") {
2245
+ if (s) s.call(this.states);
2246
+ else this.startup();
2247
+ if (s && !this.paused) this.advanceTime(__privateGet(this, _dt));
2248
+ this.stepOnce = false;
2249
+ return;
2250
+ }
2251
+ if (!this.paused) {
2252
+ (_a2 = s.update) == null ? void 0 : _a2.call(s, __privateGet(this, _dt));
2253
+ this.advanceTime(__privateGet(this, _dt));
2254
+ } else if (this.stepOnce) {
2255
+ (_b2 = s.update) == null ? void 0 : _b2.call(s, 1 / 60);
2256
+ this.advanceTime(1 / 60);
2257
+ }
2258
+ this.stepOnce = false;
2259
+ (_c = s.draw) == null ? void 0 : _c.call(s);
2260
+ }
2261
+ /** Moves game time and the timers on by `dt` seconds. */
2262
+ advanceTime(dt) {
2263
+ __privateSet(this, _time, __privateGet(this, _time) + dt);
2264
+ __privateMethod(this, _Game_instances, showTime_fn).call(this);
2265
+ __privateGet(this, _timers).advance(dt);
2266
+ }
2267
+ /** End-of-frame bookkeeping, after the game and the debug menu have drawn. Other per-frame sets reset here, before the input. */
2268
+ endFrame() {
2269
+ const drawn = __privateGet(this, _drawnButtons);
2270
+ [drawn.current, drawn.previous] = [drawn.previous, drawn.current];
2271
+ drawn.current.clear();
2272
+ this.endFrameInput();
2273
+ }
2274
+ };
2275
+ _keys = new WeakMap();
2276
+ _mouse = new WeakMap();
2277
+ _debug = new WeakMap();
2278
+ _timers = new WeakMap();
2279
+ _drawnButtons = new WeakMap();
2280
+ _time = new WeakMap();
2281
+ _dt = new WeakMap();
2282
+ _shownTime = new WeakMap();
2283
+ _shownDt = new WeakMap();
2284
+ _Game_instances = new WeakSet();
2285
+ /** Copies the engine's `time` to the public property, unless the game has assigned its own value there. */
2286
+ showTime_fn = function() {
2287
+ if (__privateGet(this, _shownTime) === null) return;
2288
+ if (this.time !== __privateGet(this, _shownTime)) {
2289
+ __privateSet(this, _shownTime, null);
2290
+ return;
2291
+ }
2292
+ this.time = __privateSet(this, _shownTime, __privateGet(this, _time));
2293
+ };
2294
+ /** Copies the engine's `dt` to the public property, unless the game has assigned its own value there. */
2295
+ showDt_fn = function() {
2296
+ if (__privateGet(this, _shownDt) === null) return;
2297
+ if (this.dt !== __privateGet(this, _shownDt)) {
2298
+ __privateSet(this, _shownDt, null);
2299
+ return;
2300
+ }
2301
+ this.dt = __privateSet(this, _shownDt, __privateGet(this, _dt));
1074
2302
  };
1075
2303
 
1076
2304
  // src/vector.ts
@@ -1435,21 +2663,22 @@
1435
2663
  return rect.x !== void 0 && rect.y !== void 0 && rect.width !== void 0 && rect.height !== void 0;
1436
2664
  },
1437
2665
  /**
1438
- * Copies `pos.x` and `pos.y` onto the shape's own `x` and `y`, and returns the same object. A shape without a `pos` is returned unchanged. The result has the same shape you passed in, so a circle stays a circle and a rect stays a rect. The collision checks call it for you.
1439
- * @param object The shape to update.
2666
+ * Returns a copy of the shape with `x` and `y` filled in from `pos.x` and `pos.y`. The object you pass in is not changed (before 1.2.0 `x` and `y` were written onto it), so shapes whose `x` and `y` are getters work. A shape without a `pos` is returned as it is, not copied. The result has the same shape you passed in, so a circle stays a circle and a rect stays a rect. The collision checks call it for you.
2667
+ * @param object The shape to read.
1440
2668
  * @example
1441
2669
  * ```js
1442
2670
  * var rect = { pos: new THRUNIUM.Vector(100, 100), width: 50, height: 50 };
1443
- * THRUNIUM.Collider.fixPos(rect);
1444
- * // rect.x is now 100 and rect.y is 100
2671
+ * var fixed = THRUNIUM.Collider.fixPos(rect);
2672
+ * // fixed.x is 100 and fixed.y is 100; rect itself has no x or y
1445
2673
  * ```
1446
2674
  */
1447
2675
  fixPos(object) {
1448
2676
  if (object.pos === void 0) return object;
1449
2677
  if (object.pos.x === void 0 && object.pos.y === void 0) return object;
1450
- object.x = object.pos.x;
1451
- object.y = object.pos.y;
1452
- return object;
2678
+ const copy = Object.create(object);
2679
+ Object.defineProperty(copy, "x", { value: object.pos.x, enumerable: true, writable: true, configurable: true });
2680
+ Object.defineProperty(copy, "y", { value: object.pos.y, enumerable: true, writable: true, configurable: true });
2681
+ return copy;
1453
2682
  },
1454
2683
  /**
1455
2684
  * Returns `true` if two rects overlap. Rects whose edges just touch count as colliding. Each rect needs `x`, `y`, `width` and `height`, or `pos`, `width` and `height`.
@@ -1472,9 +2701,9 @@
1472
2701
  * }
1473
2702
  * ```
1474
2703
  */
1475
- rect(_a3, _b) {
1476
- const a = Collider.fixPos(_a3);
1477
- const b = Collider.fixPos(_b);
2704
+ rect(_a2, _b2) {
2705
+ const a = Collider.fixPos(_a2);
2706
+ const b = Collider.fixPos(_b2);
1478
2707
  if (!Collider.isRect(a) || !Collider.isRect(b)) {
1479
2708
  throwError("One of the objects is not defined correctly as a rect");
1480
2709
  return false;
@@ -1508,9 +2737,9 @@
1508
2737
  * }
1509
2738
  * ```
1510
2739
  */
1511
- circle(_a3, _b) {
1512
- const a = Collider.fixPos(_a3);
1513
- const b = Collider.fixPos(_b);
2740
+ circle(_a2, _b2) {
2741
+ const a = Collider.fixPos(_a2);
2742
+ const b = Collider.fixPos(_b2);
1514
2743
  if (!Collider.isCircle(a) || !Collider.isCircle(b)) {
1515
2744
  throwError("One of the objects is not defined correctly as a circle");
1516
2745
  return false;
@@ -1564,8 +2793,8 @@
1564
2793
 
1565
2794
  // src/sprite.ts
1566
2795
  var game = () => T.gameObject;
1567
- var _a2;
1568
- _a2 = Symbol.toStringTag;
2796
+ var _b;
2797
+ _b = Symbol.toStringTag;
1569
2798
  var Sprite = class {
1570
2799
  /**
1571
2800
  * Creates a sprite from an image. The image must have finished loading, because its size is read here; until you call `setSpriteMap()` the whole image is one frame. Must be called with `new`, and a `THRUNIUM.Game` must exist before the sprite draws.
@@ -1582,7 +2811,7 @@
1582
2811
  * ```
1583
2812
  */
1584
2813
  constructor(image) {
1585
- this[_a2] = "THRUNIUM.Sprite";
2814
+ this[_b] = "THRUNIUM.Sprite";
1586
2815
  /**
1587
2816
  * Rotation in degrees, clockwise, around the centre of the drawn frame. Default is `0`. Set it with `setAngle()`.
1588
2817
  *
@@ -1798,6 +3027,30 @@
1798
3027
  this.spriteWidth = width;
1799
3028
  this.spriteHeight = height;
1800
3029
  }
3030
+ /**
3031
+ * The source rectangle of a frame within the image, as used by `game.drawImage()` when it is given a sprite. Frames are laid out left to right, wrapping to the next row.
3032
+ * @param frame Number of the frame, counting from 0. Default is the frame `drawAnim()` is showing, or `0` when no animation is running.
3033
+ * @returns The frame's `sx`, `sy`, `sw` and `sh` in image pixels.
3034
+ * @example
3035
+ * ```js
3036
+ * var game = new THRUNIUM.Game(400, 400);
3037
+ * game.assets = [{ src: 'images/tiles.png', index: 'tiles', spriteMap: { width: 40, height: 40 } }];
3038
+ * game.startState = 'game';
3039
+ * game.states['game'] = function() {
3040
+ * game.assets['tiles'].frameRect(2); // { sx: 80, sy: 0, sw: 40, sh: 40 } on a wide image
3041
+ * };
3042
+ * game.init();
3043
+ * game.start();
3044
+ * ```
3045
+ */
3046
+ frameRect(frame = ((_a2) => (_a2 = this.currentSprite) != null ? _a2 : 0)()) {
3047
+ return {
3048
+ sx: frame * this.spriteWidth % this.fullWidth,
3049
+ sy: Math.floor(frame * this.spriteWidth / this.fullWidth) * this.spriteHeight,
3050
+ sw: this.spriteWidth,
3051
+ sh: this.spriteHeight
3052
+ };
3053
+ }
1801
3054
  /**
1802
3055
  * Draws one frame centred on (`x`, `y`), rotated by `angle`. The frame is drawn at its own size unless you pass `width` and `height`.
1803
3056
  * @param imgNum Number of the frame to draw, counting from 0 left to right, then row by row. Default is `0`.
@@ -1819,8 +3072,7 @@
1819
3072
  * ```
1820
3073
  */
1821
3074
  draw(imgNum = 0, x, y, width, height) {
1822
- const xImg = imgNum * this.spriteWidth % this.fullWidth;
1823
- const yImg = Math.floor(imgNum * this.spriteWidth / this.fullWidth) * this.spriteHeight;
3075
+ const { sx: xImg, sy: yImg } = this.frameRect(imgNum);
1824
3076
  const w = width === void 0 ? this.spriteWidth : width;
1825
3077
  const h = height === void 0 ? this.spriteHeight : height;
1826
3078
  const ctx = game().ctx;
@@ -1854,7 +3106,7 @@
1854
3106
  * ```
1855
3107
  */
1856
3108
  drawAnim(imgFrom, imgTo, x, y, width, height) {
1857
- var _a3;
3109
+ var _a2;
1858
3110
  if (this.currentSprite == null) this.currentSprite = imgFrom;
1859
3111
  const length = this.animTimeDur / (imgTo - imgFrom + 1);
1860
3112
  const now = Date.now();
@@ -1867,7 +3119,7 @@
1867
3119
  }
1868
3120
  this.frameTimeLast = now;
1869
3121
  }
1870
- this.draw((_a3 = this.currentSprite) != null ? _a3 : void 0, x, y, width, height);
3122
+ this.draw((_a2 = this.currentSprite) != null ? _a2 : void 0, x, y, width, height);
1871
3123
  }
1872
3124
  };
1873
3125
 
@@ -2058,7 +3310,7 @@
2058
3310
  this.setStyle("display", "none");
2059
3311
  }
2060
3312
  };
2061
- function Button(txt, x, y) {
3313
+ function Button2(txt, x, y) {
2062
3314
  const button = new ElemElem("button", x, y);
2063
3315
  button.elem.textContent = txt;
2064
3316
  button.elem.style.border = "none";
@@ -2094,15 +3346,15 @@
2094
3346
  */
2095
3347
  elemsList: [],
2096
3348
  Elem: ElemElem,
2097
- Button,
3349
+ Button: Button2,
2098
3350
  Input
2099
3351
  };
2100
3352
 
2101
3353
  // src/ajax.ts
2102
3354
  function ajax(data) {
2103
- var _a3, _b, _c, _d;
2104
- const success = (_a3 = data.success) != null ? _a3 : ((e) => console.log(e));
2105
- const error = (_b = data.error) != null ? _b : (() => {
3355
+ var _a2, _b2, _c, _d;
3356
+ const success = (_a2 = data.success) != null ? _a2 : ((e) => console.log(e));
3357
+ const error = (_b2 = data.error) != null ? _b2 : (() => {
2106
3358
  });
2107
3359
  const contentType = (_c = data.contentType) != null ? _c : "application/x-www-form-urlencoded";
2108
3360
  const xhttp = new XMLHttpRequest();
@@ -2181,7 +3433,7 @@
2181
3433
  data: "requestToken=" + T.Storage.reqToken,
2182
3434
  // 1.0.0 typo `succes` kept: ajax ignores it (part of why the flow is WIP).
2183
3435
  succes: function(e) {
2184
- var _a3, _b, _c, _d;
3436
+ var _a2, _b2, _c, _d;
2185
3437
  const response = JSON.parse(e.response);
2186
3438
  if (response.access == "0" && !T.Storage.accessRequested) {
2187
3439
  window.addEventListener("message", T.Storage._receiveMessage, false);
@@ -2195,34 +3447,34 @@
2195
3447
  }, 200);
2196
3448
  } else if (response.access == "1") {
2197
3449
  T.Storage.userToken = window.event.data.userToken;
2198
- (_b = (_a3 = T.Storage._options).succes) == null ? void 0 : _b.call(_a3, { type: "userAccepted", event: e });
3450
+ (_b2 = (_a2 = T.Storage._options).succes) == null ? void 0 : _b2.call(_a2, { type: "userAccepted", event: e });
2199
3451
  } else {
2200
3452
  (_d = (_c = T.Storage._options).error) == null ? void 0 : _d.call(_c, { type: "ajaxFailed", event: e });
2201
3453
  }
2202
3454
  },
2203
3455
  error: function(e) {
2204
- var _a3, _b;
2205
- (_b = (_a3 = T.Storage._options).error) == null ? void 0 : _b.call(_a3, { type: "ajaxFailed", event: e });
3456
+ var _a2, _b2;
3457
+ (_b2 = (_a2 = T.Storage._options).error) == null ? void 0 : _b2.call(_a2, { type: "ajaxFailed", event: e });
2206
3458
  }
2207
3459
  });
2208
3460
  }
2209
3461
  function _receiveMessage(e) {
2210
- var _a3, _b, _c;
3462
+ var _a2, _b2, _c;
2211
3463
  const event = window.event;
2212
3464
  if (event.origin !== "https://www.thrungames.com/" && event.origin !== "https://www.thrungames.com/") return;
2213
- clearTimeout((_a3 = T.Storage.timeout) != null ? _a3 : void 0);
3465
+ clearTimeout((_a2 = T.Storage.timeout) != null ? _a2 : void 0);
2214
3466
  T.Storage.accessRequested = true;
2215
3467
  if (event.data.state == 1) {
2216
3468
  T.Storage.reqUserToken(T.Storage._options);
2217
3469
  } else {
2218
- (_c = (_b = T.Storage._options).error) == null ? void 0 : _c.call(_b, { type: "userRejected", event: e });
3470
+ (_c = (_b2 = T.Storage._options).error) == null ? void 0 : _c.call(_b2, { type: "userRejected", event: e });
2219
3471
  }
2220
3472
  }
2221
3473
  function request(_options2) {
2222
3474
  }
2223
3475
 
2224
3476
  // src/index.ts
2225
- T.version = "1.2.0-rc.2";
3477
+ T.version = "1.2.0-rc.4";
2226
3478
  T.pageLoad = pageLoad;
2227
3479
  T.ready = ready;
2228
3480
  T.throwError = throwError;
@@ -2234,6 +3486,7 @@
2234
3486
  T.Vector = Vector;
2235
3487
  T.Collider = Object.assign(T.Collider || {}, Collider);
2236
3488
  T.Sprite = Sprite;
3489
+ T.Button = Button;
2237
3490
  T.Elem = Object.assign(T.Elem || {}, elemApi);
2238
3491
  T.ajax = ajax;
2239
3492
  T.Storage = Object.assign(T.Storage || {}, storage, storage_token_exports);