summaryrefslogtreecommitdiffstats
path: root/src/view/MapView.ts
blob: a12d9d4ac1348ae33779ad6285cfd30729addb8a (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
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
'use strict';


import * as util from '../util';
import EntityPosition from '../model/EntityPosition';
import MapData from '../model/MapData';
import Position from '../model/Position';


const tileSize = 32;

const body = document.getElementsByTagName('body')[0];


function loadImage(url: string): Promise<HTMLImageElement> {
        return new Promise(function(resolve, reject) {
                var img = new Image();
                img.addEventListener('load', () => { resolve(img); });
                img.addEventListener('error', () => { reject(Error('Failed to load ' + url)); });
                img.src = url;
        });
}

function loadImages(imgs: {[key: string]: string}): Promise<{[key: string]: HTMLImageElement}> {
        return util.mapPromises(_.mapValues(imgs, loadImage));
}

function loadTiles(tiles: {[key: string]: {file: string}}): Promise<{[key: string]: HTMLImageElement}> {
        return loadImages(_.mapValues(tiles, (t) => `resources/sprite/tile/${t.file}.png`));
}

function loadEntities(entities: EntityPosition[]): Promise<{[key: string]: HTMLImageElement}> {
        var p: {[key: string]: Promise<HTMLImageElement>} = {};

        entities.forEach(e => {
                p[e.entity.name] = loadImage(`resources/sprite/entity/${e.entity.name}.png`);
        });

        return util.mapPromises(p);
}

function entityPosition(e: EntityPosition, time: number): Position {
        if (e.transition) {
                var t = e.transition;
                var d = (time - t.start) / (t.end-t.start);

                return new Position(
                        (1-d) * t.orig.x + d * t.dest.x,
                        (1-d) * t.orig.y + d * t.dest.y
                );
        }
        else {
                return e.position;
        }
}

function tiles(n: number) {
        return Math.round(tileSize*n);
}


export default class MapView {
        private redrawPending: boolean = false;

        private canvas: HTMLCanvasElement;
        private ctx: CanvasRenderingContext2D;
        private scale: number;

        private tiles: {[key: string]: HTMLImageElement};
        private entitySprites: {[key: string]: HTMLImageElement};

        constructor(private map: MapData,
                    private entities: {[key: string]: EntityPosition},
                    private getOrigin: () => EntityPosition,
                    private updateState: (time: number) => void) {
                this.canvas = document.createElement('canvas');
                this.canvas.style.position = 'absolute';
                body.appendChild(this.canvas);

                this.ctx = this.canvas.getContext('2d');

                window.addEventListener('resize', () => this.setSize());
                this.setSize();

                var tilesReady = loadTiles(map.tiles).then((tiles) => {
                        this.tiles = tiles;
                });

                var entitiesReady = loadEntities(this.getEntities()).then((entities) => {
                        this.entitySprites = entities;
                });

                Promise.all([tilesReady, entitiesReady]).then(() => {
                        this.redraw();
                });
        }

        private getEntities(): EntityPosition[] {
                return _.values<EntityPosition>(this.entities);
        }

        private setSize() {
                var e = document.documentElement;
                var w = window.innerWidth || e.clientWidth || body.clientWidth;
                var h = window.innerHeight || e.clientHeight || body.clientHeight;

                this.canvas.width = w;
                this.canvas.height = h;

                var pixels = Math.max(w/20, h/15.0);
                this.scale = Math.ceil(pixels / tileSize);

                this.redraw()
        }

        private drawTile(x: number, y: number, tile: HTMLImageElement) {
                if (!tile)
                        return;

                this.ctx.drawImage(tile, x*this.scale, y*this.scale, tileSize*this.scale, tileSize*this.scale);
        }

        private drawEntity(e: EntityPosition, time: number): boolean {
                var sprite = this.entitySprites[e.entity.name];
                if (!sprite)
                        return false;

                var p = entityPosition(e, time);

                this.ctx.drawImage(
                        sprite,
                        tiles(e.direction), 0,
                        tileSize, tileSize,
                        tiles(p.x)*this.scale, tiles(p.y)*this.scale,
                        tileSize*this.scale, tileSize*this.scale
                );

                return !!e.transition;
        }

        private setOrigin(time: number) {
                var origin = entityPosition(this.getOrigin(), time);

                var w = this.canvas.width;
                var h = this.canvas.height;

                this.ctx.translate(Math.round(w/2), Math.round(h/2));
                this.ctx.translate(-tiles(origin.x + 0.5)*this.scale, -tiles(origin.y + 0.5)*this.scale);
        }

        private draw(time: number) {
                this.updateState(time);

                this.redrawPending = false;

                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

                if (!this.tiles || !this.entitySprites)
                        return;

                this.ctx.save();

                this.setOrigin(time);

                (<any>this.ctx).mozImageSmoothingEnabled = false;
                (<any>this.ctx).webkitImageSmoothingEnabled = false;
                (<any>this.ctx).msImageSmoothingEnabled = false;
                (<any>this.ctx).imageSmoothingEnabled = false;

                this.map.layers.forEach((layer) => {
                        let y = 0;

                        layer.forEach((row) => {
                                let x = 0;

                                for (let tile in row) {
                                        this.drawTile(x, y, this.tiles[row[tile]]);
                                        x += tileSize;
                                }

                                y += tileSize;
                        });
                });

                var animate = false;

                this.getEntities().forEach(e => {
                        if (this.drawEntity(e, time))
                                animate = true;
                });

                this.ctx.restore();

                if (animate)
                        this.redraw();
        }

        redraw() {
                if (this.redrawPending)
                        return;

                this.redrawPending = true;
                window.requestAnimationFrame((time: number) => this.draw(time));
        }
}