@gg-web-engine/core 0.0.3 → 0.0.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.
Files changed (47) hide show
  1. package/dist/2d/entities/controllers/entity-2d-positioning.animator.js +1 -1
  2. package/dist/2d/entities/gg-2d-entity.d.ts +3 -5
  3. package/dist/2d/entities/gg-2d-entity.js +2 -3
  4. package/dist/3d/entities/controllers/animators/camera-3d.animator.d.ts +17 -0
  5. package/dist/3d/entities/controllers/animators/camera-3d.animator.js +32 -0
  6. package/dist/3d/entities/controllers/animators/entity-3d-positioning.animator.d.ts +16 -0
  7. package/dist/3d/entities/controllers/animators/entity-3d-positioning.animator.js +26 -0
  8. package/dist/3d/entities/controllers/input/car-keyboard-handling.controller.d.ts +25 -0
  9. package/dist/3d/entities/controllers/input/car-keyboard-handling.controller.js +105 -0
  10. package/dist/3d/entities/controllers/input/free-camera.controller.d.ts +54 -0
  11. package/dist/3d/entities/controllers/input/free-camera.controller.js +102 -0
  12. package/dist/3d/entities/gg-3d-entity.d.ts +3 -5
  13. package/dist/3d/entities/gg-3d-entity.js +2 -3
  14. package/dist/3d/entities/gg-3d-map-graph.entity.d.ts +3 -5
  15. package/dist/3d/entities/gg-3d-map-graph.entity.js +1 -2
  16. package/dist/3d/inputs/car-keyboard.input.d.ts +25 -0
  17. package/dist/3d/inputs/car-keyboard.input.js +100 -0
  18. package/dist/3d/inputs/free-camera.input.d.ts +22 -0
  19. package/dist/3d/inputs/free-camera.input.js +80 -0
  20. package/dist/base/clock/global-clock.d.ts +4 -3
  21. package/dist/base/clock/global-clock.js +2 -2
  22. package/dist/base/clock/i-clock.d.ts +7 -0
  23. package/dist/base/clock/i-clock.js +2 -0
  24. package/dist/base/clock/pausable-clock.d.ts +25 -0
  25. package/dist/base/clock/pausable-clock.js +79 -0
  26. package/dist/base/entities/base-gg-renderer.d.ts +3 -15
  27. package/dist/base/entities/base-gg-renderer.js +2 -30
  28. package/dist/base/entities/controllers/animation-mixer.d.ts +1 -8
  29. package/dist/base/entities/controllers/animation-mixer.js +2 -11
  30. package/dist/base/entities/gg-entity.d.ts +29 -0
  31. package/dist/base/entities/gg-entity.js +35 -1
  32. package/dist/base/entities/inline-controller.js +1 -6
  33. package/dist/base/entities/interfaces/i-tick-listener.d.ts +25 -1
  34. package/dist/base/entities/interfaces/i-tick-listener.js +17 -1
  35. package/dist/base/gg-world.d.ts +9 -6
  36. package/dist/base/gg-world.js +47 -29
  37. package/dist/base/inputs/direction.keyboard-input.d.ts +41 -0
  38. package/dist/base/inputs/direction.keyboard-input.js +85 -0
  39. package/dist/base/inputs/input.d.ts +50 -0
  40. package/dist/base/inputs/input.js +80 -0
  41. package/dist/base/inputs/keyboard.input.d.ts +45 -0
  42. package/dist/base/inputs/keyboard.input.js +130 -0
  43. package/dist/base/inputs/mouse.input.d.ts +57 -0
  44. package/dist/base/inputs/mouse.input.js +81 -0
  45. package/dist/index.d.ts +10 -10
  46. package/dist/index.js +10 -10
  47. package/package.json +1 -1
@@ -10,9 +10,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.GgWorld = void 0;
13
- const i_tick_listener_1 = require("./entities/interfaces/i-tick-listener");
13
+ const gg_entity_1 = require("./entities/gg-entity");
14
14
  const gg_static_1 = require("./gg-static");
