All files / src/x x.ts

0% Statements 0/68
0% Branches 0/42
0% Functions 0/13
0% Lines 0/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import {DomWatcher} from '../dom/dom-watcher';
import * as func from '../func/func';
import {Raf} from '../raf/raf';
import type {XGameObject} from './x-game-object';
import {XPointer} from './x-pointer';
import {XStage} from './x-stage';
import {XText} from './x-text';
 
declare global {
  interface Window {
    X: X;
    X_STAGE: XStage;
  }
}
 
interface XConfig {
  canvasElement: HTMLCanvasElement;
  debugMode?: boolean;
}
 
/**
 * # X is a mini canvas + dom 2d engine within degu.
 *
 * ```ts
 *
 *
 *
 * ```
 * @unstable
 */
export class X {
  private canvasElement: HTMLCanvasElement;
  private width: number;
  private height: number;
  private context: CanvasRenderingContext2D;
  private raf: Raf;
  private dpr: number;
  private pointer: XPointer;
  public stage: XStage;
  private debugMode: boolean;
  private mouseCoordsTextDebugObject: XText;
  private watcher: DomWatcher;
  private stageColor: string | null;
 
  constructor(config: XConfig) {
    this.canvasElement = config.canvasElement;
    // Note the ! at the end.  Required to force typescript to assume
    // getContext('2d') never returns null.
    this.context = this.canvasElement.getContext('2d')!;
 
    // Force set the canvas size. When you set the canvas size via css,
    // css stretches the pixels within the canvas.
    // Setting it as such, forces the correct size.
    this.dpr = window.devicePixelRatio || 1;
    this.canvasElement.width = 0;
    this.canvasElement.height = 0;
    this.width = 0;
    this.height = 0;
    this.resize();
 
    this.watcher = new DomWatcher();
    this.watcher.add({
      element: window,
      on: 'resize',
      callback: this.resize.bind(this),
    });
 
    this.debugMode = func.setDefault(config.debugMode, false);
 
    // Create the main stage sprite.
    this.stage = new XStage();
    this.stage.attachToCanvas(this.canvasElement);
 
    // If we want to debug the mouse coords, add a text object to
    // display.
    this.mouseCoordsTextDebugObject = new XText({
      // Add it at a really high index.
      zIndex: 999999,
    });
    this.mouseCoordsTextDebugObject.debugObject = true;
 
    if (this.debugMode) {
      window['X'] = this;
      window['X_STAGE'] = this.stage;
      this.stage.addChild(this.mouseCoordsTextDebugObject);
    }
 
    /**
     * The background color.
     */
    this.stageColor = null;
 
    // Create the main pointer.
    this.pointer = new XPointer(this.canvasElement);
 
    this.raf = new Raf(() => {
      this.gameLoop();
 
      // Update the mouse display to follow the mouse and display the
      // current coordinates.
      if (this.debugMode && this.mouseCoordsTextDebugObject) {
        this.mouseCoordsTextDebugObject.setPosition(
          this.pointer.x + 20,
          this.pointer.y + 20
        );
        this.mouseCoordsTextDebugObject.setText(
          `x: ${this.pointer.x}, y: ${this.pointer.y}`
        );
      }
    });
  }
 
  /**
   * The background color for the stage.
   * @param color
   */
  setStageColor(color: string) {
    this.stageColor = color;
  }
 
  resize() {
    this.dpr = window.devicePixelRatio || 1;
    this.canvasElement.width = this.canvasElement.offsetWidth * this.dpr;
    this.canvasElement.height = this.canvasElement.offsetHeight * this.dpr;
    this.width = this.canvasElement.offsetWidth * this.dpr;
    this.height = this.canvasElement.offsetHeight * this.dpr;
  }
 
  getPointer(): XPointer {
    return this.pointer;
  }
 
  clear() {
    this.context.clearRect(0, 0, this.width, this.height);
  }
 
  /**
   * The main engine loop.  Here we call through all the
   * sprites on the main stage.
   */
  gameLoop() {
    //Clear the canvas.
    this.clear();
 
    if (this.stageColor) {
      this.context.fillStyle = this.stageColor;
      this.context.fillRect(0, 0, this.width, this.height);
    }
 
    // Update the positions of each object
    this.stage.children.forEach((gameObject: XGameObject) => {
      gameObject.updatePositions();
    });
 
    // Render each object.
    this.stage.children.forEach((gameObject: XGameObject) => {
      this.renderGameObject(gameObject);
    });
  }
 
  /**
   * Renders a given sprite onto the canvas.  This is sort of imagined like
   * a stamping process in which we turn, scale, change alpha of the context
   * itself and stamp out the sprite per frame.
   * @param gameObject
   */
  renderGameObject(gameObject: XGameObject) {
    // Whether this gameObject is off screen.
    const shouldRender =
      gameObject.visible &&
      gameObject.gx < this.width + gameObject.width &&
      gameObject.gx + gameObject.width >= -gameObject.width &&
      gameObject.gy < this.height + gameObject.height &&
      gameObject.gy + gameObject.height >= -gameObject.height;
 
    if (!shouldRender) {
      return;
    }
 
    // If this object is interactable, check the collision state
    // with the pointer.
    let colliding = false;
    if (gameObject.interactable) {
      colliding = this.pointer.testCollidingWithGameObject(gameObject);
 
      if (colliding && this.pointer.isMouseDown) {
        gameObject.onMouseDown && gameObject.onMouseDown(gameObject);
      }
      if (colliding && !this.pointer.isMouseDown) {
        gameObject.onMouseUp && gameObject.onMouseUp(gameObject);
      }
      if (colliding) {
        gameObject.onMouseMove && gameObject.onMouseMove(gameObject);
      }
    }
 
    this.context.save();
    // this.context.translate(
    //         this.canvasElement.width  / 2,
    //         this.canvasElement.height / 2)
 
    // Scale to aspect ratio first.
    this.context.scale(this.dpr, this.dpr);
 
    // Adjust alpha
    this.context.globalAlpha = gameObject.alpha;
 
    // Move first
    this.context.translate(
      // gameObject.x + (gameObject.width * gameObject.anchorX),
      // gameObject.y + (gameObject.height * gameObject.anchorY)
      ~~gameObject.anchorGx,
      ~~gameObject.anchorGy
    );
 
    // Then rotate
    // Not sure why but canvas calculations rotation in anticlockwise manner?
    // We counter this by interving the rotation value.
    this.context.rotate(-gameObject.rotation);
 
    // Now scale
    this.context.scale(gameObject.scaleX, gameObject.scaleY);
 
    // Call the gameObject render method to figure out how to draw this
    // GameObject.
    gameObject.render(this.context);
 
    // Renders debugging outlines for this object if it is colliding.
    if (this.debugMode && !gameObject.debugObject && colliding) {
      gameObject.renderDebuggingOutlines(this.context);
    }
 
    this.context.restore();
 
    // Now loop through each child and paint it out.
    gameObject.children.forEach((childGameObject) => {
      this.renderGameObject(childGameObject);
    });
  }
 
  /*
   * Adds a watcher callback to the raf loop.
   */
  onTick(callback: Function) {
    this.raf.watch(callback);
  }
 
  /**
   * Starts the main game loop.
   */
  start() {
    this.raf.start();
  }
}