aboutsummaryrefslogtreecommitdiff
path: root/lib/systems/control_mapper.js
blob: c0ab05ec1de4362260bb18201199a911b1facfce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import { System } from '@serpentity/serpentity';

import ControllableNode from '../nodes/controllable';

const internals = {
  gamepadState: {
  },
  keyboardState: {
  }
};

/**
 * Updates control status based on the controller map
 *
 * @extends {external:Serpentity.System}
 * @class ControlMapperSystem
 * @param {object} config a configuration object to extend.
 */
export default class ControlMapperSystem extends System {

  constructor(config = {}) {

    super();

    /**
     * The node collection of controllable entities
     *
     * @property {external:Serpentity.NodeCollection} controllables
     * @instance
     * @memberof RenderSystem
     */
    this.controllables = null;

    this._initializeKeyboard();
    this._initializeGamepad();
  }

  /**
   * Initializes system when added. Requests controllable nodes.
   *
   * @function added
   * @memberof RenderSystem
   * @instance
   * @param {external:Serpentity.Engine} engine the serpentity engine to
   * which we are getting added
   */
  added(engine) {

    this.controllables = engine.getNodes(ControllableNode);
  }

  /**
   * Clears system resources when removed.
   *
   * @function removed
   * @instance
   * @memberof RenderSystem
   */
  removed() {

    this.controllables = null;
  }

  /**
   * Runs on every update of the loop. Maps the actions given the current state of the inputs
   *
   * @function update
   * @instance
   * @param {Number} currentFrameDuration the duration of the current
   * frame
   * @memberof RenderSystem
   */
  update(currentFrameDuration) {

    this._updateGamepads();

    for (const controllable of this.controllables) {
      for (const map of controllable.controlMap.map) {
        if (map.source.type === 'keyboard') {
          this._setValue(controllable.entity, map.target, !!internals.keyboardState[map.source.index]);
        }

        if (map.source.type === 'gamepad') {
          const gamepad = internals.gamepadState[map.source.gamepadNumber];
          if (gamepad) {
            const source = gamepad[map.source.gamepadInputSource];
            source && this._setValue(controllable.entity, map.target, source[map.source.index]);
          }
        }
      }
    }
  }

  // Listens to keyboard to update internal map

  _initializeKeyboard() {

    window.addEventListener('keydown', (event) => {

      internals.keyboardState[event.keyCode] = true;
    });

    window.addEventListener('keyup', (event) => {

      internals.keyboardState[event.keyCode] = false;
    });
  }

  // Requests gamepad access and binds to the events

  _initializeGamepad() {

    window.addEventListener('gamepadconnected', (event) => {

      internals.gamepadState[event.gamepad.index] = event.gamepad;
      window.gamepad = event.gamepad;
    });

    window.addEventListener('gamepaddisconnected', (event) => {

      delete internals.gamepadState[event.gamepad.index];
    });
  }

  // Update Gamepad

  _updateGamepads() {

    const gamepads = navigator.getGamepads();
    for (const index of Object.keys(internals.gamepadState)) {
      internals.gamepadState[index] = gamepads[index];
    }
  }

  // Sets the value to a target

  _setValue(entity, target, value) {

    const component = entity.getComponent(target.component);

    if (component) {
      const keyFragments = target.property.split('.');
      let currentObject = component;
      for (const keyFragment of keyFragments.slice(0, keyFragments.length - 1)) {
        currentObject = currentObject[keyFragment] = currentObject[keyFragment] || {};
      }


      const finalValue = !!target.value ? target.value(value) : value;
      const finalProperty = keyFragments.pop();
      currentObject[finalProperty] += finalValue;
    }
  }
}