15
- const keyboard_controller_1 = require("./controllers/keyboard.controller");
15
+ const keyboard_input_1 = require("./inputs/keyboard.input");
16
16
  const rxjs_1 = require("rxjs");
17
17
  const gg_console_ui_1 = require("./ui/gg-console.ui");
18
18
  const gg_debugger_ui_1 = require("./ui/gg-debugger.ui");
@@ -22,18 +22,17 @@ class GgWorld {
22
22
  this.visualScene = visualScene;
23
23
  this.physicsWorld = physicsWorld;
24
24
  this.consoleEnabled = consoleEnabled;
25
- // world clock, can be paused/resumed. Stops when disposing world
26
25
  this.worldClock = global_clock_1.GgGlobalClock.instance.createChildClock(false);
27
- // TODO consider adding mouse controller
28
- this.keyboardController = new keyboard_controller_1.KeyboardController();
26
+ this.keyboardInput = new keyboard_input_1.KeyboardInput();
29
27
  this.children = [];
28
+ // the same as children, but sorted by tick order
30
29
  this.tickListeners = [];
31
30
  this.commands = {};
32
31
  gg_static_1.GgStatic.instance.worlds.push(this);
33
32
  gg_static_1.GgStatic.instance.selectedWorld = this;
34
- this.keyboardController.start().then();
33
+ this.keyboardInput.start().then();
35
34
  if (consoleEnabled) {
36
- this.keyboardController
35
+ this.keyboardInput
37
36
  .bind('Backquote')
38
37
  .pipe((0, rxjs_1.filter)(x => x))
39
38
  .subscribe(() => {
@@ -76,23 +75,27 @@ class GgWorld {
76
75
  }), 'args: [0 or 1]; turn on/off physics debug view. Default value is 0');
77
76
  }
78
77
  }
