-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmask.js
471 lines (471 loc) · 12.5 KB
/
mask.js
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/** This is `mask`, a tiny MIT-licensed library providing collision masks
* and thus pixel-perfect collision detection in JavaScript. Collision
* masks are read from [PBM][] files. Check the [github][] page for more
* information.
* [github]: https://github.com/startling/mask
* [PBM]: http://netpbm.sourceforge.net/doc/pbm.html
*/
/*!*/
var Mask = (function () {
"use strict";
/** Construct a `Mask`.
*
* Subclasses of `Mask` should implement, at the least, `collidesAt` and
* `clone`. All subclasses are expected to have the properties `x`, `y`,
* `w`, and `h` -- the coordinates, width, and height of a bounding box
* around the `Mask`.
*
* Examples:
*
* new Mask()
*
* @constructor
* @api public
*/
function Mask () {
this.x = this.y = this.w = this.h = 0;
}
/** Make a clone of a `Mask`.
*
* Examples:
*
* someMask.clone()
*
* @this {Mask}
* @api public
*/
Mask.prototype.clone = function () {
var other = new Mask();
other.x = this.x;
other.y = this.y;
other.w = this.w;
other.h = this.h;
return other;
};
/** Translate this `Mask` in two dimensions.
*
* Examples:
*
* someMask.translate(10, 10)
*
* @this {Mask}
* @param {Number} x x-distance
* @param {Number} y y-distance
* @api public
*/
Mask.prototype.translate = function (x, y) {
this.x += x;
this.y += y;
};
/** Make a copy of this `Mask` translated to the coordinates given.
*
* Examples:
*
* someMask.at(10, 10)
*
* @this {Mask}
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @return {Mask}
* @api public
*/
Mask.prototype.at = function (x, y) {
var other = this.clone();
other.x = x;
other.y = y;
return other;
};
/** Mask a copy of this `Mask` translated in two dimensions.
*
* Examples:
*
* someMask.translated(10, 10)
*
* @this {Mask}
* @param {Number} x x-distance
* @param {Number} y y-distance
* @return {Mask}
* @api public
*/
Mask.prototype.translated = function (x, y) {
var other = this.clone();
other.translate(x, y);
return other;
};
/** Test whether a Mask is completely contained within another.
* Examples:
*
* someMask.within(new Mask.Box(10, 10))
*
* @this {Mask}
* @param {Mask} b The containing Mask.
* @api public
*/
Mask.prototype.within = function (b) {
for (var x = this.x; x < this.w + this.x; x++) {
for (var y = this.y; y < this.h + this.y; y++) {
if (this.collidesAt(x, y) &&
!b.collidesAt(x, y)) {
return false;
}
}
}
return true;
};
/** Test whether this mask collides at the given location.
*
* Examples:
*
* new Mask.Box(10, 10).collidesAt(5, 5)
*
* @this {Mask}
* @param {Number} x x-coordinate
* @param {Number} y y-coordinate
* @return {Mask}
* @api public
*/
Mask.prototype.collidesAt = function (x, y) {
return false;
};
/** Create an object representing the intersection of the bounding
* boxes of two objects.
*
* @api private
*/
function intersection (a, b) {
var a_2 = {x: a.x + a.w, y: a.y + a.h};
var b_2 = {x: b.x + b.w, y: b.y + b.h};
var overlap = {x: a.x > b.x ? a.x : b.x,
y: a.y > b.y ? a.y : b.y};
overlap.w = (a_2.x < b_2.x ? a_2.x : b_2.x) - overlap.x;
overlap.h = (a_2.y < b_2.y ? a_2.y : b_2.y) - overlap.y;
return overlap;
}
/** Test whether two Masks collide.
*
* Examples:
*
* Mask.collision(new Mask.Box(5, 5), new Mask.Box(10, 10))
*
* @param {Mask} a
* @param {Mask} b
* @api public
*/
Mask.collision = function (a, b) {
var intersect = intersection(a, b);
for (var x = intersect.x; x < intersect.x + intersect.w; x++) {
for (var y = intersect.y; y < intersect.y + intersect.h; y++) {
if (a.collidesAt(x, y) &&
b.collidesAt(x, y)) {
return true;
}
}
}
return false;
};
/** Some callbacks expect a `Mask`.
* @callback MaskCallback
* @param {Mask} the collision map
* @api private
*/
/** A mask taken from a PBM image.
*
* Examples:
*
* new Mask.PBM.load(arrayBuffer, callback);
*
* @constructor
* @api public
*/
Mask.PBM = function () {
this.x = 0;
this.y = 0;
this.w = 0;
this.h = 0;
this.data = [];
};
Mask.PBM.prototype = new Mask();
Mask.PBM.prototype.clone = function () {
var other = new Mask.PBM();
other.x = this.x;
other.y = this.y;
other.w = this.w;
other.h = this.h;
other.data = this.data;
return other;
};
Mask.PBM.prototype.collidesAt = function (x, y) {
return !!this.data[x - this.x] &&
!!this.data[x - this.x][y - this.y];
};
/** Skip every byte matching a regular expression.
*
* @api private
* @param {RegExp} regex regular expression
* @param {Uint8Buffer} bytes character data
* @param {object} state parser state
*/
function skipRegex (regex, bytes, state) {
for (; state.index < bytes.byteLength; state.index++) {
var here = String.fromCharCode(bytes[state.index]);
if (!here.match(regex)) {
break;
}
}
}
/** Find all the leading characters matching a regular expression and
* stick them in an array.
*
* @api private
* @param {RegExp} regex regular expression
* @param {Uint8Buffer} bytes character data
* @param {object} state parser state
* @return {Array}
*/
function accumulateRegex (regex, bytes, state) {
var accumulator = [];
for (; state.index < bytes.byteLength; state.index++) {
var here = String.fromCharCode(bytes[state.index]);
if (here.match(regex)) {
accumulator.push(here);
} else {
break;
}
}
return accumulator;
}
/** Skip the parts that come after a PBM signature -- whitespace and any
* number of comments.
*
* @api private
* @param {Uint8Buffer} bytes character data
* @param {object} state parser state
*/
function skipPostSignature (bytes, state) {
skipRegex(/\s/, bytes, state);
var here = String.fromCharCode(bytes[state.index]);
while (here === '#') {
state.index++;
skipRegex(/[^\n]/, bytes, state);
skipRegex(/\s/, bytes, state);
here = String.fromCharCode(bytes[state.index]);
}
}
/** Create a `Mask` from an Uint8Array taken semantically as an ASCII PBM image.
*
* @param {Uint8Buffer} bytes PBM image data.
* @param {MaskCallback} callback
* @api private
*/
var fromASCIIPBM = function (m, bytes, callback) {
var state = {index: 2};
// Skip the spaces and comments post-signature.
skipPostSignature(bytes, state);
var width = accumulateRegex(/\d/, bytes, state).join("");
skipRegex(/\s/, bytes, state);
// Read numbers and stick them into 'height' until whitespace.
var height = accumulateRegex(/\d/, bytes, state).join("");
skipRegex(/\s/, bytes, state);
// Initialize the mask.
m.w = parseInt(width, 10);
m.h = parseInt(height, 10);
m.data = [];
// Read 0 and 1 until the end of the file, skipping everything else.
for (var y = 0; y < m.h; y++) {
var row = [];
for (var x = 0; x < m.w; x++) {
if (state.index >= bytes.byteLength) {
break;
}
while (state.index < bytes.byteLength) {
var here = String.fromCharCode(bytes[state.index]);
state.index += 1;
if (here === '0') {
row.push(false);
break;
} else if (here === '1') {
row.push(true);
break;
}
}
}
m.data.push(row);
}
return callback(m);
};
/** Create a `Mask` from an Uint8Array taken semantically as an binary
* PBM image.
*
* @param {Uint8Buffer} bytes PBM image data.
* @param {MaskCallback} callback
* @api private
*/
var fromBinaryPBM = function (m, bytes, callback) {
var bits = [];
var state = {index: 2};
// Skip the spaces and comments post-signature.
skipPostSignature(bytes, state);
// Read numbers and stick them into 'width' until whitespace.
var width = accumulateRegex(/\d/, bytes, state).join("");
skipRegex(/\s/, bytes, state);
// Read numbers and stick them into 'height' until whitespace.
var height = accumulateRegex(/\d/, bytes, state).join("");
skipRegex(/\s/, bytes, state);
// Initialize the mask.
m.w = parseInt(width, 10);
m.h = parseInt(height, 10);
// Read each byte, in sequence.
for (; state.index < bytes.byteLength; state.index++) {
if (bits.length === m.h - 1 &&
bits[bits.length - 1].length === m.w - 1) {
break;
}
else if (!bits.length || bits[bits.length - 1].length >= m.w) {
bits.push([]);
}
for (var b = 0; b < 8; b++) {
if (bits[bits.length - 1].length < m.w) {
var bit = Boolean((bytes[state.index] >> (7 - b)) & 0x01);
bits[bits.length - 1].push(bit);
}
}
}
m.data = bits;
callback(m);
};
/** Create a `Mask` from a PBM image at some URL.
*
* Examples:
*
* Mask.PBM.url("http://example.com/mask.pbm", callback)
*
* @param {String} url A URL pointing to a PBM image.
* @param {MaskCallback} callback
* @api public
*/
Mask.PBM.url = function (url, callback) {
var req = new XMLHttpRequest();
req.onload = function (ev) {
if (req.response) {
var m = new Mask.PBM();
return m.load(req.response, callback);
} else {
// No response.
return callback(null, new Error("No response."));
}
};
req.onerror = function (e) {
return callback(null, e);
};
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.send();
};
/** Load an `ArrayBuffer` taken as a PBM image to a PBM mask.
*
* N.B. do not use the newly-initialized `Mask` directly until
* the callback is called.
*
* Examples:
*
* new Mask.PBM.load(arrayBuffer, callback);
*
* @param {ArrayBuffer} array image data
* @param {MaskCallback} callback
* @api public
*/
Mask.PBM.prototype.load = function (array, callback) {
var bytes = new Uint8Array(array);
if (bytes.byteLength > 2) {
if (bytes[0] === 'P'.charCodeAt(0)) {
if (bytes[1] === '4'.charCodeAt(0)) {
// This is a PBM binary file...
return fromBinaryPBM(this, bytes, callback);
} else if (bytes[1] === "1".charCodeAt(0)) {
// This is a PBM ASCII file...
return fromASCIIPBM(this, bytes, callback);
} else {
// Unknown signature.
return callback(null, new Error("Unknown PBM signature."));
}
} else {
// Unknown signature.
return callback(null, new Error("Unknown PBM signature."));
}
} else {
// File too short.
return callback(null, Error("Invalid PBM image."));
}
};
/** Create a mask as an inversion of another.
*
* Examples:
*
* new Mask.Invert(other)
*
* @constructor
* @param {Mask} other the mask to invert.
* @api public
*/
Mask.Invert = function (other) {
this.x = other.x;
this.y = other.y;
this.w = other.w;
this.h = other.h;
this.inversion = other;
};
Mask.Invert.prototype = new Mask();
Mask.Invert.prototype.clone = function () {
var other = new Mask.Invert(this.inversion);
other.translate(this.x, this.y);
return other;
};
Mask.Invert.prototype.collidesAt = function (x, y) {
return !this.inversion.collidesAt(x, y);
};
/** Masks representing vector boxes.
*
* Examples:
*
* new Mask.Box(10, 10)
*
* @constructor
* @param {Number} w width
* @param {Number} h height
* @api public
*/
Mask.Box = function (w, h) {
this.x = 0;
this.y = 0;
this.w = w;
this.h = h;
};
Mask.Box.prototype = new Mask();
Mask.Box.prototype.clone = function () {
var other = new Mask.Box(this.w, this.h);
other.translate(this.x, this.y);
return other;
};
Mask.Box.prototype.collidesAt = function (x, y) {
return x >= this.x && y >= this.y &&
x < (this.x + this.w) && y < (this.y + this.h);
};
/* Get a mask representing a bounding box of some other mask.
*
* Examples:
*
* Mask.Box.bounding(someMask)
*
* @param {Mask} m
* @return {Mask.Box}
* @api public
*/
Mask.Box.bounding = function (m) {
return new Mask.Box(m.w, m.h).at(m.x, m.y);
};
/*!*/
if (typeof module !== "undefined") {
module.exports = Mask;
}
return Mask;
})();