All files / src camera.js

29.37% Statements 74/252
14.29% Branches 1/7
12.5% Functions 1/8
29.37% Lines 74/252

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 2531x 1x 1x 3x 3x 3x 3x                   3x 3x                       3x                                   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x       2x 2x   2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                                                                                                                                                             3x 3x 3x 3x                                           3x                                                               3x            
/** A module for dealing with perspective and rendering */
export const Camera = {
  setCanvasResolution(canvas, canvasWidth, canvasHeight) {
    /* eslint-disable no-param-reassign */
    // Set the new rounded size
    canvas.style.width = canvasWidth;
    canvas.style.height = canvasHeight;
    // Set the resolution
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    /* eslint-enable no-param-reassign */
  },

  // This is used when initializing the game world and should only be called once
  getCanvasData(canvas) {
    const bounds = canvas.getBoundingClientRect();
    const ratio = bounds.width / bounds.height;
    const canvasWidth = Math.round(Math.min(bounds.width, 800) * ratio);
    const canvasHeight = Math.round(Math.min(bounds.height, 800));
    const context = canvas.getContext('2d');

    return {
      context, bounds, ratio, canvasWidth, canvasHeight,
    };
  },

  getContextPixels({ context, canvasWidth, canvasHeight }) {
    const imageData = context.getImageData(0, 0, canvasWidth, canvasHeight);
    const allAlpha = imageData.data
      .filter((_, index) => (index + 1) % 4 === 0);
    const pixels = {};

    // Split them into the map for faster access
    for (let i = 0; i < imageData.height; i++) {
      const start = i * imageData.width;
      const slice = allAlpha.slice(start, start + imageData.width);
      if (slice.every((t) => t === 0)) { continue; }
      pixels[i] = Uint8Array.from(allAlpha.slice(start, start + imageData.width));
    }
    return pixels;
  },

  /**
   * updateViewport
   *
   * @param {Object} arguments
   * @param {Viewport=} arguments.oldViewport - old viewport which will be returned if there
   *                                    is no difference between the new and the old viewport
   * @param {number} arguments.canvasWidth - absolute width of the canvas/screen
   * @param {number} arguments.canvasHeight - absolute height of the canvas/screen
   * @param {number} arguments.mapWidth - absolute width of the map
   * @param {number} arguments.mapHeight - absolute height of the map
   * @param {number} arguments.scale - an integer, 1 => no scaling
   */
  updateViewport({
    oldViewport, player, mapWidth, mapHeight, scale, canvasWidth, canvasHeight,
  }) {
    const viewportWidth = canvasWidth / scale;
    const viewportHeight = canvasHeight / scale;
 
    // Constantly updating viewport
    const centerx = Math.round((player.x + player.width / 2));
    const centery = Math.round((player.y + player.height / 2));
 
    const viewport = {
      x: Math.min(
        Math.max(0, Math.round(centerx - viewportWidth / 2)),
        mapWidth - viewportWidth,
      ),
      y: Math.min(
        Math.max(0, Math.round(centery - viewportHeight / 2)),
        mapHeight - viewportHeight,
      ),
      width: Math.round(viewportWidth),
      height: Math.round(viewportHeight),
      scale,
    };
    if (oldViewport
        && oldViewport.x === viewport.x
        && oldViewport.y === viewport.y
        && oldViewport.width === viewport.width
        && oldViewport.height === viewport.height
        && oldViewport.scale === viewport.scale) {
      return oldViewport;
    }
    return viewport;
  },

  /**
   * updateViewport
   *
   * @param {Object} arguments
   * @param {Player} arguments.player the player
   * @param {Characters} arguments.characters Non-playable characters
   * @param {CanvasRenderingContext2D} arguments.context The active collision context scene
   * @param {Viewport} arguments.viewport The current viewport
   * @param {Viewport} arguments.[oldViewport] The viewport from last time
   */
  drawScene({
    player,
    characters,
    items,
    oldItems,
    context,
    width,
    height,
    sprites,
    viewport,
    oldViewport,
    layoutContext,
    aboveContext,
    drawActorToContext,
  }) {
    if (oldViewport !== viewport || oldItems !== items) {
      if (aboveContext) {
        aboveContext.clearRect(0, 0, width, height);
        const aboveData = sprites.above[width * viewport.scale];
        aboveContext.drawImage(
          aboveData.canvas,
          viewport.x * viewport.scale,
          viewport.y * viewport.scale,
          viewport.width * viewport.scale,
          viewport.height * viewport.scale,
          0, 0,
          viewport.width * viewport.scale,
          viewport.height * viewport.scale,
        );
      }
      const layoutData = sprites.background[width * viewport.scale];
      layoutContext.drawImage(
        layoutData.canvas,
        viewport.x * viewport.scale,
        viewport.y * viewport.scale,
        viewport.width * viewport.scale,
        viewport.height * viewport.scale,
        0, 0,
        viewport.width * viewport.scale,
        viewport.height * viewport.scale,
      );
      // Draw Items on the background
      for (let i = 0; i < items.length; i++) {
        const actor = items[i];
        if (actor.inInventory || actor.hidden) { continue; }
        if (!Camera.isWithinViewport({ viewport, actor })) { continue; }
        drawActorToContext({
          context: layoutContext,
          sprites,
          actor,
          offset: viewport,
          scale: viewport.scale,
          defaultSprite: 'itemSprite',
        });
      }
    }

    // Remove old
    context.clearRect(0, 0, width, height);

    // Draw new position player position
    drawActorToContext({
      context,
      sprites,
      actor: player,
      offset: viewport,
      scale: viewport.scale,
      defaultSprite: 'characterSprite',
    });

    for (let i = 0; i < characters.length; i++) {
      const actor = characters[i];
      if (!Camera.isWithinViewport({ viewport, actor })) { continue; }
      // Draw new position
      drawActorToContext({
        context,
        sprites,
        actor,
        offset: viewport,
        scale: viewport.scale,
        defaultSprite: 'characterSprite',
      });
    }
  },
  /**
   * drawGraph.
   *
   * @param {} args
   * @param {} args.graph the graph
   * @param {} args.context the context to draw to
   */
  drawGraph({ graph, context, viewport }) {
    // context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    graph.forEach((area) => {
      context.strokeStyle = 'black';
      context.strokeRect(
        (area.x - viewport.x) * viewport.scale,
        (area.y - viewport.y) * viewport.scale,
        area.width * viewport.scale,
        area.height * viewport.scale,
      );
      context.strokeStyle = 'red';
      area.points.forEach((point) => {
        context.strokeRect(
          (point.x - viewport.x - 1) * viewport.scale,
          (point.y - viewport.y - 1) * viewport.scale,
          2,
          2,
        );
      });
    });
  },

  drawDestinations({ characters, context, viewport }) {
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    context.fillStyle = 'black';
    const colors = ['lightblue', 'red', 'yellow', 'green', 'blue', 'brown', 'purple', 'pink', 'magenta'];
    characters.forEach((c) => {
      context.strokeStyle = 'black';
      const dest = (c.waypoints && c.waypoints[c.waypoints.length - 1]) || c.destination;
      if (!dest) { return; }
      context.fillRect(
        (dest.x - 5 - viewport.x) * viewport.scale,
        (dest.y - 5 - viewport.y) * viewport.scale,
        10 * viewport.scale,
        10 * viewport.scale,
      );
      if (!c.waypoints) { return; }
      context.strokeStyle = colors[c.waypoints.length % colors.length];
      context.beginPath();
      context.moveTo(
        (Math.round(c.x + c.width / 2) - viewport.x) * viewport.scale,
        (Math.round(c.y + c.height / 2) - viewport.y) * viewport.scale,
      );
      context.lineTo(
        (c.destination.x - viewport.x) * viewport.scale,
        (c.destination.y - viewport.y) * viewport.scale,
      );
      c.waypoints.forEach((t) => {
        context.lineTo((t.x - viewport.x) * viewport.scale, (t.y - viewport.y) * viewport.scale);
      });
      context.stroke();
    });
  },
  isWithinViewport({ viewport, actor }) {
    if (viewport.x > (actor.x + actor.width) || (viewport.x + viewport.width) < actor.x) {
      return false;
    }
    if (viewport.y > (actor.y + actor.height) || (viewport.y + viewport.height) < actor.y) {
      return false;
    }
    return true;
  },
};