79
- get worldTime() {
80
- return this.worldClock.elapsedTime;
81
- }
82
78
  init() {
83
79
  return __awaiter(this, void 0, void 0, function* () {
84
80
  yield Promise.all([this.physicsWorld.init(), this.visualScene.init()]);
85
81
  this.worldClock.tick$.subscribe(([elapsed, delta]) => {
86
- let physicsTickPerformed = false;
87
- for (let i = 0; i < this.tickListeners.length; i++) {
88
- if (!physicsTickPerformed && this.tickListeners[i].tickOrder >= 500) {
89
- this.physicsWorld.simulate(delta);
90
- physicsTickPerformed = true;
82
+ let i = 0;
83
+ // emit tick to all entities with tick order < GGTickOrder.PHYSICS_SIMULATION
84
+ for (i; i < this.tickListeners.length; i++) {
85
+ if (this.tickListeners[i].tickOrder >= gg_entity_1.GGTickOrder.PHYSICS_SIMULATION) {
86
+ break;
87
+ }
88
+ if (this.tickListeners[i].active) {
89
+ this.tickListeners[i].tick$.next([elapsed, delta]);
91
90
  }
92
- this.tickListeners[i].tick$.next([elapsed, delta]);
93
91
  }
94
- if (!physicsTickPerformed) {
95
- this.physicsWorld.simulate(delta);
92
+ // run phycics simulation
93
+ this.physicsWorld.simulate(delta);
94
+ // emit tick to all remained entities
95
+ for (i; i < this.tickListeners.length; i++) {
96
+ if (this.tickListeners[i].active) {
97
+ this.tickListeners[i].tick$.next([elapsed, delta]);
98
+ }
96
99
  }
97
100
  });
98
101
  });
@@ -106,9 +109,22 @@ class GgWorld {
106
109
  resumeWorld() {
107
110
  this.worldClock.resume();
108
111
  }
112
+ get isRunning() {
113
+ return this.worldClock.isRunning;
114
+ }
115
+ get isPaused() {
116
+ return this.worldClock.isPaused;
117
+ }
118
+ get worldTime() {
119
+ return this.worldClock.elapsedTime;
120
+ }
121
+ createClock(autoStart) {
122
+ return this.worldClock.createChildClock(autoStart);
123
+ }
109
124
  dispose() {
110
125
  this.worldClock.stop();
111
126
  for (let i = 0; i < this.children.length; i++) {
127
+ this.children[i].onRemoved();
112
128
  this.children[i].dispose();
113
129
  }
114
130
  this.children.splice(0, this.children.length);
@@ -118,24 +134,26 @@ class GgWorld {
118
134
  }
119
135
  addEntity(entity) {
120
136
  if (!!entity.world) {
121
- throw new Error('Entity already spawned');
137
+ console.warn('Trying to spawn entity, which is already spawned');
138
+ return;
122
139
  }
123
140
  this.children.push(entity);
124
- if ((0, i_tick_listener_1.isITickListener)(entity)) {
125
- this.tickListeners.push(entity);
126
- this.tickListeners.sort((l1, l2) => l1.tickOrder - l2.tickOrder);
127
- }
141
+ this.tickListeners.push(entity);
142
+ this.tickListeners.sort((l1, l2) => l1.tickOrder - l2.tickOrder);
128
143
  entity.onSpawned(this);
129
144
  }
130
145
  removeEntity(entity, dispose = true) {
131
- if (entity.world !== this) {
132
- throw new Error('Entity is not a part of this world');
133
- }
134
- this.children.splice(this.children.findIndex(x => x === entity), 1);
135
- if ((0, i_tick_listener_1.isITickListener)(entity)) {
146
+ if (entity.world) {
147
+ if (entity.world !== this) {
148
+ throw new Error('Entity is not a part of this world');
149
+ }
150
+ this.children.splice(this.children.findIndex(x => x === entity), 1);
136
151
  this.tickListeners.splice(this.tickListeners.findIndex(x => x === entity), 1);
152
+ entity.onRemoved();
153
+ }
154
+ else {
155
+ console.warn('Trying to remove entity, which is not spawned');
137
156
  }
138
- entity.onRemoved();
139
157
  if (dispose) {
140
158
  entity.dispose();
141
159
  }
@@ -0,0 +1,41 @@
1
+ import { Observable } from 'rxjs';
2
+ import { KeyboardInput } from './keyboard.input';
3
+ import { Input } from './input';
4
+ /**
5
+ * The type representing desired keymap for DirectionKeyboardInput
6
+ */
7
+ export declare type DirectionKeyboardKeymap = 'arrows' | 'wasd' | 'wasd+arrows';
8
+ /**
9
+ * The type of DirectionKeyboardInput output value
10
+ */
11
+ export declare type DirectionKeyboardOutput = {
12
+ upDown?: boolean;
13
+ leftRight?: boolean;
14
+ };
15
+ /**
16
+ * An input class, responsible for handling direction keys and providing simple current direction observable.
17
+ * Supports two the most popular keyboard layouts: WASD and arrows.
18
+ */
19
+ export declare class DirectionKeyboardInput extends Input {
20
+ protected readonly keyboard: KeyboardInput;
21
+ protected readonly keymap: DirectionKeyboardKeymap;
22
+ /**
23
+ * A subject that emits `DirectionKeyboardOutput` objects whenever the input changes.
24
+ */
25
+ private _output$;
26
+ /**
27
+ * Returns an observable that emits `DirectionKeyboardOutput` objects whenever the input changes.
28
+ */
29
+ get output$(): Observable<DirectionKeyboardOutput>;
30
+ /**
31
+ * Creates a new instance of the `DirectionKeyboardInput` class.
32
+ *
33
+ * @param keyboard The `KeyboardInput` instance to use for input handling. You should probably use one from the World instance
34
+ * @param keymap The `DirectionKeyboardKeymap` defining which keys to listen for.
35
+ */
36
+ constructor(keyboard: KeyboardInput, keymap: DirectionKeyboardKeymap);
37
+ /**
38
+ * Called when the input handling should start.
39
+ */
40
+ protected startInternal(): Promise<void>;
41
+ }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DirectionKeyboardInput = void 0;
13
+ const rxjs_1 = require("rxjs");
14
+ const operators_1 = require("rxjs/operators");
15
+ const input_1 = require("./input");
16
+ /**
17
+ * An input class, responsible for handling direction keys and providing simple current direction observable.
18
+ * Supports two the most popular keyboard layouts: WASD and arrows.
19
+ */
20
+ class DirectionKeyboardInput extends input_1.Input {
21
+ /**
22
+ * Creates a new instance of the `DirectionKeyboardInput` class.
23
+ *
24
+ * @param keyboard The `KeyboardInput` instance to use for input handling. You should probably use one from the World instance
25
+ * @param keymap The `DirectionKeyboardKeymap` defining which keys to listen for.
26
+ */
27
+ constructor(keyboard, keymap) {
28
+ super();
29
+ this.keyboard = keyboard;
30
+ this.keymap = keymap;
31
+ /**
32
+ * A subject that emits `DirectionKeyboardOutput` objects whenever the input changes.
33
+ */
34
+ this._output$ = new rxjs_1.Subject();
35
+ }
36
+ /**
37
+ * Returns an observable that emits `DirectionKeyboardOutput` objects whenever the input changes.
38
+ */
39
+ get output$() {
40
+ return this._output$.asObservable();
41
+ }
42
+ /**
43
+ * Called when the input handling should start.
44
+ */
45
+ startInternal() {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ // Initialize an array to hold the keys to listen for
48
+ const keys = [[], [], [], []];
49
+ // Add the "wasd" keys to the array if specified in the keymap
50
+ if (this.keymap.includes('wasd')) {
51
+ keys[0].push('KeyW');
52
+ keys[1].push('KeyA');
53
+ keys[2].push('KeyS');
54
+ keys[3].push('KeyD');
55
+ }
56
+ // Add the arrow keys to the array if specified in the keymap
57
+ if (this.keymap.includes('arrows')) {
58
+ keys[0].push('ArrowUp');
59
+ keys[1].push('ArrowLeft');
60
+ keys[2].push('ArrowDown');
61
+ keys[3].push('ArrowRight');
62
+ }
63
+ // Bind to the keyboard events for the specified keys
64
+ (0, rxjs_1.combineLatest)(keys.map(x => this.keyboard.bindMany(...x)))
65
+ .pipe(
66
+ // Stop listening when the `stop$` signal is received
67
+ (0, rxjs_1.takeUntil)(this.stop$),
68
+ // Map the key states to a `DirectionKeyboardOutput` object
69
+ (0, operators_1.map)(moveDirection => {
70
+ const result = {};
71
+ if (moveDirection.includes(true)) {
72
+ const [f, l, b, r] = moveDirection;
73
+ if (f != b)
74
+ result.upDown = f;
75
+ if (l != r)
76
+ result.leftRight = l;
77
+ }
78
+ return result;
79
+ }))
80
+ // Emit the resulting `DirectionKeyboardOutput` object through the `_output$` subject
81
+ .subscribe(this._output$);
82
+ });
83
+ }
84
+ }
85
+ exports.DirectionKeyboardInput = DirectionKeyboardInput;
@@ -0,0 +1,50 @@
1
+ import { Subject } from 'rxjs';
2
+ /**
3
+ * An abstract class that provides basic implementation for Input class.
4
+ * Input is an entity for handling input from user, such as mouse movements, key presses etc.
5
+ * Inputs are not bound to World-s and working independently by design.
6
+ *
7
+ * TStartParams - A type representing an array of input arguments for the start method. Items are recommended to be named.
8
+ *
9
+ * TStopParams - A type representing an array of input arguments for the stop method. Items are recommended to be named.
10
+ */
11
+ export declare abstract class Input<TStartParams extends any[] = [], TStopParams extends any[] = []> {
12
+ /**
13
+ * A private boolean that represents the running state of the process.
14
+ */
15
+ private _running;
16
+ /**
17
+ * A protected subject that emits a void value when the process is stopped.
18
+ * Subclasses, when subscribing to something using rxjs, have to add pipe takeUntil(this.stop$),
19
+ * so everything will be unsubscribed when stopping input
20
+ */
21
+ protected readonly stop$: Subject<void>;
22
+ /**
23
+ * A public getter that returns the running state of the Input.
24
+ */
25
+ get running(): boolean;
26
+ /**
27
+ * An asynchronous method that starts the input. Do not override it
28
+ * @param args - An array of input arguments for the start method.
29
+ * @returns A Promise that resolves when the input is started.
30
+ */
31
+ start(...args: TStartParams): Promise<void>;
32
+ /**
33
+ * An asynchronous method that stops the input. Do not override it
34
+ * @param args - An array of input arguments for the stop method.
35
+ * @returns A Promise that resolves when the input is stopped.
36
+ */
37
+ stop(...args: TStopParams): Promise<void>;
38
+ /**
39
+ * An abstract asynchronous method that starts the input.
40
+ * @param args - An array of input arguments for the start method.
41
+ * @returns A Promise that resolves when the process is started.
42
+ */
43
+ protected abstract startInternal(...args: TStartParams): Promise<void>;
44
+ /**
45
+ * An asynchronous method that stops the input.
46
+ * @param args - An array of input arguments for the stop method.
47
+ * @returns A Promise that resolves when the process is stopped.
48
+ */
49
+ protected stopInternal(...args: TStopParams): Promise<void>;
50
+ }
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Input = void 0;
13
+ const rxjs_1 = require("rxjs");
14
+ /**
15
+ * An abstract class that provides basic implementation for Input class.
16
+ * Input is an entity for handling input from user, such as mouse movements, key presses etc.
17
+ * Inputs are not bound to World-s and working independently by design.
18
+ *
19
+ * TStartParams - A type representing an array of input arguments for the start method. Items are recommended to be named.
20
+ *
21
+ * TStopParams - A type representing an array of input arguments for the stop method. Items are recommended to be named.
22
+ */
23
+ class Input {
24
+ constructor() {
25
+ /**
26
+ * A private boolean that represents the running state of the process.
27
+ */
28
+ this._running = false;
29
+ /**
30
+ * A protected subject that emits a void value when the process is stopped.
31
+ * Subclasses, when subscribing to something using rxjs, have to add pipe takeUntil(this.stop$),
32
+ * so everything will be unsubscribed when stopping input
33
+ */
34
+ this.stop$ = new rxjs_1.Subject();
35
+ }
36
+ /**
37
+ * A public getter that returns the running state of the Input.
38
+ */
39
+ get running() {
40
+ return this._running;
41
+ }
42
+ /**
43
+ * An asynchronous method that starts the input. Do not override it
44
+ * @param args - An array of input arguments for the start method.
45
+ * @returns A Promise that resolves when the input is started.
46
+ */
47
+ start(...args) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ if (this.running) {
50
+ return;
51
+ }
52
+ yield this.startInternal(...args);
53
+ this._running = true;
54
+ });
55
+ }
56
+ /**
57
+ * An asynchronous method that stops the input. Do not override it
58
+ * @param args - An array of input arguments for the stop method.
59
+ * @returns A Promise that resolves when the input is stopped.
60
+ */
61
+ stop(...args) {
62
+ return __awaiter(this, void 0, void 0, function* () {
63
+ if (!this.running) {
64
+ return;
65
+ }
66
+ this.stop$.next();
67
+ yield this.stopInternal(...args);
68
+ this._running = false;
69
+ });
70
+ }
71
+ /**
72
+ * An asynchronous method that stops the input.
73
+ * @param args - An array of input arguments for the stop method.
74
+ * @returns A Promise that resolves when the process is stopped.
75
+ */
76
+ stopInternal(...args) {
77
+ return __awaiter(this, void 0, void 0, function* () { });
78
+ }
79
+ }
80
+ exports.Input = Input;
@@ -0,0 +1,45 @@
1
+ import { Input } from './input';
2
+ import { Observable } from 'rxjs';
3
+ /**
4
+ * A main keyboard input: it does not have own key bindings, but provides an API to bind keys.
5
+ * It is responsible for listening key up/down events (when running!) and emit the events to subscribers.
6
+ * Every World entity has its own dedicated instance of Keyboard input, which is running only when the world is running
7
+ */
8
+ export declare class KeyboardInput extends Input {
9
+ private bindings;
10
+ /**
11
+ * Creates a new instance of the `KeyboardInput` class.
12
+ */
13
+ constructor();
14
+ protected startInternal(): Promise<void>;
15
+ protected stopInternal(): Promise<void>;
16
+ /**
17
+ * Creates an observable that emits a boolean whenever a key with the given code is pressed or released
18
+ * @param code The key code to bind the observable to
19
+ * @returns An observable that emits true when the key is pressed and false when it's released
20
+ */
21
+ bind(code: string): Observable<boolean>;
22
+ /**
23
+ * Creates an observable that emits a boolean indicating whether any of the keys with the given codes are pressed or released.
24
+ * Should be used when you have more than one keys, responsible for the same action.
25
+ * @param codes The key codes to bind the observable to
26
+ * @returns An observable that emits true when any of the keys are pressed and false when they're all released
27
+ */
28
+ bindMany(...codes: string[]): Observable<boolean>;
29
+ /**
30
+ * Emulates a key down event for the given key code
31
+ * @param code The key code to emulate
32
+ */
33
+ emulateKeyDown(code: string): void;
34
+ /**
35
+ * Emulates a key up event for the given key code
36
+ * @param code The key code to emulate
37
+ */
38
+ emulateKeyUp(code: string): void;
39
+ /**
40
+ * Emulates a key press event (down and up) for the given key code
41
+ * @param code The key code to emulate
42
+ */
43
+ emulateKeyPress(code: string): void;
44
+ private handleKeys;
45
+ }
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.KeyboardInput = void 0;
13
+ const input_1 = require("./input");
14
+ const rxjs_1 = require("rxjs");
15
+ const operators_1 = require("rxjs/operators");
16
+ /**
17
+ * A main keyboard input: it does not have own key bindings, but provides an API to bind keys.
18
+ * It is responsible for listening key up/down events (when running!) and emit the events to subscribers.
19
+ * Every World entity has its own dedicated instance of Keyboard input, which is running only when the world is running
20
+ */
21
+ class KeyboardInput extends input_1.Input {
22
+ /**
23
+ * Creates a new instance of the `KeyboardInput` class.
24
+ */
25
+ constructor() {
26
+ super();
27
+ this.bindings = {};
28
+ this.handleKeys = this.handleKeys.bind(this);
29
+ }
30
+ startInternal() {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ window.addEventListener('keydown', this.handleKeys);
33
+ window.addEventListener('keyup', this.handleKeys);
34
+ });
35
+ }
36
+ stopInternal() {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ window.removeEventListener('keydown', this.handleKeys);
39
+ window.removeEventListener('keyup', this.handleKeys);
40
+ });
41
+ }
42
+ /**
43
+ * Creates an observable that emits a boolean whenever a key with the given code is pressed or released
44
+ * @param code The key code to bind the observable to
45
+ * @returns An observable that emits true when the key is pressed and false when it's released
46
+ */
47
+ bind(code) {
48
+ if (!this.bindings[code]) {
49
+ this.bindings[code] = [];
50
+ }
51
+ const subj = new rxjs_1.BehaviorSubject(false);
52
+ this.bindings[code].push(subj);
53
+ return subj.pipe((0, rxjs_1.finalize)(() => {
54
+ this.bindings[code].splice(this.bindings[code].indexOf(subj), 1);
55
+ subj.complete();
56
+ }));
57
+ }
58
+ /**
59
+ * Creates an observable that emits a boolean indicating whether any of the keys with the given codes are pressed or released.
60
+ * Should be used when you have more than one keys, responsible for the same action.
61
+ * @param codes The key codes to bind the observable to
62
+ * @returns An observable that emits true when any of the keys are pressed and false when they're all released
63
+ */
64
+ bindMany(...codes) {
65
+ if (codes.length == 0) {
66
+ console.warn('[KeyboardController] bindMany called without any key code');
67
+ return rxjs_1.NEVER;
68
+ }
69
+ if (codes.length == 1) {
70
+ return this.bind(codes[0]);
71
+ }
72
+ const subjects = [];
73
+ for (const code of codes) {
74
+ if (!this.bindings[code]) {
75
+ this.bindings[code] = [];
76
+ }
77
+ const subj = new rxjs_1.BehaviorSubject(false);
78
+ this.bindings[code].push(subj);
79
+ subjects.push(subj);
80
+ }
81
+ return (0, rxjs_1.combineLatest)(subjects).pipe((0, rxjs_1.finalize)(() => {
82
+ for (let i = 0; i < codes.length; i++) {
83
+ this.bindings[codes[i]].splice(this.bindings[codes[i]].indexOf(subjects[i]), 1);
84
+ subjects[i].complete();
85
+ }
86
+ }), (0, operators_1.map)(values => values.includes(true)));
87
+ }
88
+ /**
89
+ * Emulates a key down event for the given key code
90
+ * @param code The key code to emulate
91
+ */
92
+ emulateKeyDown(code) {
93
+ if (!this.running) {
94
+ return;
95
+ }
96
+ for (const subj of this.bindings[code] || []) {
97
+ subj.next(true);
98
+ }
99
+ }
100
+ /**
101
+ * Emulates a key up event for the given key code
102
+ * @param code The key code to emulate
103
+ */
104
+ emulateKeyUp(code) {
105
+ if (!this.running) {
106
+ return;
107
+ }
108
+ for (const subj of this.bindings[code] || []) {
109
+ subj.next(false);
110
+ }
111
+ }
112
+ /**
113
+ * Emulates a key press event (down and up) for the given key code
114
+ * @param code The key code to emulate
115
+ */
116
+ emulateKeyPress(code) {
117
+ this.emulateKeyDown(code);
118
+ this.emulateKeyUp(code);
119
+ }
120
+ handleKeys(e) {
121
+ if (e.type != 'keydown' && e.type != 'keyup') {
122
+ return;
123
+ }
124
+ const pressed = e.type == 'keydown';
125
+ for (const subj of this.bindings[e.code] || []) {
126
+ subj.next(pressed);
127
+ }
128
+ }
129
+ }
130
+ exports.KeyboardInput = KeyboardInput;
@@ -0,0 +1,57 @@
1
+ import { Input } from './input';
2
+ import { Observable } from 'rxjs';
3
+ import { Point2 } from '../models/points';
4
+ /**
5
+ * Options for pointer lock in a MouseInput.
6
+ *
7
+ * ignoreMovementWhenNotLocked: Whether to ignore mouse movement when pointer lock is not active.
8
+ *
9
+ * canvas: The canvas element to request pointer lock on.
10
+ */
11
+ export declare type MouseInputPointLockOptions = {
12
+ ignoreMovementWhenNotLocked: boolean;
13
+ canvas: HTMLCanvasElement;
14
+ };
15
+ /**
16
+ * Options for a MouseInput.
17
+ *
18
+ * pointerLock: The options for pointer lock. Do not provide it to disable pointer lock functionality
19
+ */
20
+ export declare type MouseInputOptions = {
21
+ pointerLock?: MouseInputPointLockOptions;
22
+ };
23
+ /**
24
+ * A class representing mouse input.
25
+ */
26
+ export declare class MouseInput extends Input<[], [unlockPointer?: boolean]> {
27
+ private readonly options;
28
+ /**
29
+ * An observable of the change in the x position of the mouse.
30
+ */
31
+ get deltaX$(): Observable<number>;
32
+ /**
33
+ * An observable of the change in the y position of the mouse.
34
+ */
35
+ get deltaY$(): Observable<number>;
36
+ /**
37
+ An observable of the change in the position of the mouse.
38
+ */
39
+ get delta$(): Observable<Point2>;
40
+ private _delta$;
41
+ private stopped$;
42
+ /**
43
+ Creates an instance of MouseInput.
44
+ @param {MouseInputOptions} options - The options for the MouseInput.
45
+ */
46
+ constructor(options?: MouseInputOptions);
47
+ protected startInternal(): Promise<void>;
48
+ /**
49
+ Stop listening for mouse movement events.
50
+ @param {boolean} [unlockPointer=true] - Whether to exit pointer lock.
51
+ */
52
+ protected stopInternal(unlockPointer?: boolean): Promise<void>;
53
+ /**
54
+ Request pointer lock on the canvas element.
55
+ */
56
+ private canvasClickListener;
57
+ }