language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class GuildPreview extends Base {
constructor(data, client) {
super(data.id);
this._client = client;
this.name = data.name;
this.icon = data.icon;
this.description = data.description;
this.splash = data.splash;
this.discoverySplash = data.discovery_splash;
this.features = data.features;
this.approximateMemberCount = data.approximate_member_count;
this.approximatePresenceCount = data.approximate_presence_count;
this.emojis = data.emojis;
}
get iconURL() {
return this.icon ? this._client._formatImage(Endpoints.GUILD_ICON(this.id, this.icon)) : null;
}
get splashURL() {
return this.splash ? this._client._formatImage(Endpoints.GUILD_SPLASH(this.id, this.splash)) : null;
}
get discoverySplashURL() {
return this.discoverySplash ? this._client._formatImage(Endpoints.GUILD_DISCOVERY_SPLASH(this.id, this.discoverySplash)) : null;
}
/**
* Get the guild's splash with the given format and size
* @arg {String} [format] The filetype of the icon ("jpg", "jpeg", "png", "gif", or "webp")
* @arg {Number} [size] The size of the icon (any power of two between 16 and 4096)
*/
dynamicDiscoverySplashURL(format, size) {
return this.discoverySplash ? this._client._formatImage(Endpoints.GUILD_DISCOVERY_SPLASH(this.id, this.discoverySplash), format, size) : null;
}
/**
* Get the guild's icon with the given format and size
* @arg {String} [format] The filetype of the icon ("jpg", "jpeg", "png", "gif", or "webp")
* @arg {Number} [size] The size of the icon (any power of two between 16 and 4096)
*/
dynamicIconURL(format, size) {
return this.icon ? this._client._formatImage(Endpoints.GUILD_ICON(this.id, this.icon), format, size) : null;
}
/**
* Get the guild's splash with the given format and size
* @arg {String} [format] The filetype of the icon ("jpg", "jpeg", "png", "gif", or "webp")
* @arg {Number} [size] The size of the icon (any power of two between 16 and 4096)
*/
dynamicSplashURL(format, size) {
return this.splash ? this._client._formatImage(Endpoints.GUILD_SPLASH(this.id, this.splash), format, size) : null;
}
toJSON(props = []) {
return super.toJSON([
"id",
"name",
"icon",
"description",
"splash",
"discoverySplash",
"features",
"approximateMemberCount",
"approximatePresenceCount",
"emojis",
...props
]);
}
} |
JavaScript | class WMSTerrainProvider extends AbstractTerrainProvider {
/**
* Constructor.
* @param {!osx.cesium.WMSTerrainProviderOptions} options
*/
constructor(options) {
super(options);
asserts.assert(options.layers != null && options.layers.length > 0, 'layers not defined');
/**
* Configured WMS layers to use for terrain.
* @type {!Array<!osx.cesium.WMSTerrainLayerOptions>}
* @private
*/
this.layers_ = options.layers;
this.layers_.sort(wmsTerrainLayerCompare);
// for now, name the provider based on the first layer name so it can be of use in the layers window
// we could change name based on zoom level but it's problematic because tiles are requested for multiple zoom levels
if (this.layers_.length > 0) {
this.setName(this.layers_[this.layers_.length - 1].layerName);
}
// set min/max level based on the configured layers
this.maxLevel = this.layers_[0].maxLevel;
this.minLevel = this.layers_[this.layers_.length - 1].minLevel;
// mark as ready so Cesium will start requesting terrain
this.ready = true;
}
/**
* @inheritDoc
*/
getTileDataAvailable(x, y, level) {
return super.getTileDataAvailable(x, y, level) && level < this.maxLevel;
}
/**
* @inheritDoc
*/
requestTileGeometry(x, y, level, opt_request) {
var layerName = this.getLayerForLevel_(level);
if (!layerName) {
// no terrain at this zoom level
var terrainData = new Cesium.HeightmapTerrainData({
buffer: new Uint8Array(this.tileSize * this.tileSize),
width: this.tileSize,
height: this.tileSize
});
return Cesium.when.resolve(terrainData);
}
var url = this.getRequestUrl_(x, y, level, layerName);
if (this.useProxy) {
url = ProxyHandler.getProxyUri(url);
}
var promise = Cesium.Resource.fetchArrayBuffer({
url: url,
request: opt_request
});
if (!promise) {
return undefined;
}
var childMask = this.getTerrainChildMask(x, y, level);
return Cesium.when(promise, this.arrayToHeightmap_.bind(this, childMask));
}
/**
* @param {number} level
* @return {string|undefined}
* @private
*/
getLayerForLevel_(level) {
var layerName = undefined;
if (level < this.maxLevel && level >= this.minLevel) {
for (var i = 0, n = this.layers_.length; i < n; i++) {
var layer = this.layers_[i];
if (level < layer.maxLevel && level >= layer.minLevel) {
layerName = layer.layerName;
break;
}
}
}
return layerName;
}
/**
* Get the URL for an elevation tile
*
* @param {number} x
* @param {number} y
* @param {number} level
* @param {string} layerName
* @return {string}
* @private
*/
getRequestUrl_(x, y, level, layerName) {
var url = this.url + '?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&CRS=EPSG%3A4326&STYLES=';
// add the elevation layer
url += '&LAYERS=' + layerName;
// add the format
url += '&FORMAT=image%2Fbil';
// add the tile size
url += '&WIDTH=' + this.tileSize + '&HEIGHT=' + this.tileSize;
// add the bounding box
var rect = this.tilingScheme.tileXYToNativeRectangle(x, y, level);
var xSpacing = (rect.east - rect.west) / this.tileSize;
var ySpacing = (rect.north - rect.south) / this.tileSize;
rect.west -= xSpacing * 0.5;
rect.east += xSpacing * 0.5;
rect.south -= ySpacing * 0.5;
rect.north += ySpacing * 0.5;
url += '&BBOX=' + rect.south + ',' + rect.west + ',' + rect.north + ',' + rect.east;
return url;
}
/**
* @param {number} childTileMask
* @param {ArrayBuffer} buffer
* @return {Cesium.HeightmapTerrainData}
* @private
*/
arrayToHeightmap_(childTileMask, buffer) {
var heightBuffer = this.postProcessArray_(buffer);
if (heightBuffer === undefined) {
throw new Cesium.DeveloperError('unexpected height buffer size');
}
var optionsHeightmapTerrainData = {
buffer: heightBuffer,
width: this.tileSize,
height: this.tileSize,
childTileMask: childTileMask,
structure: this.terrainDataStructure
};
return new Cesium.HeightmapTerrainData(optionsHeightmapTerrainData);
}
/**
* @param {ArrayBuffer} buffer
* @return {Int16Array|undefined}
* @private
*/
postProcessArray_(buffer) {
var result;
var viewerIn = new DataView(buffer);
var littleEndianBuffer = new ArrayBuffer(this.tileSize * this.tileSize * 2);
var littleEndianView = new DataView(littleEndianBuffer);
if (littleEndianBuffer.byteLength === buffer.byteLength) {
// switch from big to little endian
var current = 0;
var goodCell = 0;
var sum = 0;
for (var i = 0; i < littleEndianBuffer.byteLength; i += 2) {
current = viewerIn.getInt16(i, false);
// don't allow values outside acceptable ranges (in meters) for the Earth.
if (current > -500 && current < 9000) {
littleEndianView.setInt16(i, current, true);
sum += current;
goodCell++;
} else {
// elevation is outside the acceptable range, so use an average
var average = goodCell > 0 ? (sum / goodCell) : 0;
littleEndianView.setInt16(i, average, true);
}
}
result = new Int16Array(littleEndianBuffer);
}
return result;
}
/**
* Create a Cesium WMS terrain provider instance.
* @param {!osx.cesium.WMSTerrainProviderOptions} options The WMS terrain options.
* @return {!Promise<!WMSTerrainProvider>}
*/
static create(options) {
return Promise.resolve(new WMSTerrainProvider(options));
}
} |
JavaScript | class Prompt extends events {
constructor(opts = {}) {
super();
this.firstRender = true;
this.in = opts.in || process.stdin;
this.out = opts.out || process.stdout;
this.onRender = (opts.onRender || (() => void 0)).bind(this);
const rl = readline.createInterface(this.in);
readline.emitKeypressEvents(this.in, rl);
if (this.in.isTTY) this.in.setRawMode(true);
const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1;
const keypress = (str, key) => {
let a = action$1(key, isSelect);
if (a === false) {
this._ && this._(str, key);
} else if (typeof this[a] === 'function') {
this[a](key);
} else {
this.bell();
}
};
this.close = () => {
this.out.write(cursor$2.show);
this.in.removeListener('keypress', keypress);
if (this.in.isTTY) this.in.setRawMode(false);
rl.close();
this.emit(this.aborted ? 'abort' : 'submit', this.value);
this.closed = true;
};
this.in.on('keypress', keypress);
}
fire() {
this.emit('state', {
value: this.value,
aborted: !!this.aborted
});
}
bell() {
this.out.write(beep$1);
}
render() {
this.onRender(kleur);
if (this.firstRender) this.firstRender = false;
}
} |
JavaScript | class AutocompletePrompt extends prompt {
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.suggest = opts.suggest;
this.choices = opts.choices;
this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial);
this.select = this.initial || opts.cursor || 0;
this.i18n = {
noMatches: opts.noMatches || 'no matches found'
};
this.fallback = opts.fallback || this.initial;
this.suggestions = [[]];
this.page = 0;
this.input = '';
this.limit = opts.limit || 10;
this.cursor = 0;
this.transform = style$7.render(opts.style);
this.scale = this.transform.scale;
this.render = this.render.bind(this);
this.complete = this.complete.bind(this);
this.clear = clear$7('');
this.complete(this.render);
this.render();
}
set fallback(fb) {
this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
}
get fallback() {
let choice;
if (typeof this._fb === 'number') choice = this.choices[this._fb];else if (typeof this._fb === 'string') choice = {
title: this._fb
};
return choice || this._fb || {
title: this.i18n.noMatches
};
}
moveSelect(i) {
this.select = i;
if (this.suggestions[this.page].length > 0) this.value = getVal(this.suggestions[this.page], i);else this.value = this.fallback.value;
this.fire();
}
complete(cb) {
var _this = this;
return _asyncToGenerator$3(function* () {
const p = _this.completing = _this.suggest(_this.input, _this.choices);
const suggestions = yield p;
if (_this.completing !== p) return;
_this.suggestions = suggestions.map((s, i, arr) => ({
title: getTitle(arr, i),
value: getVal(arr, i),
description: s.description
})).reduce((arr, sug) => {
if (arr[arr.length - 1].length < _this.limit) arr[arr.length - 1].push(sug);else arr.push([sug]);
return arr;
}, [[]]);
_this.completing = false;
if (!_this.suggestions[_this.page]) _this.page = 0; // if (!this.suggestions.length && this.fallback) {
// const index = getIndex(this.choices, this.fallback);
// this.suggestions = [[]];
// if (index !== undefined)
// this.suggestions[0].push({ title: getTitle(this.choices, index), value: getVal(this.choices, index) });
// this.isFallback = true;
// }
const l = Math.max(suggestions.length - 1, 0);
_this.moveSelect(Math.min(l, _this.select));
cb && cb();
})();
}
reset() {
this.input = '';
this.complete(() => {
this.moveSelect(this.initial !== void 0 ? this.initial : 0);
this.render();
});
this.render();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
_(c, key) {
// TODO on ctrl+# go to page #
let s1 = this.input.slice(0, this.cursor);
let s2 = this.input.slice(this.cursor);
this.input = `${s1}${c}${s2}`;
this.cursor = s1.length + 1;
this.complete(this.render);
this.render();
}
delete() {
if (this.cursor === 0) return this.bell();
let s1 = this.input.slice(0, this.cursor - 1);
let s2 = this.input.slice(this.cursor);
this.input = `${s1}${s2}`;
this.complete(this.render);
this.cursor = this.cursor - 1;
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
let s1 = this.input.slice(0, this.cursor);
let s2 = this.input.slice(this.cursor + 1);
this.input = `${s1}${s2}`;
this.complete(this.render);
this.render();
}
first() {
this.moveSelect(0);
this.render();
}
last() {
this.moveSelect(this.suggestions[this.page].length - 1);
this.render();
}
up() {
if (this.select <= 0) return this.bell();
this.moveSelect(this.select - 1);
this.render();
}
down() {
if (this.select >= this.suggestions[this.page].length - 1) return this.bell();
this.moveSelect(this.select + 1);
this.render();
}
next() {
if (this.select === this.suggestions[this.page].length - 1) {
this.page = (this.page + 1) % this.suggestions.length;
this.moveSelect(0);
} else this.moveSelect(this.select + 1);
this.render();
}
nextPage() {
if (this.page >= this.suggestions.length - 1) return this.bell();
this.page++;
this.moveSelect(0);
this.render();
}
prevPage() {
if (this.page <= 0) return this.bell();
this.page--;
this.moveSelect(0);
this.render();
}
left() {
if (this.cursor <= 0) return this.bell();
this.cursor = this.cursor - 1;
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length) return this.bell();
this.cursor = this.cursor + 1;
this.render();
}
renderOption(v, hovered) {
let desc,
title = v.title;
if (hovered) {
title = kleur.cyan(v.title);
if (v.description) {
desc = ` - ${v.description}`;
if (title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) {
desc = '\n' + wrap$3(v.description, {
width: this.out.columns
});
}
}
}
return title + kleur.gray(desc || '');
}
render() {
if (this.closed) return;
if (!this.firstRender) this.out.write(clear$7(this.outputText));
super.render();
this.outputText = [kleur.bold(style$7.symbol(this.done, this.aborted)), kleur.bold(this.msg), style$7.delimiter(this.completing), this.done && this.suggestions[this.page][this.select] ? this.suggestions[this.page][this.select].title : this.rendered = this.transform.render(this.input)].join(' ');
if (!this.done) {
const suggestions = this.suggestions[this.page].map((item, i) => this.renderOption(item, this.select === i)).join('\n');
this.outputText += `\n` + (suggestions || kleur.gray(this.fallback.title));
if (this.suggestions[this.page].length > 1) {
this.outputText += kleur.blue(`\nPage ${this.page + 1}/${this.suggestions.length}`);
}
}
this.out.write(erase$6.line + cursor$9.to(0) + this.outputText);
}
} |
JavaScript | class Prompt$1 extends events {
constructor(opts={}) {
super();
this.firstRender = true;
this.in = opts.in || process.stdin;
this.out = opts.out || process.stdout;
this.onRender = (opts.onRender || (() => void 0)).bind(this);
const rl = readline.createInterface(this.in);
readline.emitKeypressEvents(this.in, rl);
if (this.in.isTTY) this.in.setRawMode(true);
const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1;
const keypress = (str, key) => {
let a = action$3(key, isSelect);
if (a === false) {
this._ && this._(str, key);
} else if (typeof this[a] === 'function') {
this[a](key);
} else {
this.bell();
}
};
this.close = () => {
this.out.write(cursor$d.show);
this.in.removeListener('keypress', keypress);
if (this.in.isTTY) this.in.setRawMode(false);
rl.close();
this.emit(this.aborted ? 'abort' : 'submit', this.value);
this.closed = true;
};
this.in.on('keypress', keypress);
}
fire() {
this.emit('state', {
value: this.value,
aborted: !!this.aborted
});
}
bell() {
this.out.write(beep$2);
}
render() {
this.onRender(kleur);
if (this.firstRender) this.firstRender = false;
}
} |
JavaScript | class AutocompletePrompt$1 extends prompt$2 {
constructor(opts={}) {
super(opts);
this.msg = opts.message;
this.suggest = opts.suggest;
this.choices = opts.choices;
this.initial = typeof opts.initial === 'number'
? opts.initial
: getIndex$1(opts.choices, opts.initial);
this.select = this.initial || opts.cursor || 0;
this.i18n = { noMatches: opts.noMatches || 'no matches found' };
this.fallback = opts.fallback || this.initial;
this.suggestions = [[]];
this.page = 0;
this.input = '';
this.limit = opts.limit || 10;
this.cursor = 0;
this.transform = style$h.render(opts.style);
this.scale = this.transform.scale;
this.render = this.render.bind(this);
this.complete = this.complete.bind(this);
this.clear = clear$h('');
this.complete(this.render);
this.render();
}
set fallback(fb) {
this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
}
get fallback() {
let choice;
if (typeof this._fb === 'number')
choice = this.choices[this._fb];
else if (typeof this._fb === 'string')
choice = { title: this._fb };
return choice || this._fb || { title: this.i18n.noMatches };
}
moveSelect(i) {
this.select = i;
if (this.suggestions[this.page].length > 0)
this.value = getVal$1(this.suggestions[this.page], i);
else this.value = this.fallback.value;
this.fire();
}
async complete(cb) {
const p = (this.completing = this.suggest(this.input, this.choices));
const suggestions = await p;
if (this.completing !== p) return;
this.suggestions = suggestions
.map((s, i, arr) => ({ title: getTitle$1(arr, i), value: getVal$1(arr, i), description: s.description }))
.reduce((arr, sug) => {
if (arr[arr.length - 1].length < this.limit)
arr[arr.length - 1].push(sug);
else arr.push([sug]);
return arr;
}, [[]]);
this.completing = false;
if (!this.suggestions[this.page])
this.page = 0;
// if (!this.suggestions.length && this.fallback) {
// const index = getIndex(this.choices, this.fallback);
// this.suggestions = [[]];
// if (index !== undefined)
// this.suggestions[0].push({ title: getTitle(this.choices, index), value: getVal(this.choices, index) });
// this.isFallback = true;
// }
const l = Math.max(suggestions.length - 1, 0);
this.moveSelect(Math.min(l, this.select));
cb && cb();
}
reset() {
this.input = '';
this.complete(() => {
this.moveSelect(this.initial !== void 0 ? this.initial : 0);
this.render();
});
this.render();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
_(c, key) { // TODO on ctrl+# go to page #
let s1 = this.input.slice(0, this.cursor);
let s2 = this.input.slice(this.cursor);
this.input = `${s1}${c}${s2}`;
this.cursor = s1.length+1;
this.complete(this.render);
this.render();
}
delete() {
if (this.cursor === 0) return this.bell();
let s1 = this.input.slice(0, this.cursor-1);
let s2 = this.input.slice(this.cursor);
this.input = `${s1}${s2}`;
this.complete(this.render);
this.cursor = this.cursor-1;
this.render();
}
deleteForward() {
if(this.cursor*this.scale >= this.rendered.length) return this.bell();
let s1 = this.input.slice(0, this.cursor);
let s2 = this.input.slice(this.cursor+1);
this.input = `${s1}${s2}`;
this.complete(this.render);
this.render();
}
first() {
this.moveSelect(0);
this.render();
}
last() {
this.moveSelect(this.suggestions[this.page].length - 1);
this.render();
}
up() {
if (this.select <= 0) return this.bell();
this.moveSelect(this.select - 1);
this.render();
}
down() {
if (this.select >= this.suggestions[this.page].length - 1) return this.bell();
this.moveSelect(this.select + 1);
this.render();
}
next() {
if (this.select === this.suggestions[this.page].length - 1) {
this.page = (this.page + 1) % this.suggestions.length;
this.moveSelect(0);
} else this.moveSelect(this.select + 1);
this.render();
}
nextPage() {
if (this.page >= this.suggestions.length - 1)
return this.bell();
this.page++;
this.moveSelect(0);
this.render();
}
prevPage() {
if (this.page <= 0)
return this.bell();
this.page--;
this.moveSelect(0);
this.render();
}
left() {
if (this.cursor <= 0) return this.bell();
this.cursor = this.cursor-1;
this.render();
}
right() {
if (this.cursor*this.scale >= this.rendered.length) return this.bell();
this.cursor = this.cursor+1;
this.render();
}
renderOption(v, hovered) {
let desc, title = v.title;
if (hovered) {
title = kleur.cyan(v.title);
if (v.description) {
desc = ` - ${v.description}`;
if (title.length + desc.length >= this.out.columns
|| v.description.split(/\r?\n/).length > 1) {
desc = '\n' + wrap$7(v.description, { width: this.out.columns });
}
}
}
return title + kleur.gray(desc || '');
}
render() {
if (this.closed) return;
if (!this.firstRender) this.out.write(clear$h(this.outputText));
super.render();
this.outputText = [
kleur.bold(style$h.symbol(this.done, this.aborted)),
kleur.bold(this.msg),
style$h.delimiter(this.completing),
this.done && this.suggestions[this.page][this.select]
? this.suggestions[this.page][this.select].title
: this.rendered = this.transform.render(this.input)
].join(' ');
if (!this.done) {
const suggestions = this.suggestions[this.page]
.map((item, i) => this.renderOption(item, this.select === i))
.join('\n');
this.outputText += `\n` + (suggestions || kleur.gray(this.fallback.title));
if (this.suggestions[this.page].length > 1) {
this.outputText += kleur.blue(`\nPage ${this.page+1}/${this.suggestions.length}`);
}
}
this.out.write(erase$d.line + cursor$k.to(0) + this.outputText);
}
} |
JavaScript | class MathField {
/**
* To create a mathfield, you would typically use {@linkcode module:MathLive#makeMathField MathLive.makeMathField()}
* instead of invoking directly this constructor.
*
*
* @param {HTMLElement} element - The DOM element that this mathfield is attached to.
* Note that `element.mathfield` is this object.
* @param {MathFieldConfig} config - See {@tutorial CONFIG} for details
* @method MathField#constructor
* @private
*/
constructor(element, config) {
// Setup default config options
this.$setConfig(config || {});
this.element = element;
element.mathfield = this;
// Save existing content
this.originalContent = element.innerHTML;
let elementText = this.element.textContent;
if (elementText) {
elementText = elementText.trim();
}
// Additional elements used for UI.
// They are retrieved in order a bit later, so they need to be kept in sync
// 1.0/ The field, where the math equation will be displayed
// 1.1/ The virtual keyboard toggle
// 2/ The popover panel which displays info in command mode
// 3/ The keystroke caption panel (option+shift+K)
// 4/ The virtual keyboard
// 5.0/ The area to stick MathML for screen reading larger exprs (not used right now)
// The for the area is that focus would bounce their and then back triggering the
// screen reader to read it
// 5.1/ The aria-live region for announcements
let markup = '';
if (!this.config.substituteTextArea) {
if (/android|ipad|ipod|iphone/i.test(navigator.userAgent)) {
// On Android or iOS, don't use a textarea, which has the side effect of
// bringing up the OS virtual keyboard
markup += `<span class='ML__textarea'>
<span class='ML__textarea__textarea'
tabindex="0" role="textbox"
style='display:inline-block;height:1px;width:1px' >
</span>
</span>`;
} else {
markup += '<span class="ML__textarea">' +
'<textarea class="ML__textarea__textarea" autocapitalize="off" autocomplete="off" ' +
'autocorrect="off" spellcheck="false" aria-hidden="true" tabindex="0">' +
'</textarea>' +
'</span>';
}
} else {
if (typeof this.config.substituteTextArea === 'string') {
markup += this.config.substituteTextArea;
} else {
// We don't really need this one, but we keep it here so that the
// indexes below remain the same whether a substituteTextArea is
// provided or not.
markup += '<span></span>';
}
}
markup += '<span class="ML__fieldcontainer">' +
'<span class="ML__fieldcontainer__field"></span>';
// If no value is specified for the virtualKeyboardMode, use
// `onfocus` on touch-capable devices and `off` otherwise.
if (!this.config.virtualKeyboardMode) {
this.config.virtualKeyboardMode =
(window.matchMedia && window.matchMedia("(any-pointer: coarse)").matches) ? 'onfocus' : 'off';
}
// Only display the virtual keyboard toggle if the virtual keyboard mode is
// 'manual'
if (this.config.virtualKeyboardMode === 'manual') {
markup += `<button class="ML__virtual-keyboard-toggle" data-tooltip="${l10n('tooltip.toggle virtual keyboard')}">`;
// data-tooltip='Toggle Virtual Keyboard'
if (this.config.virtualKeyboardToggleGlyph) {
markup += this.config.virtualKeyboardToggleGlyph;
} else {
markup += `<span style="width: 21px; margin-top: 4px;"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M528 64H48C21.49 64 0 85.49 0 112v288c0 26.51 21.49 48 48 48h480c26.51 0 48-21.49 48-48V112c0-26.51-21.49-48-48-48zm16 336c0 8.823-7.177 16-16 16H48c-8.823 0-16-7.177-16-16V112c0-8.823 7.177-16 16-16h480c8.823 0 16 7.177 16 16v288zM168 268v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm-336 80v-24c0-6.627-5.373-12-12-12H84c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm384 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zM120 188v-24c0-6.627-5.373-12-12-12H84c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm96 0v-24c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v24c0 6.627 5.373 12 12 12h24c6.627 0 12-5.373 12-12zm-96 152v-8c0-6.627-5.373-12-12-12H180c-6.627 0-12 5.373-12 12v8c0 6.627 5.373 12 12 12h216c6.627 0 12-5.373 12-12z"/></svg></span>`;
}
markup += '</button>';
} else {
markup += '<span ></span>';
}
markup += '</span>';
markup += `
<div class="sr-only">
<span aria-live="assertive" aria-atomic="true"></span>
<span></span>
</div>
`;
this.element.innerHTML = markup;
let iChild = 0; // index of child -- used to make changes below easier
if (typeof this.config.substituteTextArea === 'function') {
this.textarea = this.config.substituteTextArea();
} else {
this.textarea = this.element.children[iChild++].firstElementChild;
}
this.field = this.element.children[iChild].children[0];
// Listen to 'wheel' events to scroll (horizontally) the field when it overflows
this.field.addEventListener('wheel', ev => {
ev.preventDefault();
ev.stopPropagation();
let wheelDelta = typeof ev.deltaX === 'undefined' ? ev.detail : -ev.deltaX;
if (!isFinite(wheelDelta)) { wheelDelta = ev.wheelDelta / 10; }
this.field.scroll({
top: 0,
left: this.field.scrollLeft - wheelDelta * 5
});
}, { passive: false });
this.virtualKeyboardToggleDOMNode = this.element.children[iChild++].children[1];
this._attachButtonHandlers(this.virtualKeyboardToggleDOMNode, {
default: 'toggleVirtualKeyboard',
alt: 'toggleVirtualKeyboardAlt',
shift: 'toggleVirtualKeyboardShift'
});
this.ariaLiveText = this.element.children[iChild].children[0];
this.accessibleNode = this.element.children[iChild++].children[1];
// Some panels are shared amongst instances of mathfield
// (there's a single instance in the document)
this.popover = getSharedElement('mathlive-popover-panel', 'ML__popover');
this.keystrokeCaption = getSharedElement('mathlive-keystroke-caption-panel', 'ML__keystroke-caption');
// The keystroke caption panel and the command bar are
// initially hidden
this.keystrokeCaptionVisible = false;
this.virtualKeyboardVisible = false;
this.keystrokeBuffer = '';
this.keystrokeBufferStates = [];
this.keystrokeBufferResetTimer = null;
// This index indicates which of the suggestions available to
// display in the popover panel
this.suggestionIndex = 0;
// The input mode (text, math, command)
// While mathlist.anchorMode() represent the mode of the current selection,
// this.mode is the mode chosen by the user. It indicates the mode the
// next character typed will be interpreted in.
// It is often identical to mathlist.anchorMode() since changing the selection
// changes the mode, but sometimes it is not, for example when a user
// enters a mode changing command.
this.mode = config.defaultMode || 'math';
this.smartModeSuppressed = false;
// Current style (color, weight, italic, etc...)
// Reflects the style to be applied on next insertion, if any
this.style = {};
// Focus/blur state
this.blurred = true;
on(this.element, 'focus', this);
on(this.element, 'blur', this);
// Capture clipboard events
on(this.textarea, 'cut', this);
on(this.textarea, 'copy', this);
on(this.textarea, 'paste', this);
// Delegate keyboard events
Keyboard.delegateKeyboardEvents(this.textarea, {
container: this.element,
allowDeadKey: () => this.mode === 'text',
typedText: this._onTypedText.bind(this),
paste: this._onPaste.bind(this),
keystroke: this._onKeystroke.bind(this),
focus: this._onFocus.bind(this),
blur: this._onBlur.bind(this),
});
// Delegate mouse and touch events
if (window.PointerEvent) {
// Use modern pointer events if available
on(this.field, 'pointerdown', this);
} else {
on(this.field, 'touchstart:active mousedown', this);
}
// Request notification for when the window is resized (
// or the device switched from portrait to landscape) to adjust
// the UI (popover, etc...)
on(window, 'resize', this);
// Override some handlers in the config
const localConfig = { ...config };
localConfig.onSelectionDidChange =
MathField.prototype._onSelectionDidChange.bind(this);
localConfig.onContentDidChange =
MathField.prototype._onContentDidChange.bind(this);
localConfig.onAnnounce = this.config.onAnnounce;
localConfig.macros = this.config.macros;
localConfig.removeExtraneousParentheses = this.config.removeExtraneousParentheses;
this.mathlist = new EditableMathlist.EditableMathlist(localConfig, this);
// Prepare to manage undo/redo
this.undoManager = new Undo.UndoManager(this.mathlist);
// If there was some content in the element, use it for the initial
// value of the mathfield
if (elementText.length > 0) {
this.$latex(elementText);
}
// Now start recording potentially undoable actions
this.undoManager.startRecording();
this.undoManager.snapshot(this.config);
}
/*
* handleEvent is a function invoked when an event is registered with an
* object instead ( see `addEventListener()` in `on()`)
* The name is defined by addEventListener() and cannot be changed.
* This pattern is used to be able to release bound event handlers,
* (event handlers that need access to `this`) as the bind() function
* would create a new function that would have to be kept track off
* to be able to properly remove the event handler later.
*/
handleEvent(evt) {
switch (evt.type) {
case 'focus':
this._onFocus(evt);
break;
case 'blur':
this._onBlur(evt);
break;
case 'touchstart':
this._onPointerDown(evt);
break;
case 'mousedown':
this._onPointerDown(evt);
break;
case 'pointerdown':
this._onPointerDown(evt);
break;
case 'resize': {
if (this._resizeTimer) { window.cancelAnimationFrame(this._resizeTimer); }
this._resizeTimer = window.requestAnimationFrame(() => this._onResize());
break;
}
case 'cut':
this._onCut(evt);
break;
case 'copy':
this._onCopy(evt);
break;
case 'paste':
this._onPaste(evt);
break;
default: console.warn('Unexpected event type', evt.type);
}
}
/**
* Revert this math field to its original content. After this method has been
* called, no other methods can be called on the MathField object. To turn the
* element back into a MathField, call `MathLive.makeMathField()` on the
* element again to get a new math field object.
*
* @method MathField#$revertToOriginalContent
*/
$revertToOriginalContent() {
this.element.innerHTML = this.originalContent;
this.element.mathfield = null;
delete this.accessibleNode;
delete this.ariaLiveText;
delete this.field;
off(this.textarea, 'cut', this);
off(this.textarea, 'copy', this);
off(this.textarea, 'paste', this);
this.textarea.remove();
delete this.textarea;
this.virtualKeyboardToggleDOMNode.remove();
delete this.virtualKeyboardToggleDOMNode;
delete releaseSharedElement(this.popover);
delete releaseSharedElement(this.keystrokeCaption);
delete releaseSharedElement(this.virtualKeyboard);
delete releaseSharedElement(document.getElementById('mathlive-alternate-keys-panel'));
off(this.element, 'pointerdown', this);
off(this.element, 'touchstart:active mousedown', this);
off(this.element, 'focus', this);
off(this.element, 'blur', this);
off(window, 'resize', this);
}
_resetKeystrokeBuffer() {
this.keystrokeBuffer = '';
this.keystrokeBufferStates = [];
clearTimeout(this.keystrokeBufferResetTimer);
}
/**
* Return the (x,y) client coordinates of the caret
*
* @method MathField#_getCaretPosition
* @private
*/
_getCaretPosition() {
const caret = _findElementWithCaret(this.field);
if (caret) {
const bounds = caret.getBoundingClientRect();
return {
x: bounds.right + window.scrollX,
y: bounds.bottom + window.scrollY
};
}
return null;
}
_getSelectionBounds() {
const selectedNodes = this.field.querySelectorAll('.ML__selected');
if (selectedNodes && selectedNodes.length > 0) {
const selectionRect = { top: Infinity, bottom: -Infinity, left: Infinity, right: -Infinity };
// Calculate the union of the bounds of all the selected spans
selectedNodes.forEach(node => {
const bounds = node.getBoundingClientRect();
if (bounds.left < selectionRect.left) { selectionRect.left = bounds.left; }
if (bounds.right > selectionRect.right) { selectionRect.right = bounds.right; }
if (bounds.bottom > selectionRect.bottom) { selectionRect.bottom = bounds.bottom; }
if (bounds.top < selectionRect.top) { selectionRect.top = bounds.top; }
});
const fieldRect = this.field.getBoundingClientRect();
const w = selectionRect.right - selectionRect.left;
const h = selectionRect.bottom - selectionRect.top;
selectionRect.left = Math.ceil(selectionRect.left - fieldRect.left + this.field.scrollLeft);
selectionRect.right = selectionRect.left + w;
selectionRect.top = Math.ceil(selectionRect.top - fieldRect.top);
selectionRect.bottom = selectionRect.top + h;
return selectionRect;
}
return null;
}
/**
* @param {number} x
* @param {number} y
* @param {object} options
* @param {boolean} options.bias if 0, the midpoint of the bounding box
* is considered to return the sibling. If <0, the left sibling is
* favored, if >0, the right sibling
* @private
*/
_pathFromPoint(x, y, options) {
options = options || {};
options.bias = options.bias || 0;
let result;
// Try to find the deepest element that is near the point that was
// clicked on (the point could be outside of the element)
const nearest = nearestElementFromPoint(this.field, x, y);
const el = nearest.element;
const id = el ? el.getAttribute('data-atom-id') : null;
if (id) {
// Let's find the atom that has a matching ID with the element that
// was clicked on (or near)
const paths = this.mathlist.filter(function (_path, atom) {
// If the atom allows children to be selected, match only if
// the ID of the atom matches the one we're looking for.
if (!atom.captureSelection) {
return atom.id === id;
}
// If the atom does not allow children to be selected
// (captureSelection === true), the element matches if any of
// its children has an ID that matches.
return atom.filter(childAtom => childAtom.id === id).length > 0;
});
if (paths && paths.length > 0) {
// (There should be exactly one atom that matches this ID...)
// Set the result to the path to this atom
result = MathPath.pathFromString(paths[0]).path;
if (options.bias === 0) {
// If the point clicked is to the left of the vertical midline,
// adjust the path to *before* the atom (i.e. after the
// preceding atom)
const bounds = el.getBoundingClientRect();
if (x < bounds.left + bounds.width / 2 && !el.classList.contains('ML__placeholder')) {
result[result.length - 1].offset =
Math.max(0, result[result.length - 1].offset - 1);
}
} else if (options.bias < 0) {
result[result.length - 1].offset =
Math.min(this.mathlist.siblings().length - 1, Math.max(0, result[result.length - 1].offset + options.bias));
}
}
}
return result;
}
_onPointerDown(evt) {
const that = this;
let anchor;
let trackingPointer = false;
let trackingWords = false;
let dirty = false;
// If a mouse button other than the main one was pressed, return
if (evt.buttons !== 1) { return; }
function endPointerTracking(evt) {
if (window.PointerEvent) {
off(that.field, 'pointermove', onPointerMove);
off(that.field, 'pointerend pointerleave pointercancel', endPointerTracking);
// off(window, 'pointermove', onPointerMove);
// off(window, 'pointerup blur', endPointerTracking);
that.field.releasePointerCapture(evt.pointerId);
} else {
off(that.field, 'touchmove', onPointerMove);
off(that.field, 'touchend touchleave', endPointerTracking);
off(window, 'mousemove', onPointerMove);
off(window, 'mouseup blur', endPointerTracking);
}
trackingPointer = false;
clearInterval(scrollInterval);
that.element.querySelectorAll('.ML__scroller').forEach(x => x.parentNode.removeChild(x));
evt.preventDefault();
evt.stopPropagation();
}
let scrollLeft = false;
let scrollRight = false;
const scrollInterval = setInterval(() => {
if (scrollLeft) {
that.field.scroll({ top: 0, left: that.field.scrollLeft - 16 });
} else if (scrollRight) {
that.field.scroll({ top: 0, left: that.field.scrollLeft + 16 });
}
}, 32);
function onPointerMove(evt) {
const x = evt.touches ? evt.touches[0].clientX : evt.clientX;
const y = evt.touches ? evt.touches[0].clientY : evt.clientY;
// Ignore events that are within small spatial and temporal bounds
// of the pointer down
const hysteresis = evt.pointerType === 'touch' ? 20 : 5;
if (Date.now() < anchorTime + 500 &&
Math.abs(anchorX - x) < hysteresis && Math.abs(anchorY - y) < hysteresis) {
evt.preventDefault();
evt.stopPropagation();
return;
}
const fieldBounds = that.field.getBoundingClientRect();
scrollRight = x > fieldBounds.right;
scrollLeft = x < fieldBounds.left;
let actualAnchor = anchor;
if (window.PointerEvent) {
if (!evt.isPrimary) {
actualAnchor = that._pathFromPoint(evt.clientX, evt.clientY, { bias: 0 });
}
} else {
if (evt.touches && evt.touches.length === 2) {
actualAnchor = that._pathFromPoint(evt.touches[1].clientX, evt.touches[1].clientY, { bias: 0 });
}
}
const focus = that._pathFromPoint(x, y, { bias: x <= anchorX ? (x === anchorX ? 0 : -1) : +1 });
if (focus && that.mathlist.setRange(actualAnchor, focus, { extendToWordBoundary: trackingWords })) {
// Re-render if the range has actually changed
that._requestUpdate();
}
// Prevent synthetic mouseMove event when this is a touch event
evt.preventDefault();
evt.stopPropagation();
}
const anchorX = evt.touches ? evt.touches[0].clientX : evt.clientX;
const anchorY = evt.touches ? evt.touches[0].clientY : evt.clientY;
const anchorTime = Date.now();
// Calculate the tap count
if (lastTap && Math.abs(lastTap.x - anchorX) < 5 &&
Math.abs(lastTap.y - anchorY) < 5 &&
Date.now() < lastTap.time + 500) {
tapCount += 1;
lastTap.time = anchorTime;
} else {
lastTap = {
x: anchorX,
y: anchorY,
time: anchorTime
};
tapCount = 1;
}
const bounds = this.field.getBoundingClientRect();
if (anchorX >= bounds.left && anchorX <= bounds.right &&
anchorY >= bounds.top && anchorY <= bounds.bottom) {
// Create divs to block out pointer tracking to the left and right of
// the math field (to avoid triggering the hover of the virtual
// keyboard toggle, for example)
let div = document.createElement('div');
div.className = 'ML__scroller';
this.element.appendChild(div);
div.style.left = (bounds.left - 200) + 'px';
div = document.createElement('div');
div.className = 'ML__scroller';
this.element.appendChild(div);
div.style.left = (bounds.right) + 'px';
// Focus the math field
if (!this.$hasFocus()) {
dirty = true;
if (this.textarea.focus) { this.textarea.focus(); }
}
// Clicking or tapping the field resets the keystroke buffer and
// smart mode
this._resetKeystrokeBuffer();
this.smartModeSuppressed = false;
anchor = this._pathFromPoint(anchorX, anchorY, { bias: 0 });
if (anchor) {
if (evt.shiftKey) {
// Extend the selection if the shift-key is down
this.mathlist.setRange(this.mathlist.path, anchor);
anchor = MathPath.clone(this.mathlist.path);
anchor[anchor.length - 1].offset -= 1;
} else {
this.mathlist.setPath(anchor, 0);
}
// The selection has changed, so we'll need to re-render
dirty = true;
// Reset any user-specified style
this.style = {};
// evt.detail contains the number of consecutive clicks
// for double-click, triple-click, etc...
// (note that evt.detail is not set when using pointerEvent)
if (evt.detail === 3 || tapCount > 2) {
endPointerTracking(evt);
if (evt.detail === 3 || tapCount === 3) {
// This is a triple-click
this.mathlist.selectAll_();
}
} else if (!trackingPointer) {
trackingPointer = true;
if (window.PointerEvent) {
on(that.field, 'pointermove', onPointerMove);
on(that.field, 'pointerend pointercancel pointerup', endPointerTracking);
that.field.setPointerCapture(evt.pointerId);
} else {
on(window, 'blur', endPointerTracking);
if (evt.touches) {
// To receive the subsequent touchmove/touch, need to
// listen to this evt.target.
// This was a touch event
on(evt.target, 'touchmove', onPointerMove);
on(evt.target, 'touchend', endPointerTracking);
} else {
on(window, 'mousemove', onPointerMove);
on(window, 'mouseup', endPointerTracking);
}
}
if (evt.detail === 2 || tapCount === 2) {
// This is a double-click
trackingWords = true;
this.mathlist.selectGroup_();
}
}
}
} else {
lastTap = null;
}
if (dirty) { this._requestUpdate(); }
// Prevent the browser from handling, in particular when this is a
// touch event prevent the synthetic mouseDown event from being generated
evt.preventDefault();
}
_onSelectionDidChange() {
// Every atom before the new caret position is now committed
this.mathlist.commitCommandStringBeforeInsertionPoint();
// If the selection is not collapsed, put it in the textarea
// This will allow cut/copy to work.
let result = '';
this.mathlist.forEachSelected(atom => { result += atom.toLatex(); });
if (result) {
this.textarea.value = result;
// The textarea may be a span (on mobile, for example), so check that
// it has a select() before calling it.
if (this.$hasFocus() && this.textarea.select) {
this.textarea.select();
}
} else {
this.textarea.value = '';
this.textarea.setAttribute('aria-label', '');
}
// Update the mode
{
const previousMode = this.mode;
this.mode = this.mathlist.anchorMode() || this.config.defaultMode;
if (this.mode !== previousMode && typeof this.config.onModeChange === 'function') {
this.config.onModeChange(this, this.mode);
}
if (previousMode === 'command' && this.mode !== 'command') {
Popover.hidePopover(this);
this.mathlist.removeCommandString();
}
}
// Defer the updating of the popover position: we'll need the tree to be
// re-rendered first to get an updated caret position
Popover.updatePopoverPosition(this, { deferred: true });
// Invoke client handlers, if provided.
if (typeof this.config.onSelectionDidChange === 'function') {
this.config.onSelectionDidChange(this);
}
}
_onContentDidChange() {
if (this.undoManager.canRedo()) {
this.element.classList.add('can-redo');
} else {
this.element.classList.remove('can-redo');
}
if (this.undoManager.canUndo()) {
this.element.classList.add('can-undo');
} else {
this.element.classList.remove('can-undo');
}
if (typeof this.config.onContentDidChange === 'function') {
this.config.onContentDidChange(this);
}
}
/* Returns the speech text of the next atom after the selection or
* an 'end of' phrasing based on what structure we are at the end of
*/
_nextAtomSpeechText(oldMathlist) {
function relation(parent, leaf) {
const EXPR_NAME = {
// 'array': 'should not happen',
'numer': 'numerator',
'denom': 'denominator',
'index': 'index',
'body': 'parent',
'subscript': 'subscript',
'superscript': 'superscript'
};
const PARENT_NAME = {
'enclose': 'cross out',
'leftright': 'fence',
'surd': 'square root',
'root': 'math field'
};
return (leaf.relation === 'body' ? PARENT_NAME[parent.type] : EXPR_NAME[leaf.relation]);
}
const oldPath = oldMathlist ? oldMathlist.path : [];
const path = this.mathlist.path;
const leaf = path[path.length - 1];
let result = '';
while (oldPath.length > path.length) {
result += 'out of ' + relation(oldMathlist.parent(), oldPath[oldPath.length - 1]) + '; ';
oldPath.pop();
}
if (!this.mathlist.isCollapsed()) {
return speakableText(this, '', this.mathlist.getSelectedAtoms());
}
// announce start of denominator, etc
const relationName = relation(this.mathlist.parent(), leaf);
if (leaf.offset === 0) {
result += (relationName ? 'start of ' + relationName : 'unknown') + ': ';
}
const atom = this.mathlist.sibling(Math.max(1, this.mathlist.extent));
if (atom) {
result += speakableText(this, '', atom);
} else if (leaf.offset !== 0) { // don't say both start and end
result += relationName ? 'end of ' + relationName : 'unknown';
}
return result;
}
_announce(command, mathlist, atoms) {
if (typeof this.config.onAnnounce === 'function') {
this.config.onAnnounce(this, command, mathlist, atoms);
}
}
_onFocus() {
if (this.blurred) {
this.blurred = false;
// The textarea may be a span (on mobile, for example), so check that
// it has a focus() before calling it.
if (this.textarea.focus) { this.textarea.focus(); }
if (this.config.virtualKeyboardMode === 'onfocus') {
this.showVirtualKeyboard_();
}
Popover.updatePopoverPosition(this);
if (this.config.onFocus) { this.config.onFocus(this); }
this._requestUpdate();
}
}
_onBlur() {
if (!this.blurred) {
this.blurred = true;
this.ariaLiveText.textContent = '';
if (this.config.virtualKeyboardMode === 'onfocus') {
this.hideVirtualKeyboard_();
}
this.complete_({ discard: true });
this._requestUpdate();
if (this.config.onBlur) { this.config.onBlur(this); }
}
}
_onResize() {
this.element.classList.remove('ML__isNarrowWidth', 'ML__isWideWidth', 'ML__isExtendedWidth');
if (window.innerWidth >= 1024) {
this.element.classList.add('ML__isExtendedWidth');
} else if (window.innerWidth >= 768) {
this.element.classList.add('ML__isWideWidth');
} else {
this.element.classList.add('ML__isNarrowWidth');
}
Popover.updatePopoverPosition(this);
}
toggleKeystrokeCaption_() {
this.keystrokeCaptionVisible = !this.keystrokeCaptionVisible;
this.keystrokeCaption.innerHTML = '';
if (!this.keystrokeCaptionVisible) {
this.keystrokeCaption.style.visibility = 'hidden';
}
}
_showKeystroke(keystroke) {
const vb = this.keystrokeCaption;
if (vb && this.keystrokeCaptionVisible) {
const bounds = this.element.getBoundingClientRect();
vb.style.left = bounds.left + 'px';
vb.style.top = (bounds.top - 64) + 'px';
vb.innerHTML = '<span>' +
(Shortcuts.stringify(keystroke) || keystroke) +
'</span>' + vb.innerHTML;
vb.style.visibility = 'visible';
setTimeout(function () {
if (vb.childNodes.length > 0) {
vb.removeChild(vb.childNodes[vb.childNodes.length - 1]);
}
if (vb.childNodes.length === 0) {
vb.style.visibility = 'hidden';
}
}, 3000);
}
}
/**
* @param {string|string[]} command - A selector, or an array whose first element
* is a selector, and whose subsequent elements are arguments to the selector.
* Note that selectors do not include a final "_". They can be passed either
* in camelCase or kebab-case. So:
* ```javascript
* mf.$perform('selectAll');
* mf.$perform('select-all');
* ```
* both calls are valid and invoke the same selector.
*
* @method MathField#$perform
*/
$perform(command) {
if (!command) { return false; }
let handled = false;
let selector;
let args = [];
let dirty = false;
if (Array.isArray(command)) {
selector = command[0];
args = command.slice(1);
} else {
selector = command;
}
// Convert kebab case (like-this) to camel case (likeThis).
selector = selector.replace(/-\w/g, (m) => m[1].toUpperCase());
selector += '_';
if (typeof this.mathlist[selector] === 'function') {
if (/^(delete|transpose|add)/.test(selector)) {
this._resetKeystrokeBuffer();
}
if (/^(delete|transpose|add)/.test(selector) && this.mode !== 'command') {
// Update the undo state to account for the current selection
this.undoManager.pop();
this.undoManager.snapshot(this.config);
}
this.mathlist[selector](...args);
if (/^(delete|transpose|add)/.test(selector) && this.mode !== 'command') {
this.undoManager.snapshot(this.config);
}
if (/^(delete)/.test(selector) && this.mode === 'command') {
const command = this.mathlist.extractCommandStringAroundInsertionPoint();
const suggestions = Definitions.suggest(command);
if (suggestions.length === 0) {
Popover.hidePopover(this);
} else {
Popover.showPopoverWithLatex(this, suggestions[0].match, suggestions.length > 1);
}
}
dirty = true;
handled = true;
} else if (typeof this[selector] === 'function') {
dirty = this[selector](...args);
handled = true;
}
// If the command changed the selection so that it is no longer
// collapsed, or if it was an editing command, reset the inline
// shortcut buffer and the user style
if (!this.mathlist.isCollapsed() || /^(transpose|paste|complete|((moveToNextChar|moveToPreviousChar|extend).*))_$/.test(selector)) {
this._resetKeystrokeBuffer();
this.style = {};
}
// Render the mathlist
if (dirty) { this._requestUpdate(); }
return handled;
}
/**
* Perform a command, but:
* * focus the mathfield
* * provide haptic and audio feedback
* This is used by the virtual keyboard when command keys (delete, arrows, etc..)
* are pressed.
* @param {string} command
* @private
*/
performWithFeedback_(command) {
this.focus();
if (this.config.keypressVibration && navigator.vibrate) {
navigator.vibrate(HAPTIC_FEEDBACK_DURATION);
}
// Convert kebab case to camel case.
command = command.replace(/-\w/g, (m) => m[1].toUpperCase());
if (command === 'moveToNextPlaceholder' ||
command === 'moveToPreviousPlaceholder' ||
command === 'complete') {
if (this.returnKeypressSound) {
this.returnKeypressSound.load();
this.returnKeypressSound.play().catch(err => console.warn(err));
} else if (this.keypressSound) {
this.keypressSound.load();
this.keypressSound.play().catch(err => console.warn(err));
}
} else if (command === 'deletePreviousChar' ||
command === 'deleteNextChar' ||
command === 'deletePreviousWord' ||
command === 'deleteNextWord' ||
command === 'deleteToGroupStart' ||
command === 'deleteToGroupEnd' ||
command === 'deleteToMathFieldStart' ||
command === 'deleteToMathFieldEnd') {
if (this.deleteKeypressSound) {
this.deleteKeypressSound.load();
this.deleteKeypressSound.play().catch(err => console.warn(err));
} else if (this.keypressSound) {
this.keypressSound.load();
this.keypressSound.play().catch(err => console.warn(err));
}
} else if (this.keypressSound) {
this.keypressSound.load();
this.keypressSound.play().catch(err => console.warn(err));
}
return this.$perform(command);
}
/**
* Convert the atoms before the anchor to 'text' mode
* @param {number} count - how many atoms back to look at
* @param {function} until - callback to indicate when to stop
* @private
*/
convertLastAtomsToText_(count, until) {
if (typeof count === 'function') {
until = count;
count = Infinity;
}
if (count === undefined) { count = Infinity; }
let i = 0;
let done = false;
this.mathlist.contentWillChange();
while (!done) {
const atom = this.mathlist.sibling(i);
done = count === 0 || !atom || atom.mode !== 'math' ||
!(/mord|textord|mpunct/.test(atom.type) ||
(atom.type === 'mop' && /[a-zA-Z]+/.test(atom.body))) ||
atom.superscript || atom.subscript ||
(until && !until(atom));
if (!done) {
atom.applyStyle({ mode: 'text' });
atom.latex = atom.body;
}
i -= 1;
count -= 1;
}
this.mathlist.contentDidChange();
}
/**
* Convert the atoms before the anchor to 'math' mode 'mord'
* @param {number} count - how many atoms back to look at
* @param {function} until - callback to indicate when to stop
* @private
*/
convertLastAtomsToMath_(count, until) {
if (typeof count === 'function') {
until = count;
count = Infinity;
}
if (count === undefined) { count = Infinity; }
this.mathlist.contentWillChange();
let i = 0;
let done = false;
while (!done) {
const atom = this.mathlist.sibling(i);
done = count === 0 || !atom || atom.mode !== 'text' ||
atom.body === ' ' ||
(until && !until(atom));
if (!done) {
atom.applyStyle({ mode: 'math', type: 'mord' });
}
i -= 1;
count -= 1;
}
this.removeIsolatedSpace_();
this.mathlist.contentDidChange();
}
/**
* Going backwards from the anchor, if a text zone consisting of a single
* space character is found (i.e. it is surrounded by math zone),
* remove it.
* @private
*/
removeIsolatedSpace_() {
let i = 0;
while (this.mathlist.sibling(i) && this.mathlist.sibling(i).mode === 'math') {
i -= 1;
}
// If the atom before the last one converted is a
// text mode space, preceded by a math mode atom,
// remove the space
if (this.mathlist.sibling(i) &&
this.mathlist.sibling(i).mode === 'text' &&
this.mathlist.sibling(i).body === ' ' && (!this.mathlist.sibling(i - 1) ||
this.mathlist.sibling(i - 1).mode === 'math')) {
this.mathlist.contentWillChange();
this.mathlist.siblings().splice(i - 1, 1);
this.mathlist.contentDidChange();
// We need to adjust the selection after doing some surgery on the atoms list
// But we don't want to receive selection notification changes
// which could have a side effect of changing the mode :(
const save = this.mathlist.suppressChangeNotifications;
this.mathlist.suppressChangeNotifications = true;
this.mathlist.setSelection(this.mathlist.anchorOffset() - 1);
this.mathlist.suppressChangeNotifications = save;
}
}
/**
* Return the characters before anchor that could potentially be turned
* into text mode.
* This excludes things like 'mop' (e.g. \sin)
* @return {string}
* @method MathField#getTextBeforeAnchor_
* @private
*/
getTextBeforeAnchor_() {
// Going backwards, accumulate
let result = '';
let i = 0;
let done = false;
while (!done) {
const atom = this.mathlist.sibling(i);
done = !(atom &&
((atom.mode === 'text' && !atom.type) ||
(atom.mode === 'math' && /mord|textord|mpunct/.test(atom.type))));
if (!done) {
result = atom.body + result;
}
i -= 1;
}
return result;
}
/**
* Consider whether to switch mode give the content before the anchor
* and the character being input
*
* @param {string} keystroke
* @param {Event} evt - a Event corresponding to the keystroke
* @method MathField#smartMode_
* @return {boolean} true if the mode should change
* @private
*/
smartMode_(keystroke, evt) {
if (this.smartModeSuppressed) { return false; }
if (this.mathlist.endOffset() < this.mathlist.siblings().length - 1) { return false; }
if (!evt || evt.ctrlKey || evt.metaKey) { return false; }
const c = Keyboard.eventToChar(evt);
if (c.length > 1) { return false; } // Backspace, Left, etc...
if (!this.mathlist.isCollapsed()) {
// There is a selection
if (this.mode === 'text') {
if (/[/_^]/.test(c)) { return true; }
}
return false;
}
const context = this.getTextBeforeAnchor_() + c;
if (this.mode === 'text') {
// We're in text mode. Should we switch to math?
if (keystroke === 'Esc' || /[/\\]/.test(c)) {
// If this is a command for a fraction,
// or the '\' command mode key
// switch to 'math'
return true;
}
if (/[\^_]/.test(c)) {
// If this is a superscript or subscript
// switch to 'math'
if (/(^|\s)[a-zA-Z][^_]$/.test(context)) {
// If left hand context is a single letter,
// convert it to math
this.convertLastAtomsToMath_(1);
}
return true;
}
// If this is a closing matching fence
// switch to 'math' mode
const lFence = { ')': '(', '}': '{', ']': '[' }[c];
if (lFence && this.mathlist.parent() &&
this.mathlist.parent().type === 'leftright' &&
this.mathlist.parent().leftDelim === lFence) {
return true;
}
if (/(^|[^a-zA-Z])(a|I)[ ]$/.test(context)) {
// Single letters that are valid words in the current language
// Do nothing. @todo: localization
return false;
}
if (/[$€£₤₺¥¤฿¢₡₧₨₹₩₱]/u.test(c)) {
// A currency symbol.
// Switch to math mode
return true;
}
if (/(^|[^a-zA-Z'’])[a-zA-Z][ ]$/.test(context)) {
// An isolated letter, followed by a space:
// Convert the letter to math, stay in text mode.
this.convertLastAtomsToMath_(1);
return false;
}
if (/[^0-9]\.[^0-9\s]$/.test(context)) {
// A period followed by something other than space or a digit
// and not preceded by a digit.
// We thought this was a text period, but turns out it's not
// Turn it into a \cdot
this.convertLastAtomsToMath_(1);
const atom = this.mathlist.sibling(0);
atom.body = '⋅'; // centered dot
atom.autoFontFamily = 'cmr';
atom.latex = '\\cdot';
return true;
}
if (/(^|\s)[a-zA-Z][^a-zA-Z]$/.test(context)) {
// Single letter (x), followed by a non-letter (>, =...)
this.convertLastAtomsToMath_(1);
return true;
}
if (/\.[0-9]$/.test(context)) {
// If the new character is a digit,
// and it was preceded by a dot (which may have been converted
// to text)
// turn the dot back into 'math'
this.convertLastAtomsToMath_(1);
return true;
}
if (/[(][0-9+\-.]$/.test(context)) {
// An open paren followed by a number
// Turn the paren back to math and switch.
this.convertLastAtomsToMath_(1);
return true;
}
if (/[(][a-z][,;]$/.test(context)) {
// An open paren followed by a single letter, then a "," or ";"
// Turn the paren back and letter to math and switch.
this.convertLastAtomsToMath_(2);
return true;
}
// The tests above can look behind and change what had previously
// been entered. Now, let's just look at the typed character.
if (/[0-9+\-=><*|]$/.test(c)) {
// If this new character looks like a number,
// or a relational operator (=, <, >)
// or a "*" or "|"
// (note that <=, >=, etc... are handled separately as shortcuts)
// switch to 'math'
this.removeIsolatedSpace_();
return true;
}
} else {
// We're in math mode. Should we switch to text?
if (keystroke === 'Spacebar') {
this.convertLastAtomsToText_(a => /[a-z][:,;.]$/.test(a.body));
return true;
}
if (/[a-zA-Z]{3,}$/.test(context) && !/(dxd|abc|xyz|uvw)$/.test(context)) {
// A sequence of three characters
// (except for some exceptions)
// Convert them to text.
this.convertLastAtomsToText_(a => /[a-zA-Z:,;.]/.test(a.body));
return true;
}
if (/(^|\W)(if|If)$/i.test(context)) {
// @todo localization
this.convertLastAtomsToText_(1);
return true;
}
if (/(\u0393|\u0394|\u0398|\u039b|\u039E|\u03A0|\u03A3|\u03a5|\u03a6|\u03a8|\u03a9|[\u03b1-\u03c9]|\u03d1|\u03d5|\u03d6|\u03f1|\u03f5){3,}$/u.test(context) &&
!/(αβγ)$/.test(context)) {
// A sequence of three *greek* characters
// (except for one exception)
// Convert them to text.
this.convertLastAtomsToText_(a => /(:|,|;|.|\u0393|\u0394|\u0398|\u039b|\u039E|\u03A0|\u03A3|\u03a5|\u03a6|\u03a8|\u03a9|[\u03b1-\u03c9]|\u03d1|\u03d5|\u03d6|\u03f1|\u03f5)/u.test(a.body));
return true;
}
if (/\?|\./.test(c)) {
// If the last character is a period or question mark,
// turn it to 'text'
return true;
}
}
return false;
}
/**
* @param {string} keystroke
* @param {Event} evt - optional, an Event corresponding to the keystroke
* @method MathField#_onKeystroke
* @private
*/
_onKeystroke(keystroke, evt) {
// 1. Display the keystroke in the keystroke panel (if visible)
this._showKeystroke(keystroke);
// 2. Reset the timer for the keystroke buffer reset
clearTimeout(this.keystrokeBufferResetTimer);
// 3. Give a chance to the custom keystroke handler to intercept the event
if (this.config.onKeystroke && !this.config.onKeystroke(this, keystroke, evt)) {
if (evt && evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
// 4. Let's try to find a matching shortcut or command
let shortcut;
let stateIndex;
let selector;
let resetKeystrokeBuffer = false;
// 4.1 Check if the keystroke, prefixed with the previously typed keystrokes,
// would match a long shortcut (i.e. '~~')
// Ignore the key if command or control is pressed (it may be a shortcut,
// see 4.3)
if (this.mode !== 'command' && (!evt || (!evt.ctrlKey && !evt.metaKey))) {
const c = Keyboard.eventToChar(evt);
// The Backspace key will be handled as a delete command later (5.4)
// const c = Keyboard.eventToChar(evt);
if (c !== 'Backspace') {
if (!c || c.length > 1) {
// It was a non-alpha character (PageUp, End, etc...)
this._resetKeystrokeBuffer();
} else {
// Find the longest substring that matches a shortcut
const candidate = this.keystrokeBuffer + c;
let i = 0;
while (!shortcut && i < candidate.length) {
let siblings;
if (this.keystrokeBufferStates[i]) {
const mathlist = new EditableMathlist.EditableMathlist();
mathlist.root = MathAtom.makeRoot('math', ParserModule.parseTokens(Lexer.tokenize(this.keystrokeBufferStates[i].latex), this.config.default, null, this.config.macros));
mathlist.setPath(this.keystrokeBufferStates[i].selection);
siblings = mathlist.siblings();
} else {
siblings = this.mathlist.siblings();
}
shortcut = Shortcuts.forString(this.mode, siblings, candidate.slice(i), this.config);
i += 1;
}
stateIndex = i - 1;
this.keystrokeBuffer += c;
this.keystrokeBufferStates.push(this.undoManager.save());
if (Shortcuts.startsWithString(candidate, this.config).length <= 1) {
resetKeystrokeBuffer = true;
} else {
if (this.config.inlineShortcutTimeout) {
// Set a timer to reset the shortcut buffer
this.keystrokeBufferResetTimer = setTimeout(() => {
this._resetKeystrokeBuffer();
}, this.config.inlineShortcutTimeout);
}
}
}
}
}
// 4.2. Should we switch mode?
// Need to check this before determing if there's a valid shortcut
// since if we switch to math mode, we may want to apply the shortcut
// e.g. "slope = rise/run"
if (this.config.smartMode) {
const previousMode = this.mode;
if (shortcut) {
// If we found a shortcut (e.g. "alpha"),
// switch to math mode and insert it
this.mode = 'math';
} else if (this.smartMode_(keystroke, evt)) {
this.mode = { 'math': 'text', 'text': 'math' }[this.mode];
selector = '';
}
// Notify of mode change
if (this.mode !== previousMode && typeof this.config.onModeChange === 'function') {
this.config.onModeChange(this, this.mode);
}
}
// 4.3 Check if this matches a keystroke shortcut
// Need to check this **after** checking for inline shortcuts because
// shift+backquote is a keystroke that inserts "\~"", but "~~" is a
// shortcut for "\approx" and needs to have priority over shift+backquote
if (!shortcut && !selector) {
selector = Shortcuts.selectorForKeystroke(this.mode, keystroke);
}
// No shortcut :( We're done.
if (!shortcut && !selector) { return true; }
// 5. Perform the action matching this shortcut
// 5.1 Remove any error indicator (wavy underline) on the current command
// sequence (if there are any)
this.mathlist.decorateCommandStringAroundInsertionPoint(false);
// 5.2 If we have a `moveAfterParent` selector (usually triggered with
// `spacebar), and we're at the end of a smart fence, close the fence with
// an empty (.) right delimiter
const parent = this.mathlist.parent();
if (selector === 'moveAfterParent' && parent &&
parent.type === 'leftright' &&
this.mathlist.endOffset() === this.mathlist.siblings().length - 1 &&
this.config.smartFence &&
this.mathlist._insertSmartFence('.')) {
// Pressing the space bar (moveAfterParent selector) when at the end
// of a potential smartfence will close it as a semi-open fence
selector = '';
this._requestUpdate(); // Re-render the closed smartfence
}
// 5.3 If this is the Spacebar and we're just before or right after
// a text zone, insert the space inside the text zone
if (this.mode === 'math' && keystroke === 'Spacebar' && !shortcut) {
const nextSibling = this.mathlist.sibling(1);
const previousSibling = this.mathlist.sibling(-1);
if ((nextSibling && nextSibling.mode === 'text') ||
(previousSibling && previousSibling.mode === 'text')) {
this.mathlist.insert(' ', { mode: 'text' });
}
}
// 5.4 If there's a selector, perform it.
if ((selector && !this.$perform(selector)) || shortcut) {
// // 6.5 insert the shortcut
if (shortcut) {
// If the shortcut is a mandatory escape sequence (\}, etc...)
// don't make it undoable, this would result in syntactically incorrect
// formulas
if (!/^(\\{|\\}|\\[|\\]|\\@|\\#|\\$|\\%|\\^|\\_|\\backslash)$/.test(shortcut)) {
// To enable the substitution to be undoable,
// insert the character before applying the substitution
const style = { ...this.mathlist.anchorStyle(), ...this.style };
this.mathlist.insert(Keyboard.eventToChar(evt), {
suppressChangeNotifications: true,
mode: this.mode,
style: style
});
const saveMode = this.mode;
// Create a snapshot with the inserted character
this.undoManager.snapshotAndCoalesce(this.config);
// Revert to the state before the beginning of the shortcut
// (restore doesn't change the undo stack)
this.undoManager.restore(this.keystrokeBufferStates[stateIndex], { ...this.config, suppressChangeNotifications: true });
this.mode = saveMode;
}
this.mathlist.contentWillChange();
const save = this.mathlist.suppressChangeNotifications;
this.mathlist.suppressChangeNotifications = true;
// Insert the substitute, possibly as a smart fence
const style = { ...this.mathlist.anchorStyle(), ...this.style };
this.mathlist.insert(shortcut, {
format: 'latex',
mode: this.mode,
style: style,
smartFence: true
});
// Check if as a result of the substitution there is now an isolated
// (text mode) space (surrounded by math). In which case, remove it.
this.removeIsolatedSpace_();
// Switch (back) to text mode if the shortcut ended with a space
if (shortcut.endsWith(' ')) {
this.mode = 'text';
this.mathlist.insert(' ', { mode: 'text', style: style });
}
this.mathlist.suppressChangeNotifications = save;
this.mathlist.contentDidChange();
this.undoManager.snapshot(this.config);
this._requestUpdate();
this._announce('replacement');
// If we're done with the shortcuts (found a unique one), reset it.
if (resetKeystrokeBuffer) {
this._resetKeystrokeBuffer();
}
}
}
// 6. Make sure the insertion point is scrolled into view
this.scrollIntoView();
// 7. Keystroke has been handled, if it wasn't caught in the default
// case, so prevent propagation
if (evt && evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
/**
* This handler is invoked when text has been typed, pasted in or input with
* an input method. As a result, `text` can be a sequence of characters to
* be inserted.
* @param {string} text
* @param {object} options
* @param {boolean} options.focus - If true, the mathfield will be focused
* @param {boolean} options.feedback - If true, provide audio and haptic feedback
* @param {boolean} options.simulateKeystroke - If true, generate some synthetic
* keystrokes (useful to trigger inline shortcuts, for example)
* @param {boolean} options.commandMode - If true, switch to command mode if
* necessary, then insert text
* @private
*/
_onTypedText(text, options) {
options = options || {};
// Focus, then provide audio and haptic feedback
if (options.focus) { this.$focus(); }
if (options.feedback) {
if (this.config.keypressVibration && navigator.vibrate) {
navigator.vibrate(HAPTIC_FEEDBACK_DURATION);
}
if (this.keypressSound) {
this.keypressSound.load();
this.keypressSound.play().catch(err => console.warn(err));
}
}
if (options.commandMode && this.mode !== 'command') {
this.switchMode_('command');
}
// Remove any error indicator on the current command sequence
// (if there is one)
this.mathlist.decorateCommandStringAroundInsertionPoint(false);
if (options.simulateKeystroke) {
// for (const c of text) {
const c = text.charAt(0);
const ev = Keyboard.charToEvent(c);
if (!this.$keystroke(Keyboard.keyboardEventToString(ev), ev)) { return; }
// }
}
// Insert the specified text at the current insertion point.
// If the selection is not collapsed, the content will be deleted first.
let popoverText = '';
let displayArrows = false;
if (this.pasteInProgress) {
this.pasteInProgress = false;
// This call was made in response to a paste event.
// Interpret `text` as a 'smart' expression (could be LaTeX, could be
// UnicodeMath)
this.mathlist.insert(text, {
smartFence: this.config.smartFence,
mode: 'math'
});
} else {
const style = { ...this.mathlist.anchorStyle(), ...this.style };
// Decompose the string into an array of graphemes.
// This is necessary to correctly process what is displayed as a single
// glyph (a grapheme) but which is composed of multiple Unicode
// codepoints. This is the case in particular for some emojis, such as
// those with a skin tone modifier, the country flags emojis or
// compound emojis such as the professional emojis, including the
// David Bowie emoji: 👨🏻🎤
const graphemes = GraphemeSplitter.splitGraphemes(text);
for (const c of graphemes) {
if (this.mode === 'command') {
this.mathlist.removeSuggestion();
this.suggestionIndex = 0;
const command = this.mathlist.extractCommandStringAroundInsertionPoint();
const suggestions = Definitions.suggest(command + c);
displayArrows = suggestions.length > 1;
if (suggestions.length === 0) {
this.mathlist.insert(c, { mode: 'command' });
if (/^\\[a-zA-Z\\*]+$/.test(command + c)) {
// This looks like a command name, but not a known one
this.mathlist.decorateCommandStringAroundInsertionPoint(true);
}
Popover.hidePopover(this);
} else {
this.mathlist.insert(c, { mode: 'command' });
if (suggestions[0].match !== command + c) {
this.mathlist.insertSuggestion(suggestions[0].match, -suggestions[0].match.length + command.length + 1);
}
popoverText = suggestions[0].match;
}
} else if (this.mode === 'math') {
// Some characters are mapped to commands. Handle them here.
// This is important to handle synthetic text input and
// non-US keyboards, on which, fop example, the '^' key is
// not mapped to 'Shift-Digit6'.
const selector = {
'^': 'moveToSuperscript',
'_': 'moveToSubscript',
' ': 'moveAfterParent'
}[c];
if (selector) {
if (selector === 'moveToSuperscript') {
if (this._superscriptDepth() >= this.config.scriptDepth[1]) {
this._announce('plonk');
return;
}
} else if (selector === 'moveToSubscript') {
if (this._subscriptDepth() >= this.config.scriptDepth[0]) {
this._announce('plonk');
return;
}
}
this.$perform(selector);
} else {
if (this.config.smartSuperscript &&
this.mathlist.relation() === 'superscript' &&
/[0-9]/.test(c) &&
this.mathlist.siblings().filter(x => x.type !== 'first').length === 0) {
// We are inserting a digit into an empty superscript
// If smartSuperscript is on, insert the digit, and
// exit the superscript.
this.mathlist.insert(c, { mode: 'math', style: style });
this.mathlist.moveAfterParent_();
} else {
this.mathlist.insert(c, {
mode: 'math',
style: style,
smartFence: this.config.smartFence
});
}
}
} else if (this.mode === 'text') {
this.mathlist.insert(c, { mode: 'text', style: style });
}
}
}
if (this.mode !== 'command') {
this.undoManager.snapshotAndCoalesce(this.config);
}
// Render the mathlist
this._requestUpdate();
// Make sure the insertion point is visible
this.scrollIntoView();
// Since the location of the popover depends on the position of the caret
// only show the popover after the formula has been rendered and the
// position of the caret calculated
Popover.showPopoverWithLatex(this, popoverText, displayArrows);
}
/*
* Return a hash (32-bit integer) representing the content of the mathfield
* (but not the selection state)
*/
_hash() {
let result = 0;
const str = this.mathlist.root.toLatex(false);
for (let i = 0; i < str.length; i++) {
result = result * 31 + str.charCodeAt(i);
result = result | 0; // Force it to a 32-bit number
}
return Math.abs(result);
}
_requestUpdate() {
if (!this.dirty) {
this.dirty = true;
requestAnimationFrame(_ => this._render());
}
}
/**
* Lay-out the math field and generate the DOM.
*
* This is usually done automatically, but if the font-size, or other geometric
* attributes are modified, outside of MathLive, this function may need to be
* called explicitly.
*
* @method MathField#render
* @private
*/
_render(renderOptions) {
renderOptions = renderOptions || {};
this.dirty = false;
//
// 1. Stop and reset read aloud state
//
if (!window.mathlive) { window.mathlive = {}; }
//
// 2. Validate selection
//
if (!this.mathlist.anchor()) {
console.warn('Invalid selection, resetting it. ' + MathPath.pathToString(this.mathlist.path));
this.mathlist.path = [{ relation: 'body', offset: 0 }];
}
//
// 3. Update selection state and blinking cursor (caret)
//
this.mathlist.forEach(a => {
a.caret = '';
a.isSelected = false;
});
const hasFocus = this.$hasFocus();
if (this.mathlist.isCollapsed()) {
this.mathlist.anchor().caret = hasFocus ? this.mode : '';
} else {
this.mathlist.forEachSelected(a => { a.isSelected = true; });
}
//
// 4. Create spans corresponding to the updated mathlist
//
const spans = MathAtom.decompose({
mathstyle: 'displaystyle',
generateID: {
// Using the hash as a seed for the ID
// keeps the IDs the same until the content of the field changes.
seed: this._hash(),
// The `groupNumbers` flag indicates that extra spans should be generated
// to represent group of atoms, for example, a span to group
// consecutive digits to represent a number.
groupNumbers: renderOptions.forHighlighting,
},
macros: this.config.macros
}, this.mathlist.root);
//
// 5. Construct struts around the spans
//
const base = Span.makeSpan(spans, 'ML__base');
base.attributes = {
// Sometimes Google Translate kicks in an attempts to 'translate' math
// This doesn't work very well, so turn off translate
'translate': 'no',
// Hint to screen readers to not attempt to read this span
// They should use instead the 'aria-label' below.
'aria-hidden': 'true'
};
const topStrut = Span.makeSpan('', 'ML__strut');
topStrut.setStyle('height', base.height, 'em');
const struts = [topStrut];
if (base.depth !== 0) {
const bottomStrut = Span.makeSpan('', 'ML__strut--bottom');
bottomStrut.setStyle('height', base.height + base.depth, 'em');
bottomStrut.setStyle('vertical-align', -base.depth, 'em');
struts.push(bottomStrut);
}
struts.push(base);
const wrapper = Span.makeSpan(struts, 'ML__mathlive');
//
// 6. Generate markup and accessible node
//
this.field.innerHTML = wrapper.toMarkup(0, this.config.horizontalSpacingScale);
this.field.classList.toggle('ML__focused', hasFocus);
// Probably want to generate content on the fly depending on what to speak
this.accessibleNode.innerHTML =
"<math xmlns='http://www.w3.org/1998/Math/MathML'>" +
MathAtom.toMathML(this.mathlist.root, this.config) +
"</math>";
//this.ariaLiveText.textContent = "";
//
// 7. Calculate selection rectangle
//
const selectionRect = this._getSelectionBounds();
if (selectionRect) {
const selectionElement = document.createElement('div');
selectionElement.classList.add('ML__selection');
selectionElement.style.position = 'absolute';
selectionElement.style.left = selectionRect.left + 'px';
selectionElement.style.top = selectionRect.top + 'px';
selectionElement.style.width = Math.ceil(selectionRect.right - selectionRect.left) + 'px';
selectionElement.style.height = Math.ceil(selectionRect.bottom - selectionRect.top - 1) + 'px';
this.field.insertBefore(selectionElement, this.field.childNodes[0]);
}
}
_onPaste() {
// Make note we're in the process of pasting. The subsequent call to
// onTypedText() will take care of interpreting the clipboard content
this.pasteInProgress = true;
return true;
}
_onCut() {
// Clearing the selection will have the side effect of clearing the
// content of the textarea. However, the textarea value is what will
// be copied to the clipboard, so defer the clearing of the selection
// to later, after the cut operation has been handled.
setTimeout(function () {
this.$clearSelection();
this._requestUpdate();
}.bind(this), 0);
return true;
}
_onCopy(e) {
if (this.mathlist.isCollapsed()) {
e.clipboardData.setData('text/plain', this.$text('latex-expanded'));
e.clipboardData.setData('application/json', this.$text('json'));
e.clipboardData.setData('application/xml', this.$text('mathML'));
} else {
e.clipboardData.setData('text/plain', this.$selectedText('latex-expanded'));
e.clipboardData.setData('application/json', this.$selectedText('json'));
e.clipboardData.setData('application/xml', this.$selectedText('mathML'));
}
// Prevent the current document selection from being written to the clipboard.
e.preventDefault();
}
formatMathlist(root, format) {
format = format || 'latex';
let result = '';
if (format === 'latex' || format === 'latex-expanded') {
result = root.toLatex(format === 'latex-expanded');
} else if (format === 'mathML') {
result = root.toMathML(this.config);
} else if (format === 'spoken') {
result = MathAtom.toSpeakableText(root, this.config);
} else if (format === 'spoken-text') {
const saveTextToSpeechMarkup = this.config.textToSpeechMarkup;
this.config.textToSpeechMarkup = '';
result = MathAtom.toSpeakableText(root, this.config);
this.config.textToSpeechMarkup = saveTextToSpeechMarkup;
} else if (format === 'spoken-ssml' || format === 'spoken-ssml-withHighlighting') {
const saveTextToSpeechMarkup = this.config.textToSpeechMarkup;
const saveGenerateID = this.config.generateID;
this.config.textToSpeechMarkup = 'ssml';
if (format === 'spoken-ssml-withHighlighting') {
this.config.generateID = true;
}
result = MathAtom.toSpeakableText(root, this.config);
this.config.textToSpeechMarkup = saveTextToSpeechMarkup;
this.config.generateID = saveGenerateID;
} else if (format === 'json') {
const json = MathAtom.toAST(root, this.config);
result = JSON.stringify(json);
} else if (format === 'ASCIIMath') {
result = toASCIIMath(root, this.config);
} else {
console.warn('Unknown format :', format);
}
return result;
}
//
// PUBLIC API
//
/**
* Return a textual representation of the mathfield.
* @param {string} [format='latex']. One of
* * `'latex'`
* * `'latex-expanded'` : all macros are recursively expanded to their definition
* * `'spoken'`
* * `'spoken-text'`
* * `'spoken-ssml'`
* * `spoken-ssml-withHighlighting`
* * `'mathML'`
* * `'json'`
* @return {string}
* @method MathField#$text
*/
$text(format) {
return this.formatMathlist(this.mathlist.root, format);
}
/**
* Return a textual representation of the selection in the mathfield.
* @param {string} [format='latex']. One of
* * `'latex'`
* * `'latex-expanded'` : all macros are recursively expanded to their definition
* * `'spoken'`
* * `'spoken-text'`
* * `'spoken-ssml'`
* * `spoken-ssml-withHighlighting`
* * `'mathML'`
* * `'json'`
* @return {string}
* @method MathField#$selectedText
*/
$selectedText(format) {
const atoms = this.mathlist.getSelectedAtoms();
if (!atoms) { return ''; }
const root = MathAtom.makeRoot('math', atoms);
return this.formatMathlist(root, format);
}
/**
* Return true if the length of the selection is 0, that is, if it is a single
* insertion point.
* @return {boolean}
* @method MathField#$selectionIsCollapsed
*/
$selectionIsCollapsed() {
return this.mathlist.isCollapsed();
}
/**
* Return the depth of the selection group. If the selection is at the root level,
* returns 0. If the selection is a portion of the numerator of a fraction
* which is at the root level, return 1. Note that in that case, the numerator
* would be the "selection group".
* @return {number}
* @method MathField#$selectionDepth
*/
$selectionDepth() {
return this.mathlist.path.length;
}
_superscriptDepth() {
let result = 0;
let i = 0;
let atom = this.mathlist.ancestor(i);
let wasSuperscript = false;
while (atom) {
if (atom.superscript || atom.subscript) {
result += 1;
}
if (atom.superscript) {
wasSuperscript = true;
} else if (atom.subscript) {
wasSuperscript = false;
}
i += 1;
atom = this.mathlist.ancestor(i);
}
return wasSuperscript ? result : 0;
}
_subscriptDepth() {
let result = 0;
let i = 0;
let atom = this.mathlist.ancestor(i);
let wasSubscript = false;
while (atom) {
if (atom.superscript || atom.subscript) {
result += 1;
}
if (atom.superscript) {
wasSubscript = false;
} else if (atom.subscript) {
wasSubscript = true;
}
i += 1;
atom = this.mathlist.ancestor(i);
}
return wasSubscript ? result : 0;
}
/**
* Return true if the selection starts at the beginning of the selection group.
* @return {boolean}
* @method MathField#$selectionAtStart
*/
$selectionAtStart() {
return this.mathlist.startOffset() === 0;
}
/**
* Return true if the selection extends to the end of the selection group.
* @return {boolean}
* @method MathField#$selectionAtEnd
*/
$selectionAtEnd() {
return this.mathlist.endOffset() >= this.mathlist.siblings().length - 1;
}
/*
* True if the entire group is selected
* */
groupIsSelected() {
return this.mathlist.startOffset() === 0 &&
this.mathlist.endOffset() >= this.mathlist.siblings().length - 1;
}
/**
* If `text` is not empty, sets the content of the mathfield to the
* text interpreted as a LaTeX expression.
* If `text` is empty (or omitted), return the content of the mahtfield as a
* LaTeX expression.
* @param {string} text
*
* @param {Object.<string, any>} options
* @param {boolean} options.suppressChangeNotifications - If true, the
* handlers for the contentWillChange and contentDidChange notifications will
* not be invoked. Default `false`.
*
* @return {string}
* @method MathField#$latex
*/
$latex(text, options) {
if (text) {
const oldValue = this.mathlist.root.toLatex();
if (text !== oldValue) {
options = options || {};
this.mathlist.insert(text, Object.assign({}, this.config, {
insertionMode: 'replaceAll',
selectionMode: 'after',
format: 'latex',
mode: 'math',
suppressChangeNotifications: options.suppressChangeNotifications
}));
this.undoManager.snapshot(this.config);
this._requestUpdate();
}
return text;
}
// Return the content as LaTeX
return this.mathlist.root.toLatex();
}
/**
* Return the DOM element associated with this mathfield.
*
* Note that `this.$el().mathfield = this`
* @return {HTMLElement}
* @method MathField#$el
*/
$el() {
return this.element;
}
undo() {
this.complete_();
// Undo to the previous state
this.undoManager.undo(this.config);
return true;
}
redo() {
this.complete_();
this.undoManager.redo(this.config);
return true;
}
scrollIntoView() {
// If a render is pending, do it now to make sure we have correct layout
// and caret position
if (this.dirty) {
this._render();
}
let pos = this._getCaretPosition();
const fieldBounds = this.field.getBoundingClientRect();
if (!pos) {
const selectionBounds = this._getSelectionBounds();
if (selectionBounds) {
pos = {
x: selectionBounds.right + fieldBounds.left - this.field.scrollLeft,
y: selectionBounds.top + fieldBounds.top - this.field.scrollTop
};
}
}
if (pos) {
const x = pos.x - window.scrollX;
if (x < fieldBounds.left) {
this.field.scroll({
top: 0,
left: x - fieldBounds.left + this.field.scrollLeft - 20,
behavior: 'smooth'
});
} else if (x > fieldBounds.right) {
this.field.scroll({
top: 0,
left: x - fieldBounds.right + this.field.scrollLeft + 20,
behavior: 'smooth'
});
}
}
}
scrollToStart() {
this.field.scroll(0, 0);
}
scrollToEnd() {
const fieldBounds = this.field.getBoundingClientRect();
this.field.scroll(fieldBounds.left - window.scrollX, 0);
}
/**
*
* @method MathField#enterCommandMode_
* @private
*/
enterCommandMode_() {
this.switchMode_('command');
}
copyToClipboard_() {
this.$focus();
// If the selection is empty, select the entire field before
// copying it.
if (this.mathlist.isCollapsed()) {
this.$select();
}
document.execCommand('copy');
return false;
}
cutToClipboard_() {
this.$focus();
document.execCommand('cut');
return true;
}
pasteFromClipboard_() {
this.$focus();
document.execCommand('paste');
return true;
}
/**
* This method can be invoked as a selector with {@linkcode MathField#$perform $perform("insert")}
* or called explicitly.
*
* It will insert the specified block of text at the current insertion point,
* according to the insertion mode specified.
*
* After the insertion, the selection will be set according to the `selectionMode`.
* @param {string} s - The text to be inserted
*
* @param {Object.<string, any>} [options={}]
*
* @param {'placeholder' | 'after' | 'before' | 'item'} options.selectionMode - Describes where the selection
* will be after the insertion:
* * `'placeholder'`: the selection will be the first available placeholder
* in the item that has been inserted (default)
* * `'after'`: the selection will be an insertion point after the item that
* has been inserted,
* * `'before'`: the selection will be an insertion point before
* the item that has been inserted
* * `'item'`: the item that was inserted will be selected
*
* @param {'auto' | 'latex'} options.format - The format of the string `s`:
* * `'auto'`: the string is interpreted as a latex fragment or command)
* (default)
* * `'latex'`: the string is interpreted strictly as a latex fragment
*
* @param {boolean} options.focus - If true, the mathfield will be focused after
* the insertion
*
* @param {boolean} options.feedback - If true, provide audio and haptic feedback
*
* @param {'text' | 'math' | ''} options.mode - 'text' or 'math'. If empty, the current mode
* is used (default)
*
* @param {boolean} options.resetStyle - If true, the style after the insertion
* is the same as the style before (if false, the style after the
* insertion is the style of the last inserted atom).
*
* @method MathField#$insert
*/
$insert(s, options) {
if (typeof s === 'string' && s.length > 0) {
options = options || {};
if (options.focus) { this.$focus(); }
if (options.feedback) {
if (this.config.keypressVibration && navigator.vibrate) {
navigator.vibrate(HAPTIC_FEEDBACK_DURATION);
}
if (this.keypressSound) {
this.keypressSound.load();
this.keypressSound.play();
}
}
if (s === '\\\\') {
// This string is interpreted as an "insert row after" command
this.mathlist.addRowAfter_();
} else if (s === '&') {
this.mathlist.addColumnAfter_();
} else {
const savedStyle = this.style;
this.mathlist.insert(s, {
mode: this.mode,
style: this.mathlist.anchorStyle(),
...options
});
if (options.resetStyle) {
this.style = savedStyle;
}
}
this.undoManager.snapshot(this.config);
this._requestUpdate();
return true;
}
return false;
}
switchMode_(mode, prefix, suffix) {
this._resetKeystrokeBuffer();
// Suppress (temporarily) smart mode if switching to/from text or math
// This prevents switching to/from command mode from supressing smart mode.
this.smartModeSuppressed = /text|math/.test(this.mode) && /text|math/.test(mode);
if (prefix) {
this.$insert(prefix, {
format: 'latex',
mode: { 'math': 'text', 'text': 'math' }[mode]
});
}
// Remove any error indicator on the current command sequence (if there is one)
this.mathlist.decorateCommandStringAroundInsertionPoint(false);
if (mode === 'command') {
this.mathlist.removeSuggestion();
Popover.hidePopover(this);
this.suggestionIndex = 0;
// Switch to the command mode keyboard layer
if (this.virtualKeyboardVisible) {
this.switchKeyboardLayer_('lower-command');
}
this.mathlist.insert('\u001b', { mode: 'math' });
} else {
this.mode = mode;
}
if (suffix) {
this.$insert(suffix, {
format: 'latex',
mode: mode
});
}
// Notify of mode change
if (typeof this.config.onModeChange === 'function') {
this.config.onModeChange(this, this.mode);
}
this._requestUpdate();
}
/**
* When in command mode, insert the select command and return to math mode
* If escape is true, the command is discared.
* @param {object} options
* @param {boolean} options.discard if true, the command is discarded and the
* mode switched back to math
* @param {boolean} options.acceptSuggestion if true, accept the suggestion to
* complete the command. Otherwise, only use what has been entered so far.
* @method MathField#complete_
* @private
*/
complete_(options) {
options = options || {};
Popover.hidePopover(this);
if (options.discard) {
this.mathlist.spliceCommandStringAroundInsertionPoint(null);
this.switchMode_('math');
return true;
}
const command = this.mathlist.extractCommandStringAroundInsertionPoint(!options.acceptSuggestion);
if (command) {
if (command === '\\(' || command === '\\)') {
this.mathlist.spliceCommandStringAroundInsertionPoint([]);
this.mathlist.insert(command.slice(1), { mode: this.mode });
} else {
// We'll assume we want to insert in math mode
// (commands are only available in math mode)
const mode = 'math';
if (Definitions.commandAllowed(mode, command)) {
const mathlist = ParserModule.parseTokens(Lexer.tokenize(command), mode, null, this.config.macros);
this.mathlist.spliceCommandStringAroundInsertionPoint(mathlist);
} else {
// This wasn't a simple function or symbol.
// Interpret the input as LaTeX code
const mathlist = ParserModule.parseTokens(Lexer.tokenize(command), mode, null, this.config.macros);
if (mathlist) {
this.mathlist.spliceCommandStringAroundInsertionPoint(mathlist);
} else {
this.mathlist.decorateCommandStringAroundInsertionPoint(true);
}
}
}
this.undoManager.snapshot(this.config);
this._announce('replacement');
return true;
}
return false;
}
_updateSuggestion() {
this.mathlist.positionInsertionPointAfterCommitedCommand();
this.mathlist.removeSuggestion();
const command = this.mathlist.extractCommandStringAroundInsertionPoint();
const suggestions = Definitions.suggest(command);
if (suggestions.length === 0) {
Popover.hidePopover(this);
this.mathlist.decorateCommandStringAroundInsertionPoint(true);
} else {
const index = this.suggestionIndex % suggestions.length;
const l = command.length - suggestions[index].match.length;
if (l !== 0) {
this.mathlist.insertSuggestion(suggestions[index].match, l);
}
Popover.showPopoverWithLatex(this, suggestions[index].match, suggestions.length > 1);
}
this._requestUpdate();
}
nextSuggestion_() {
this.suggestionIndex += 1;
// The modulo of the suggestionIndex is used to determine which suggestion
// to display, so no need to worry about rolling over.
this._updateSuggestion();
return false;
}
previousSuggestion_() {
this.suggestionIndex -= 1;
if (this.suggestionIndex < 0) {
// We're rolling over
// Get the list of suggestions, so we can know how many there are
// Not very efficient, but simple.
this.mathlist.removeSuggestion();
const command = this.mathlist.extractCommandStringAroundInsertionPoint();
const suggestions = Definitions.suggest(command);
this.suggestionIndex = suggestions.length - 1;
}
this._updateSuggestion();
return false;
}
/**
* Attach event handlers to an element so that it will react by executing
* a command when pressed.
* `'command'` can be:
* - a string, a single selector
* - an array, whose first element is a selector followed by one or more arguments.
* - an object, with the following keys:
* * 'default': command performed on up, with a down + up sequence with no
* delay between down and up
* * 'alt', 'shift', 'altshift' keys: command performed on up with
* one of these modifiers pressed
* * 'pressed': command performed on 'down'
* * 'pressAndHoldStart': command performed after a tap/down followed by a
* delay (optional)
* * 'pressAndHoldEnd': command performed on up, if there was a delay
* between down and up, if absent, 'default' is performed
* The value of the keys specify which selector (string
* or array) to perform depending on the keyboard state when the button is
* pressed.
*
* The 'pressed' and 'active' classes will get added to
* the element, as the :hover and :active pseudo-classes are not reliable
* (at least on Chrome Android).
*
* @param {HTMLElement} el
* @param {object|string} command
* @private
*/
_attachButtonHandlers(el, command) {
const that = this;
if (typeof command === 'object' && (command.default || command.pressed)) {
// Attach the default (no modifiers pressed) command to the element
if (command.default) {
el.setAttribute('data-' + this.config.namespace + 'command', JSON.stringify(command.default));
}
if (command.alt) {
el.setAttribute('data-' + this.config.namespace + 'command-alt', JSON.stringify(command.alt));
}
if (command.altshift) {
el.setAttribute('data-' + this.config.namespace + 'command-altshift', JSON.stringify(command.altshift));
}
if (command.shift) {
el.setAttribute('data-' + this.config.namespace + 'command-shift', JSON.stringify(command.shift));
}
// .pressed: command to perform when the button is pressed (i.e.
// on mouse down/touch). Otherwise the command is performed when
// the button is released
if (command.pressed) {
el.setAttribute('data-' + this.config.namespace + 'command-pressed', JSON.stringify(command.pressed));
}
if (command.pressAndHoldStart) {
el.setAttribute('data-' + this.config.namespace + 'command-pressAndHoldStart', JSON.stringify(command.pressAndHoldStart));
}
if (command.pressAndHoldEnd) {
el.setAttribute('data-' + this.config.namespace + 'command-pressAndHoldEnd', JSON.stringify(command.pressAndHoldEnd));
}
} else {
// We need to turn the command into a string to attach it to the dataset
// associated with the button (the command could be an array made of a
// selector and one or more parameters)
el.setAttribute('data-' + this.config.namespace + 'command', JSON.stringify(command));
}
let pressHoldStart;
let pressHoldElement;
let touchID;
let syntheticTarget; // Target while touch move
let pressAndHoldTimer;
on(el, 'mousedown touchstart:passive', function (ev) {
if (ev.type !== 'mousedown' || ev.buttons === 1) {
// The primary button was pressed or the screen was tapped.
ev.stopPropagation();
ev.preventDefault();
el.classList.add('pressed');
pressHoldStart = Date.now();
// Record the ID of the primary touch point for tracking on touchmove
if (ev.type === 'touchstart') { touchID = ev.changedTouches[0].identifier; }
// Parse the JSON to get the command (and its optional arguments)
// and perform it immediately
const command = el.getAttribute('data-' + that.config.namespace + 'command-pressed');
if (command) {
that.$perform(JSON.parse(command));
}
// If there is a `press and hold start` command, perform it
// after a delay, if we're still pressed by then.
const pressAndHoldStartCommand = el.getAttribute('data-' + that.config.namespace + 'command-pressAndHoldStart');
if (pressAndHoldStartCommand) {
pressHoldElement = el;
if (pressAndHoldTimer) { clearTimeout(pressAndHoldTimer); }
pressAndHoldTimer = window.setTimeout(function () {
if (el.classList.contains('pressed')) {
that.$perform(JSON.parse(pressAndHoldStartCommand));
}
}, 300);
}
}
});
on(el, 'mouseleave touchcancel', function () {
el.classList.remove('pressed');
// let command = el.getAttribute('data-' + that.config.namespace +
// 'command-pressAndHoldEnd');
// const now = Date.now();
// if (command && now > pressHoldStart + 300) {
// that.$perform(JSON.parse(command));
// }
});
on(el, 'touchmove:passive', function (ev) {
// Unlike with mouse tracking, touch tracking only sends events
// to the target that was originally tapped on. For consistency,
// we want to mimic the behavior of the mouse interaction by
// tracking the touch events and dispatching them to potential targets
ev.preventDefault();
for (let i = 0; i < ev.changedTouches.length; i++) {
if (ev.changedTouches[i].identifier === touchID) {
// Found a touch matching our primary/tracked touch
const target = document.elementFromPoint(ev.changedTouches[i].clientX, ev.changedTouches[i].clientY);
if (target !== syntheticTarget && syntheticTarget) {
syntheticTarget.dispatchEvent(new MouseEvent('mouseleave'), { bubbles: true });
syntheticTarget = null;
}
if (target) {
syntheticTarget = target;
target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, buttons: 1 }));
}
}
}
});
on(el, 'mouseenter', function (ev) {
if (ev.buttons === 1) {
el.classList.add('pressed');
}
});
on(el, 'mouseup touchend click', function (ev) {
if (syntheticTarget) {
ev.stopPropagation();
ev.preventDefault();
const target = syntheticTarget;
syntheticTarget = null;
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
return;
}
el.classList.remove('pressed');
el.classList.add('active');
if (ev.type === 'click' && ev.detail !== 0) {
// This is a click event triggered by a mouse interaction
// (and not a keyboard interaction)
// Ignore it, we'll handle the mouseup (or touchend) instead.
ev.stopPropagation();
ev.preventDefault();
return;
}
// Since we want the active state to be visible for a while,
// use a timer to remove it after a short delay
window.setTimeout(function () { el.classList.remove('active'); }, 150);
let command = el.getAttribute('data-' + that.config.namespace +
'command-pressAndHoldEnd');
const now = Date.now();
// If the button has not been pressed for very long or if we were
// not the button that started the press and hold, don't consider
// it a press-and-hold.
if (el !== pressHoldElement || now < pressHoldStart + 300) {
command = undefined;
}
if (!command && ev.altKey && ev.shiftKey) {
command = el.getAttribute('data-' + that.config.namespace +
'command-altshift');
}
if (!command && ev.altKey) {
command = el.getAttribute('data-' + that.config.namespace +
'command-alt');
}
if (!command && ev.shiftKey) {
command = el.getAttribute('data-' + that.config.namespace +
'command-shift');
}
if (!command) {
command = el.getAttribute('data-' + that.config.namespace +
'command');
}
if (command) {
// Parse the JSON to get the command (and its optional arguments)
// and perform it
that.$perform(JSON.parse(command));
}
ev.stopPropagation();
ev.preventDefault();
});
}
_makeButton(label, cls, ariaLabel, command) {
const button = document.createElement('span');
button.innerHTML = label;
if (cls) { button.classList.add([].slice.call(cls.split(' '))); }
if (ariaLabel) { button.setAttribute('aria-label', ariaLabel); }
this._attachButtonHandlers(button, command);
return button;
}
/*
* Alternate options are displayed when a key on the virtual keyboard is pressed
* and held.
*
*/
showAlternateKeys_(keycap, altKeys) {
const altContainer = getSharedElement('mathlive-alternate-keys-panel', 'ML__keyboard alternate-keys');
if (this.virtualKeyboard.classList.contains('material')) {
altContainer.classList.add('material');
}
if (altKeys.length >= 7) {
// Width 4
altContainer.style.width = '286px';
} else if (altKeys.length === 4 || altKeys.length === 2) {
// Width 2
altContainer.style.width = '146px';
} else if (altKeys.length === 1) {
// Width 1
altContainer.style.width = '86px';
} else {
// Width 3
altContainer.style.width = '146px';
}
// Reset container height
altContainer.style.height = 'auto';
let markup = '';
for (const altKey of altKeys) {
markup += '<li';
if (typeof altKey === 'string') {
markup += ' data-latex="' + altKey.replace(/"/g, '"') + '"';
} else {
if (altKey.latex) {
markup += ' data-latex="' + altKey.latex.replace(/"/g, '"') + '"';
}
if (altKey.content) {
markup += ' data-content="' + altKey.content.replace(/"/g, '"') + '"';
}
if (altKey.insert) {
markup += ' data-insert="' + altKey.insert.replace(/"/g, '"') + '"';
}
if (altKey.command) {
markup += " data-command='" + altKey.command.replace(/"/g, '"') + "'";
}
if (altKey.aside) {
markup += ' data-aside="' + altKey.aside.replace(/"/g, '"') + '"';
}
if (altKey.classes) {
markup += ' data-classes="' + altKey.classes + '"';
}
}
markup += '>';
markup += altKey.label || '';
markup += '</li>';
}
markup = '<ul>' + markup + '</ul>';
altContainer.innerHTML = markup;
VirtualKeyboard.makeKeycap(this, altContainer.getElementsByTagName('li'), 'performAlternateKeys');
const keycapEl = this.virtualKeyboard.querySelector('div.keyboard-layer.is-visible div.rows ul li[data-alt-keys="' + keycap + '"]');
const position = keycapEl.getBoundingClientRect();
if (position) {
if (position.top - altContainer.clientHeight < 0) {
// altContainer.style.maxWidth = '320px'; // Up to six columns
altContainer.style.width = 'auto';
if (altKeys.length <= 6) {
altContainer.style.height = '56px'; // 1 row
} else if (altKeys.length <= 12) {
altContainer.style.height = '108px'; // 2 rows
} else {
altContainer.style.height = '205px'; // 3 rows
}
}
const top = (position.top - altContainer.clientHeight + 5).toString() + 'px';
const left = Math.max(0, Math.min(window.innerWidth - altContainer.offsetWidth, ((position.left + position.right - altContainer.offsetWidth) / 2))) + 'px';
altContainer.style.transform = 'translate(' + left + ',' + top + ')';
altContainer.classList.add('is-visible');
}
return false;
}
hideAlternateKeys_() {
const altContainer = document.getElementById('mathlive-alternate-keys-panel');
if (altContainer) {
altContainer.classList.remove('is-visible');
altContainer.innerHTML = '';
delete releaseSharedElement(altContainer);
}
return false;
}
/*
* The command invoked when an alternate key is pressed.
* We need to hide the Alternate Keys panel, then perform the
* command.
*/
performAlternateKeys_(command) {
this.hideAlternateKeys_();
return this.$perform(command);
}
switchKeyboardLayer_(layer) {
if (this.config.virtualKeyboardMode !== 'off') {
if (layer !== 'lower-command' && layer !== 'upper-command' && layer !== 'symbols-command') {
// If we switch to a non-command keyboard layer, first exit command mode.
this.complete_();
}
this.showVirtualKeyboard_();
// If the alternate keys panel was visible, hide it
this.hideAlternateKeys_();
// If we were in a temporarily shifted state (shift-key held down)
// restore our state before switching to a new layer.
this.unshiftKeyboardLayer_();
const layers = this.virtualKeyboard.getElementsByClassName('keyboard-layer');
// Search for the requested layer
let found = false;
for (let i = 0; i < layers.length; i++) {
if (layers[i].id === layer) {
found = true;
break;
}
}
// We did find the layer, switch to it.
// If we didn't find it, do nothing and keep the current layer
if (found) {
for (let i = 0; i < layers.length; i++) {
if (layers[i].id === layer) {
layers[i].classList.add('is-visible');
} else {
layers[i].classList.remove('is-visible');
}
}
}
this.$focus();
}
return true;
}
/*
* Temporarily change the labels and the command of the keys
* (for example when a modifier key is held down.)
*/
shiftKeyboardLayer_() {
const keycaps = this.virtualKeyboard.querySelectorAll('div.keyboard-layer.is-visible .rows .keycap, div.keyboard-layer.is-visible .rows .action');
if (keycaps) {
for (let i = 0; i < keycaps.length; i++) {
const keycap = keycaps[i];
let shiftedContent = keycap.getAttribute('data-shifted');
if (shiftedContent || /^[a-z]$/.test(keycap.innerHTML)) {
keycap.setAttribute('data-unshifted-content', keycap.innerHTML);
if (!shiftedContent) {
shiftedContent = keycap.innerHTML.toUpperCase();
}
keycap.innerHTML = shiftedContent;
const command = keycap.getAttribute('data-' + this.config.namespace + 'command');
if (command) {
keycap.setAttribute('data-unshifted-command', command);
const shiftedCommand = keycap.getAttribute('data-shifted-command');
if (shiftedCommand) {
keycap.setAttribute('data-' + this.config.namespace + 'command', shiftedCommand);
} else {
const commandObj = JSON.parse(command);
if (Array.isArray(commandObj)) {
commandObj[1] = commandObj[1].toUpperCase();
}
keycap.setAttribute('data-' + this.config.namespace + 'command', JSON.stringify(commandObj));
}
}
}
}
}
return false;
}
/*
* Restore the key labels and commands to the state before a modifier key
* was pressed.
*
*/
unshiftKeyboardLayer_() {
const keycaps = this.virtualKeyboard.querySelectorAll('div.keyboard-layer.is-visible .rows .keycap, div.keyboard-layer.is-visible .rows .action');
if (keycaps) {
for (let i = 0; i < keycaps.length; i++) {
const keycap = keycaps[i];
const content = keycap.getAttribute('data-unshifted-content');
if (content) {
keycap.innerHTML = content;
}
const command = keycap.getAttribute('data-unshifted-command');
if (command) {
keycap.setAttribute('data-' + this.config.namespace + 'command', command);
}
}
}
return false;
}
insertAndUnshiftKeyboardLayer_(c) {
this.$insert(c);
this.unshiftKeyboardLayer_();
return true;
}
/* Toggle the virtual keyboard, but switch to the alternate theme if available */
toggleVirtualKeyboardAlt_() {
let hadAltTheme = false;
if (this.virtualKeyboard) {
hadAltTheme = this.virtualKeyboard.classList.contains('material');
this.virtualKeyboard.remove();
delete this.virtualKeyboard;
this.virtualKeyboard = null;
}
this.showVirtualKeyboard_(hadAltTheme ? '' : 'material');
return false;
}
/* Toggle the virtual keyboard, but switch another keyboard layout */
toggleVirtualKeyboardShift_() {
this.config.virtualKeyboardLayout = {
'qwerty': 'azerty',
'azerty': 'qwertz',
'qwertz': 'dvorak',
'dvorak': 'colemak',
'colemak': 'qwerty'
}[this.config.virtualKeyboardLayout];
let layer = this.virtualKeyboard ?
this.virtualKeyboard.querySelector('div.keyboard-layer.is-visible') : null;
layer = layer ? layer.id : '';
if (this.virtualKeyboard) {
this.virtualKeyboard.remove();
delete this.virtualKeyboard;
this.virtualKeyboard = null;
}
this.showVirtualKeyboard_();
if (layer) { this.switchKeyboardLayer_(layer); }
return false;
}
showVirtualKeyboard_(theme) {
this.virtualKeyboardVisible = false;
this.toggleVirtualKeyboard_(theme);
return false;
}
hideVirtualKeyboard_() {
this.virtualKeyboardVisible = true;
this.toggleVirtualKeyboard_();
return false;
}
toggleVirtualKeyboard_(theme) {
this.virtualKeyboardVisible = !this.virtualKeyboardVisible;
if (this.virtualKeyboardVisible) {
if (this.virtualKeyboard) {
this.virtualKeyboard.classList.add('is-visible');
} else {
// Construct the virtual keyboard
this.virtualKeyboard = VirtualKeyboard.make(this, theme);
// Let's make sure that tapping on the keyboard focuses the field
on(this.virtualKeyboard, 'touchstart:passive mousedown', function () {
that.$focus();
});
document.body.appendChild(this.virtualKeyboard);
}
// For the transition effect to work, the property has to be changed
// after the insertion in the DOM. Use setTimeout
const that = this;
window.setTimeout(function () { that.virtualKeyboard.classList.add('is-visible'); }, 1);
} else if (this.virtualKeyboard) {
this.virtualKeyboard.classList.remove('is-visible');
}
if (typeof this.config.onVirtualKeyboardToggle === 'function') {
this.config.onVirtualKeyboardToggle(this, this.virtualKeyboardVisible, this.virtualKeyboard);
}
return false;
}
/**
* Apply a style (color, bold, italic, etc...).
*
* If there is a selection, the style is applied to the selection
*
* If the selection already has this style, remove it. If the selection
* has the style partially applied (i.e. only some sections), remove it from
* those sections, and apply it to the entire selection.
*
* If there is no selection, the style will apply to the next character typed.
*
* @param {object} style an object with the following properties. All the
* properties are optional, but they can be combined.
*
* @param {string} [style.mode=''] - Either `'math'`, `'text'` or '`command`'
* @param {string} [style.color=''] - The text/fill color, as a CSS RGB value or
* a string for some 'well-known' colors, e.g. 'red', '#f00', etc...
*
* @param {string} [style.backgroundColor=''] - The background color.
*
* @param {string} [style.fontFamily=''] - The font family used to render text.
* This value can the name of a locally available font, or a CSS font stack, e.g.
* "Avenir", "Georgia, serif", etc...
* This can also be one of the following TeX-specific values:
* - 'cmr': Computer Modern Roman, serif
* - 'cmss': Computer Modern Sans-serif, latin characters only
* - 'cmtt': Typewriter, slab, latin characters only
* - 'cal': Calligraphic style, uppercase latin letters and digits only
* - 'frak': Fraktur, gothic, uppercase, lowercase and digits
* - 'bb': Blackboard bold, uppercase only
* - 'scr': Script style, uppercase only
*
* @param {string} [style.series=''] - The font 'series', i.e. weight and
* stretch. The following values can be combined, for example: "ebc": extra-bold,
* condensed. Aside from 'b', these attributes may not have visible effect if the
* font family does not support this attribute:
* - 'ul' ultra-light weight
* - 'el': extra-light
* - 'l': light
* - 'sl': semi-light
* - 'm': medium (default)
* - 'sb': semi-bold
* - 'b': bold
* - 'eb': extra-bold
* - 'ub': ultra-bold
* - 'uc': ultra-condensed
* - 'ec': extra-condensed
* - 'c': condensed
* - 'sc': semi-condensed
* - 'n': normal (default)
* - 'sx': semi-expanded
* - 'x': expanded
* - 'ex': extra-expanded
* - 'ux': ultra-expanded
*
* @param {string} [style.shape=''] - The font 'shape', i.e. italic.
* - 'auto': italic or upright, depending on mode and letter (single letters are
* italic in math mode)
* - 'up': upright
* - 'it': italic
* - 'sl': slanted or oblique (often the same as italic)
* - 'sc': small caps
* - 'ol': outline
*
* @param {string} [style.size=''] - The font size: 'size1'...'size10'
* 'size5' is the default size
* @method MathField#$applyStyle
* */
$applyStyle(style) {
this._resetKeystrokeBuffer();
style = validateStyle(style);
if (style.mode) {
// There's a mode ('text', 'math', 'command') change
if (this.mathlist.isCollapsed()) {
// Nothing selected
this.switchMode_(style.mode);
} else {
// Convert the selection from one mode to another
const previousMode = this.mode;
const targetMode = (this.mathlist.anchorMode() || this.config.default) === 'math' ?
'text' : 'math';
let convertedSelection = this.$selectedText('ASCIIMath');
if (targetMode === 'math' && /^"[^"]+"$/.test(convertedSelection)) {
convertedSelection = convertedSelection.slice(1, -1);
}
this.$insert(convertedSelection, {
mode: targetMode,
selectionMode: 'item',
format: targetMode === 'text' ? 'text' : 'ASCIIMath'
});
this.mode = targetMode;
if (this.groupIsSelected()) {
// The entire group was selected. Adjust parent mode if
// appropriate
const parent = this.mathlist.parent();
if (parent && (parent.type === 'group' || parent.type === 'root')) {
parent.mode = targetMode;
}
}
// Notify of mode change
if (this.mode !== previousMode && typeof this.config.onModeChange === 'function') {
this.config.onModeChange(this, this.mode);
}
}
delete style.mode;
}
if (this.mathlist.isCollapsed()) {
// No selection, let's update the 'current' style
if (this.style.fontSeries && style.fontSeries === this.style.fontSeries) {
style.fontSeries = 'auto';
}
if (style.fontShape && style.fontShape === this.style.fontShape) {
style.fontShape = 'auto';
}
if (style.color && style.color === this.style.color) {
style.color = 'none';
}
if (style.backgroundColor && style.backgroundColor === this.style.backgroundColor) {
style.backgroundColor = 'none';
}
if (style.fontSize && style.fontSize === this.style.fontSize) {
style.fontSize = 'auto';
}
this.style = { ...this.style, ...style };
// This style will be used the next time an atom is inserted
} else {
// Change the style of the selection
this.mathlist._applyStyle(style);
this.undoManager.snapshot(this.config);
}
return true;
}
$hasFocus() {
return document.hasFocus() && document.activeElement === this.textarea;
}
$focus() {
if (!this.$hasFocus()) {
// The textarea may be a span (on mobile, for example), so check that
// it has a focus() before calling it.
if (this.textarea.focus) { this.textarea.focus(); }
this._announce('line');
}
}
$blur() {
if (this.$hasFocus()) {
if (this.textarea.blur) {
this.textarea.blur();
}
}
}
$select() {
this.mathlist.selectAll_();
}
$clearSelection() {
this.mathlist.delete_();
}
/**
* @param {string} keys - A string representation of a key combination.
*
* For example `'Alt-KeyU'`.
*
* See [W3C UIEvents](https://www.w3.org/TR/uievents/#code-virtual-keyboards)
* @param {Event} evt
* @return {boolean}
* @method MathField#$keystroke
*/
$keystroke(keys, evt) {
// This is the public API, while onKeystroke is the
// internal handler
return this._onKeystroke(keys, evt);
}
/**
* Simulate a user typing the keys indicated by text.
* @param {string} text - A sequence of one or more characters.
* @method MathField#$typedText
*/
$typedText(text) {
// This is the public API, while onTypedText is the
// internal handler
this._onTypedText(text);
}
/**
*
* @param {string} text
* @param {Object.<string, any>} [options={}]
* @param {boolean} options.focus - If true, the mathfield will be focused
* @param {boolean} options.feedback - If true, provide audio and haptic feedback
* @param {boolean} options.simulateKeystroke - If true, generate some synthetic
* keystrokes (useful to trigger inline shortcuts, for example)
* @private
*/
typedText_(text, options) {
return this._onTypedText(text, options);
}
/**
*
* Update the configuration options for this mathfield.
*
* @param {MathFieldConfig} [config={}] See {@tutorial CONFIG} for details.
*
* @method MathField#$setConfig
*/
$setConfig(conf) {
if (!this.config) {
this.config = {
smartFence: true,
smartSuperscript: true,
scriptDepth: [Infinity, Infinity],
removeExtraneousParentheses: true,
overrideDefaultInlineShortcuts: false,
virtualKeyboard: '',
virtualKeyboardLayout: 'qwerty',
namespace: '',
};
}
this.config = { ...this.config, ...conf };
if (this.config.scriptDepth !== undefined && !Array.isArray(this.config.scriptDepth)) {
const depth = parseInt(this.config.scriptDepth);
this.config.scriptDepth = [depth, depth];
}
if (typeof this.config.removeExtraneousParentheses === 'undefined') {
this.config.removeExtraneousParentheses = true;
}
this.config.onAnnounce = conf.onAnnounce || _onAnnounce;
this.config.macros = Object.assign({}, Definitions.MACROS, this.config.macros);
// Validate the namespace (used for `data-` attributes)
if (!/^[a-z]*[-]?$/.test(this.config.namespace)) {
throw Error('options.namespace must be a string of lowercase characters only');
}
if (!/-$/.test(this.config.namespace)) {
this.config.namespace += '-';
}
// Localization strings override (or localizations for new locales)
l10n.locale = this.config.locale || l10n.locale;
l10n.merge(this.config.strings);
this.config.virtualKeyboardLayout = conf.virtualKeyboardLayout || {
'fr': 'azerty',
'be': 'azerty',
'al': 'qwertz',
'ba': 'qwertz',
'cz': 'qwertz',
'de': 'qwertz',
'hu': 'qwertz',
'sk': 'qwertz',
'ch': 'qwertz',
}[l10n.locale.substring(0, 2)] || 'qwerty';
// Possible keypress sound feedback
this.keypressSound = undefined;
this.spacebarKeypressSound = undefined;
this.returnKeypressSound = undefined;
this.deleteKeypressSound = undefined;
if (this.config.keypressSound) {
if (typeof this.config.keypressSound === 'string') {
this.keypressSound = new Audio();
this.keypressSound.preload = 'none';
this.keypressSound.src = this.config.keypressSound;
this.keypressSound.volume = AUDIO_FEEDBACK_VOLUME;
this.spacebarKeypressSound = this.keypressSound;
this.returnKeypressSound = this.keypressSound;
this.deleteKeypressSound = this.keypressSound;
} else {
console.assert(this.config.keypressSound.default);
this.keypressSound = new Audio();
this.keypressSound.preload = 'none';
this.keypressSound.src = this.config.keypressSound.default;
this.keypressSound.volume = AUDIO_FEEDBACK_VOLUME;
this.spacebarKeypressSound = this.keypressSound;
this.returnKeypressSound = this.keypressSound;
this.deleteKeypressSound = this.keypressSound;
if (this.config.keypressSound.spacebar) {
this.spacebarKeypressSound = new Audio();
this.spacebarKeypressSound.preload = 'none';
this.spacebarKeypressSound.src = this.config.keypressSound.spacebar;
this.spacebarKeypressSound.volume = AUDIO_FEEDBACK_VOLUME;
}
if (this.config.keypressSound.return) {
this.returnKeypressSound = new Audio();
this.returnKeypressSound.preload = 'none';
this.returnKeypressSound.src = this.config.keypressSound.return;
this.returnKeypressSound.volume = AUDIO_FEEDBACK_VOLUME;
}
if (this.config.keypressSound.delete) {
this.deleteKeypressSound = new Audio();
this.deleteKeypressSound.preload = 'none';
this.deleteKeypressSound.src = this.config.keypressSound.delete;
this.deleteKeypressSound.volume = AUDIO_FEEDBACK_VOLUME;
}
}
}
if (this.config.plonkSound) {
this.plonkSound = new Audio();
this.plonkSound.preload = 'none';
this.plonkSound.src = this.config.plonkSound;
this.plonkSound.volume = AUDIO_FEEDBACK_VOLUME;
}
}
/**
*
* Speak some part of the expression, either with or without synchronized highlighting.
*
* @param {string} amount (all, selection, left, right, group, parent)
* @param {object} speakOptions
* @param {boolean} speakOptions.withHighlighting - If true, synchronized highlighting of speech will happen (if possible). Default is false.
*
* @method MathField#speak_
*/
speak_(amount, speakOptions) {
speakOptions = speakOptions || { withHighlighting: false };
function getAtoms(mathField, amount) {
let result = null;
switch (amount) {
case 'all':
result = mathField.mathlist.root;
break;
case 'selection':
if (!mathField.mathlist.isCollapsed()) {
result = mathField.mathlist.getSelectedAtoms();
}
break;
case 'left': {
const siblings = mathField.mathlist.siblings();
const last = mathField.mathlist.startOffset();
if (last >= 1) {
result = [];
for (let i = 1; i <= last; i++) {
result.push(siblings[i]);
}
}
break;
}
case 'right': {
const siblings = mathField.mathlist.siblings();
const first = mathField.mathlist.endOffset() + 1;
if (first <= siblings.length - 1) {
result = [];
for (let i = first; i <= siblings.length - 1; i++) {
result.push(siblings[i]);
}
}
break;
}
case 'start':
case 'end':
// not yet implemented
break;
case 'group':
result = mathField.mathlist.siblings();
break;
case 'parent': {
const parent = mathField.mathlist.parent();
if (parent && parent.type !== 'root') {
result = mathField.mathlist.parent();
}
break;
}
default:
console.log('unknown atom type "' + mathField.type + '"');
break;
}
return result;
}
function getFailedSpeech(amount) {
let result = '';
switch (amount) {
case 'all':
console.log("Internal failure: speak all failed");
break;
case 'selection':
result = 'no selection';
break;
case 'left':
result = 'at start';
break;
case 'right':
result = 'at end';
break;
case 'group':
console.log("Internal failure: speak group failed");
break;
case 'parent':
result = 'no parent';
break;
default:
console.log('unknown speak_ param value: "' + amount + '"');
break;
}
return result;
}
const atoms = getAtoms(this, amount);
if (atoms === null) {
this.config.handleSpeak(getFailedSpeech(amount));
return false;
}
const options = { ...this.config };
if (speakOptions.withHighlighting || options.speechEngine === 'amazon') {
options.textToSpeechMarkup = (window.sre && options.textToSpeechRules === 'sre') ? 'ssml_step' : 'ssml';
if (speakOptions.withHighlighting) {
options.generateID = true;
}
}
const text = MathAtom.toSpeakableText(atoms, options);
if (speakOptions.withHighlighting) {
window.mathlive.readAloudMathField = this;
this._render({ forHighlighting: true });
if (this.config.handleReadAloud) {
this.config.handleReadAloud(this.field, text, this.config);
}
} else {
if (this.config.handleSpeak) {
this.config.handleSpeak(text, options);
}
}
return false;
}
} |
JavaScript | class Phrase {
constructor(phrases, lang) {
this.phrases = phrases
this.lang = lang
this.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
this.SpeechGrammarList = window.SpeechGrammarList || window.webkitSpeechGrammarList
this.SpeechRecognitionEvent = window.SpeechRecognitionEvent || window.webkitSpeechRecognitionEvent
}
testSpeech() {
const prasesSplitted = this.phrases.join(' | ')
const grammar = `#JSGF V1.0; grammar phrase; public <phrase> = ${prasesSplitted};`
const recognition = new this.SpeechRecognition()
const speechRecognitionList = new this.SpeechGrammarList()
speechRecognitionList.addFromString(grammar, 1)
recognition.grammars = speechRecognitionList
recognition.lang = this.lang
recognition.interimResults = false
recognition.maxAlternatives = 1
recognition.start()
this.recognition = recognition
}
onResult(evt) {
/* The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
It has a getter so it can be accessed like an array
The first [0] returns the SpeechRecognitionResult at position 0.
Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects that contain individual results.
These also have getters so they can be accessed like arrays.
The second [0] returns the SpeechRecognitionAlternative at position 0.
We then return the transcript property of the SpeechRecognitionAlternative object */
return new Promise((resolve, reject) => {
const speechResult = evt.results[0][0].transcript
console.log(`Speechs received: ${speechResult}.`)
if (this.phrases.indexOf(speechResult.toLowerCase()) > -1) {
resolve(speechResult)
} else {
reject(new Error(`That didn't sound right. --> "${speechResult}"`))
}
console.info(`Confidence: ${evt.results[0][0].confidence}`)
})
}
onSpeechEnd() {
this.recognition.stop()
console.log('END: Start new test...')
return true
}
onError(evt) {
console.log('ERROR: Start new test...')
console.error(`Error occurred in recognition: ${evt.error}`)
return true
}
} |
JavaScript | class PagedAction extends BaseAction {
/**
* Constructor.
*
* @param {String} method
* @param {Object} params
* @param {Executor} executor
* @param {*} DestinationType
* @param {Boolean} returnsArray
*/
constructor(method, params, executor, DestinationType, returnsArray) {
super(method, params, executor, DestinationType, returnsArray);
this.changeParam('start', 0);
this.changeParam('max', 100);
}
withStart(start) {
this.start = start;
return this;
}
set start(start) {
this.changeParam('start', start);
return this;
}
withMax(max) {
this.max = max;
return this;
}
set max(max) {
this.changeParam('max', max);
return this;
}
/**
* Executes the current action and returns all results.
*
* @returns {Promise}
*/
async executeAll(restEach = -1, restSeconds = -1, restCallback = null, report = null) {
let all = [];
let transformCallback = null;
await this.executeAllReport(([data, transform]) => {
if (transformCallback === null) {
transformCallback = transform;
}
data.forEach(item => all.push(item));
if (report !== null) {
report(all.length);
}
}, restEach, restSeconds, restCallback);
return [all, transformCallback];
}
/**
* Executes the current action and reports the results of each step to the
* given reporter.
*
* @returns {Promise}
*/
async executeAllReport(reporter, restEach = -1, restSeconds = -1, restCallback = null) {
let result = [];
var reports = 0;
do {
if (restEach > -1 && reports > 0 && reports % restEach === 0) {
if (restCallback !== null) {
restCallback();
}
await (async () => {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, restSeconds * 1000);
});
})();
}
result = await this.execute();
if (result[0].length > 0) {
let c = reporter(result);
// being able to stop execution
if (c === false) {
return;
}
reports++;
}
this.changeParam('start', this.params.start + this.params.max);
} while (result[0].length > 0 && result[0].length === this.params.max);
}
/**
* Gets a flag indicating whether the current action is valid.
*
* @returns {boolean}
*/
isValid() {
return true;
}
} |
JavaScript | class GraphObject {
constructor({ options = {}, dataObject, filterManager = {}, graphType = {}, dataGrouper = {} }) {
this.options = options;
this.graphType = graphType
let { filterList = [], taggedFilters = {}, activatedFilters = [] } = filterManager;
this.filterManager = new FilterManager({ inputDataObject: dataObject, filterList, taggedFilters, activatedFilters });
this.graphDataObject = this.filterManager.reApplyAllFilters();
let { groupingType, targetColumn, yAxis } = dataGrouper;
this.dataGrouper = new DataGrouper({ dataObject: this.graphDataObject, groupingType, targetColumn, yAxis });
}
getConstructingArguments() {
return {
options: this.options,
graphType: this.graphType,
dataGrouper: {
groupingType: this.dataGrouper.groupingType,
targetColumn: this.dataGrouper.targetColumn,
yAxis: {
dataAction: {
actionType: this.dataGrouper.yAxis.actionType,
targetColumn: this.dataGrouper.yAxis.targetColumn,
},
label: this.dataGrouper.yAxis.label,
color: this.dataGrouper.yAxis.color,
}
}
}
}
getChart() {
return {
type: this.graphType,
data: this.dataGrouper.getData(),
options: this.options
}
}
} |
JavaScript | class RequestLogService {
/**
* @description Fetch all request logs
* @param {object} query Request log query
* @return {Promise<{success: boolean, error: *}|{success: boolean, data: *}>}
*/
async getAll (query) {
try {
// create paginated result
const paginate = await RequestLog.paginate({}, paginateQueries('request_logs', query))
return response.sendSuccess(paginate)
} catch (error) {
return response.sendError(error)
}
}
/**
* @description Fetch one request log by id
* @param {string} id Request log id
* @return {Promise<{success: boolean, error: *}|{success: boolean, data: *}>}
*/
async getById (id) {
try {
const requestLog = await RequestLog.findById(id)
if (!requestLog) return response.sendError(createError.NotFound('Request log not found'))
return response.sendSuccess(requestLog)
} catch (error) {
return response.sendError(error)
}
}
} |
JavaScript | class InjectHtml {
constructor() {
/**
* Serves the injected style and script imports.
*/
this.serveAssetsMiddleware = express_1.static(__dirname + "/../../client");
/**
* Monkey-patches `res.send` in order to inject style and script imports.
*/
this.injectAssetsMiddleware = (req, res, next) => {
const send = res.send;
res.send = html => {
html = this.insertImportTags(html);
return send.call(res, html);
};
next();
};
this.insertImportTags = (html) => {
html = String(html);
if (!html.includes("VERDACCIO_API_URL")) {
return html;
}
return html
.replace(/<\/head>/, headWithStyle)
.replace(/<\/body>/, bodyWithScript);
};
}
} |
JavaScript | class MetadataManager {
/**
* Namespace of the model
*
* @type {string|undefined}
*/
get namespace () {
return this[_namespace];
}
/**
* Validation schema of the model
*
* @type {Schema|undefined}
*/
get schema () {
if (isFunction(this[_schema])) {
this[_schema] = this[_schema]();
}
if (isObject(this[_schema])) {
if (!(this[_schema] instanceof Schema)) {
this[_schema] = new Schema(this[_schema]);
}
} else {
this[_schema] = new Schema();
}
return this[_schema];
}
/**
* Full name of the model (including namespace)
*
* @type {string}
*/
get name () {
return compact([this.namespace, this[_model].name]).join('/');
}
/**
* Handled model
*
* @type {Model}
*/
get model () {
return this[_model];
}
/**
* @param {Model} model The handled model
* @param {Schema} [schema] The validation schema
* @param {string} [namespace] The model's namespace
*
*/
constructor(model, schema, namespace) {
this[_model] = model;
this[_schema] = schema;
this[_namespace] = namespace;
instances[this.name] = this;
}
/**
* Register a model
*
* @param {Model} model The handled model
* @param {Schema} [schema] The validation schema
* @param {string} [namespace] The model's namespace
*
* @return {MetadataManager} The model's metadata manager
*/
static register(model, schema, namespace) {
model[_metadata] = new MetadataManager(model, schema, namespace);
return model[_metadata];
}
/**
* Retreive the metadata of a model
*
* @param {Model|Proxy} model The managed model or its proxy
*
* @return {MetadataManager|undefined} The metadata manager if exists
*/
static getMetadata (model) {
let metadata;
if (isString(model)) {
metadata = instances[model];
} else if (isFunction(model) || isObject(model)) {
if (model instanceof ModelInterface) {
model = model.constructor;
}
if (model.prototype instanceof ModelInterface) {
if (!model[_metadata] || (model[_metadata] === Object.getPrototypeOf(model)[_metadata])) {
MetadataManager.register(model);
}
metadata = model[_metadata];
}
}
return metadata;
}
} |
JavaScript | class ImportGenBankModal extends Component {
static propTypes = {
projectOpen: PropTypes.func.isRequired,
currentProjectId: PropTypes.string.isRequired,
open: PropTypes.bool.isRequired,
uiShowGenBankImport: PropTypes.func.isRequired,
uiSpin: PropTypes.func.isRequired,
projectLoad: PropTypes.func.isRequired,
projectSave: PropTypes.func.isRequired,
};
constructor() {
super();
this.state = {
files: [],
error: null,
processing: false,
destination: 'new project', // or 'current project'
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.open && !this.props.open) {
this.setState({
files: [],
error: null,
});
}
}
onDrop = (files) => {
this.setState({ files });
};
onSubmit = (evt) => {
evt.preventDefault();
this.setState({
error: null,
});
if (this.state.files.length) {
this.setState({
processing: true,
});
this.props.uiSpin('Importing your file... Please wait');
const projectId = this.state.destination === 'current project' ? this.props.currentProjectId : '';
const file = this.state.files[0];
const isCSV = file.name.toLowerCase().endsWith('.csv');
const importer = isCSV ? importCsvFile : importGenbankFile;
//if saving into current project, save the current project first (and force the save) so its on the server
const savePromise = projectId ?
this.props.projectSave(this.props.currentProjectId, true) :
Promise.resolve();
savePromise
.then(() => importer(projectId, file))
.then((projectId) => {
this.props.uiSpin();
if (projectId === this.props.currentProjectId) {
//true to forcibly reload the project, avoid our cache
this.props.projectLoad(projectId, true);
} else {
this.props.projectOpen(projectId);
}
this.setState({
processing: false,
});
this.props.uiShowGenBankImport(false);
})
.catch((error) => {
this.props.uiSpin();
this.setState({
error: `Error uploading file: ${error}`,
processing: false,
});
});
}
};
showFiles() {
const files = this.state.files.map((file, index) => <div className="file-name" key={index}>{file.name}</div>);
return files;
}
render() {
if (!this.props.open) {
return null;
}
return (
<div>
<ModalWindow
open
title="Import GenBank File"
payload={(
<form
disabled={this.state.processing}
onSubmit={this.onSubmit}
id="genbank-import-form"
className="gd-form genbank-import-form"
>
<div className="title">Import</div>
<div className="radio">
<div>Import data to:</div>
<input
checked={this.state.destination === 'new project'}
type="radio"
name="destination"
disabled={this.state.processing}
onChange={() => this.setState({ destination: 'new project' })}
/>
<div>New Project</div>
</div>
<div className="radio">
<div />
<input
checked={this.state.destination === 'current project'}
type="radio"
name="destination"
disabled={this.state.processing}
onChange={() => this.setState({ destination: 'current project' })}
/>
<div>Current Project</div>
</div>
<Dropzone
onDrop={this.onDrop}
className="dropzone"
activeClassName="dropzone-hot"
multiple={false}
>
<div className="dropzone-text">Drop File Here</div>
</Dropzone>
{this.showFiles()}
{this.state.error ? <div className="error visible">{this.state.error}</div> : null}
<button type="submit" disabled={this.state.processing}>Upload</button>
<button
type="button"
disabled={this.state.processing}
onClick={() => {
this.props.uiShowGenBankImport(false);
}}
>Cancel
</button>
<div className="link">
<span>Format documentation and sample .CSV files can be found
<a
className="blue-link"
href="https://geneticconstructor.readme.io/docs/csv-upload"
target="_blank"
rel="noopener noreferrer"
>here</a>
</span>
</div>
</form>
)}
closeOnClickOutside
closeModal={(buttonText) => {
this.props.uiShowGenBankImport(false);
}}
/>
</div>
);
}
} |
JavaScript | class VfButtonCallback extends React.Component {
componentDidMount() {
// console.log("any JS actions needed");
}
render() {
return React.createElement(React.Fragment, null);
}
} |
JavaScript | class MersenneTwister {
constructor(seed) {
/* Period parameters */
this.N = 624;
this.M = 397;
this.MATRIX_A = 0x9908b0df; /* constant vector a */
this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
this.mt = new Array(this.N); /* the array for the state vector */
this.mti = this.N + 1; /* mti==N+1 means mt[N] is not initialized */
if (Array.isArray(seed)) {
if (seed.length > 0)
this.initByArray(seed, seed.length);
}
else {
if (seed === undefined) {
this.initSeed(new Date().getTime());
}
else {
this.initSeed(seed);
}
}
}
/* initializes mt[N] with a seed */
/* origin name init_genrand */
initSeed(seed) {
this.mt[0] = seed >>> 0;
for (this.mti = 1; this.mti < this.N; this.mti++) {
const s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
this.mt[this.mti] =
((((s & 0xffff0000) >>> 16) * 1812433253) << 16) +
(s & 0x0000ffff) * 1812433253 +
this.mti;
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
this.mt[this.mti] >>>= 0;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
initByArray(initKey, keyLength) {
this.initSeed(19650218);
let i = 1;
let j = 0;
let k = this.N > keyLength ? this.N : keyLength;
for (; k; k--) {
const s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^
(((((s & 0xffff0000) >>> 16) * 1664525) << 16) +
(s & 0x0000ffff) * 1664525)) +
initKey[j] +
j; /* non linear */
this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
i++;
j++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
if (j >= keyLength)
j = 0;
}
for (k = this.N - 1; k; k--) {
const s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^
(((((s & 0xffff0000) >>> 16) * 1566083941) << 16) +
(s & 0x0000ffff) * 1566083941)) -
i; /* non linear */
this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
i++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
}
this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
}
/* generates a random number on [0,0xffffffff]-interval */
/* origin name genrand_int32 */
randomInt32() {
let y;
const mag01 = [0x0, this.MATRIX_A];
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (this.mti >= this.N) {
/* generate N words at one time */
let kk;
if (this.mti === this.N + 1)
/* if init_seed() has not been called, */
this.initSeed(5489); /* a default initial seed is used */
for (kk = 0; kk < this.N - this.M; kk++) {
y =
(this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
}
for (; kk < this.N - 1; kk++) {
y =
(this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] =
this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
}
y =
(this.mt[this.N - 1] & this.UPPER_MASK) |
(this.mt[0] & this.LOWER_MASK);
this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1];
this.mti = 0;
}
y = this.mt[this.mti++];
/* Tempering */
y ^= y >>> 11;
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= y >>> 18;
return y >>> 0;
}
/* generates a random number on [0,0x7fffffff]-interval */
/* origin name genrand_int31 */
randomInt31() {
return this.randomInt32() >>> 1;
}
/* generates a random number on [0,1]-real-interval */
/* origin name genrand_real1 */
randomReal1() {
return this.randomInt32() * (1.0 / 4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
/* origin name genrand_real2 */
randomReal2() {
return this.randomInt32() * (1.0 / 4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
/* origin name genrand_real3 */
randomReal3() {
return (this.randomInt32() + 0.5) * (1.0 / 4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
/* origin name genrand_res53 */
randomRes53() {
const a = this.randomInt32() >>> 5;
const b = this.randomInt32() >>> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
} |
JavaScript | class ModalManager {
constructor({ hideSiblingNodes = true, handleContainerOverflow = true } = {}) {
this.hideSiblingNodes = hideSiblingNodes;
this.handleContainerOverflow = handleContainerOverflow;
this.modals = [];
this.containers = [];
this.data = [];
}
add = (modal, container, className) => {
let modalIdx = this.modals.indexOf(modal);
let containerIdx = this.containers.indexOf(container);
if (modalIdx !== -1) {
return modalIdx;
}
modalIdx = this.modals.length;
this.modals.push(modal);
if (this.hideSiblingNodes) {
hideSiblings(container, modal.mountNode);
}
if (containerIdx !== -1) {
this.data[containerIdx].modals.push(modal);
return modalIdx;
}
let data = {
modals: [ modal ],
//right now only the first modal of a container will have its classes applied
classes: className ? className.split(/\s+/) : [],
overflowing: isOverflowing(container)
};
if (this.handleContainerOverflow) {
setContainerStyle(data, container)
}
data.classes.forEach(
classes.addClass.bind(null, container));
this.containers.push(container);
this.data.push(data);
return modalIdx;
}
remove = (modal) => {
let modalIdx = this.modals.indexOf(modal);
if (modalIdx === -1) {
return;
}
let containerIdx = findContainer(this.data, modal);
let data = this.data[containerIdx];
let container = this.containers[containerIdx];
data.modals.splice(
data.modals.indexOf(modal), 1);
this.modals.splice(modalIdx, 1);
// if that was the last modal in a container,
// clean up the container
if (data.modals.length === 0){
data.classes.forEach(
classes.removeClass.bind(null, container));
if (this.handleContainerOverflow) {
removeContainerStyle(data, container)
}
if (this.hideSiblingNodes) {
showSiblings(container, modal.mountNode);
}
this.containers.splice(containerIdx, 1);
this.data.splice(containerIdx, 1);
}
else if (this.hideSiblingNodes) {
//otherwise make sure the next top modal is visible to a SR
ariaHidden(false, data.modals[data.modals.length - 1].mountNode);
}
}
isTopModal = (modal) => {
return !!this.modals.length
&& this.modals[this.modals.length - 1] === modal;
}
} |
JavaScript | class Node {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
// Generate linked list from array
static from(arr) {
let head = null;
let tail = null;
arr.forEach((v) => {
const node = new Node(v);
if (!head) head = node;
if (tail) tail.next = node;
tail = node;
});
return head;
}
} |
JavaScript | class CloudProvider {
constructor() {
this.regions = [];
this.catalog = null;
}
} |
JavaScript | class Hero2 extends Phaser.Sprite {
constructor(game, x, y) {
// call Phaser.Sprite constructor
super(game, x, y, 'hero');
// Phaser: configure hero animation
this.animations.add('stop', [0]);
this.animations.add('run', [1,2], 8, true);
this.animations.add('jump', [3]);
this.animations.add('fall', [4]);
// Phaser: make the hero pinned to a specific coord
this.anchor.set(0.5, 0.5);
// Phaser: enable physics for this sprite
this.game.physics.enable(this);
// Phaser: make the body stay inside the screen bounds
this.body.collideWorldBounds = true;
}
/*
* add more public/private methods to the class down here
*/
// public custom method. Given a direction (-1: left,
// 0: no direction, +1: right) update physics and image
move(direction) {
// Instead of acting directly on the position...
// this.x += direction * 2.5; // 2.5 pixels each frame
// ...affect the body (physics) of the sprite
const SPEED = 200;
this.body.velocity.x = direction * SPEED;
// flip the image (using +/-100% scale) depending on
// the movement direction, so that the hero faces the correct direction
if (direction != 0){
this.scale.x = direction;
}
}
// public custom method
jump() {
const JUMP_SPEED = 600;
let canJump = this.body.touching.down;
if (canJump) {
this.body.velocity.y = -JUMP_SPEED;
}
return canJump;
};
// public custom method
bounce() {
const BOUNCE_SPEED = 200;
this.body.velocity.y = -BOUNCE_SPEED;
};
freeze() {
this.body.enable = false;
this.isFrozen = true;
};
// public method to update anumation
update() {
let animationName = this._getAnimationName();
if (this.animations.name != animationName) {
this.animations.play(animationName);
}
}
// private method
_getAnimationName() {
let name = 'stop'; // default animation
// jumping
if (this.body.velocity.y < 0) {
name = 'jump';
}
// falling (i.e. falling after a jump)
else if (this.body.velocity.y >= 0 && !this.body.touching.down) {
name = 'fall';
}
// running
else if (this.body.velocity.x != 0 && this.body.touching.down) {
name = 'run';
}
return name;
}
} |
JavaScript | class FirebaseAdminPushAdapter {
constructor(pushConfig = {}) {
this.validPushTypes = ['ios', 'osx', 'tvos', 'android', 'fcm', 'web'];
const {
maxTokensPerRequest = defaultMaxTokensPerRequest, serviceAccountKey, databaseURL
} = pushConfig;
if (!serviceAccountKey || !databaseURL) {
throw new Error('Trying to initialize FirebaseAdminPushAdapter without serviceAccountKey / databaseURL');
}
this.maxTokensPerRequest = maxTokensPerRequest;
admin.initializeApp({
credential: admin.credential.cert(serviceAccountKey),
databaseURL: databaseURL
});
}
getValidPushTypes() {
return this.validPushTypes;
}
getValidTokens(installations) {
return this.getValidInstallations(installations).map(installation => installation.deviceToken);
}
getValidInstallations(installations) {
return installations.filter(
installation => ~this.validPushTypes.indexOf(installation.deviceType) && installation.deviceToken
).map(installation => installation);
}
send(data, installations) {
const validInstallations = this.getValidInstallations(installations);
const tokens = this.getValidTokens(validInstallations);
const chunks = [];
const chunkInstallations = [];
let i = 0;
while (i < tokens.length) {
let end = i + this.maxTokensPerRequest;
chunks.push(tokens.slice(i, end));
chunkInstallations.push(validInstallations.slice(i, end));
i = end;
}
let timestamp = Date.now();
let expirationTime;
// We handle the expiration_time convertion in push.js, so expiration_time is a valid date
// in Unix epoch time in milliseconds here
if (data['expiration_time']) {
expirationTime = data['expiration_time'];
}
// Generate FCM payload
let fcmPayload = this.generatePayload(data);
let fcmOptions = this.generateOptions(data, timestamp, expirationTime);
return chunks.reduce(
(pr, deviceTokens, idx) => pr.then(
() => this.sendToDevice(chunkInstallations[idx], deviceTokens, fcmPayload, fcmOptions)
), Promise.resolve()
);
}
/**
* Generate the fcm payload from the data we get from api request.
* @param {Object} requestData The request body
* @returns {Object} A promise which is resolved after we get results from fcm
*/
generatePayload(requestData) {
requestData = requestData.data || {};
const {
badge, alert, sound, title, body, uri, icon, color, topic, ...customData
} = requestData;
const notification = {};
if (typeof badge !== 'undefined' && badge !== null) {
if (badge === 'Increment') {
notification.badge = '+1';
} else {
notification.badge = badge.toString();
}
}
if (alert) {
notification.body = alert;
}
if (title) {
notification.title = title;
}
if (body) {
notification.body = body;
}
if (uri) {
notification.link = uri;
}
if (sound) {
notification.sound = sound;
}
if (icon) {
notification.icon = icon;
}
if (color) {
notification.color = color;
}
const payload = {
notification: notification
};
if (topic) {
payload.topic = topic;
}
if (Object.keys(customData).length > 0) {
payload.data = customData;
}
return payload;
}
/**
* Generate the fcm options from the data we get from api request.
* @param {Object} requestData The request body
* @param {Number} timestamp A number whose format is the Unix Epoch
* @param {Number|undefined} expirationTime A number whose format is the Unix Epoch or undefined
* @returns {Object} A promise which is resolved after we get results from fcm
*/
generateOptions(requestData, timestamp, expirationTime) {
requestData = requestData.data || {};
const {
'content-available': contentAvailable, 'mutable-content': mutableContent, collapseKey
} = requestData;
let options = {
priority: 'high'
};
if (contentAvailable == 1) {
options.contentAvailable = 1;
}
if (mutableContent == 1) {
options.mutableContent = 1;
}
if (collapseKey) {
options.collapseKey = collapseKey;
}
if (expirationTime) {
// The timestamp and expiration is in milliseconds but fcmd requires second
let timeToLive = Math.floor((expirationTime - timestamp) / 1000);
if (timeToLive < 0) {
timeToLive = 0;
}
if (timeToLive >= FCMTimeToLiveMax) {
timeToLive = FCMTimeToLiveMax;
}
options.timeToLive = timeToLive;
}
return options;
}
/**
* sendToDevice
* @param {Array} installations
* @param {Array} deviceTokens
* @param {Object} payload
* @param {Object} options
*
* @returns {Object} A promise
*/
async sendToDevice(installations, deviceTokens, payload, options) {
let length = deviceTokens.length;
log.verbose(LOG_PREFIX, `sending to ${length} ${length > 1 ? 'devices' : 'device'}`);
try {
const response = await admin.messaging().sendToDevice(deviceTokens, payload, options);
log.verbose(LOG_PREFIX, `GCM Response: %s`, JSON.stringify(response, null, 4));
const resolutions = [];
let {
results, multicastId, canonicalRegistrationTokenCount = 0, failureCount = 0, successCount = 0
} = response || {};
installations.forEach(installation => {
let idx = deviceTokens.indexOf(installation.deviceToken);
let result = results && results[idx] ? results[idx] : undefined;
let device = {
deviceToken: installation.deviceToken,
deviceType: installation.deviceType,
appIdentifier: installation.appIdentifier
};
let resolution = {
device,
multicastId,
canonicalRegistrationTokenCount,
failureCount,
successCount,
response: result
};
if (!result || result.error) {
resolution.transmitted = false;
} else {
resolution.transmitted = true;
}
resolutions.push(resolution);
});
return resolutions;
} catch (error) {
log.error(LOG_PREFIX, `send errored: % s`, JSON.stringify(error, null, 4));
throw error;
}
}
} |
JavaScript | class Store {
constructor(base, validation, config) {
this.base = base || "./data/";
this.validation = validation || {};
this.config = config;
}
/**
* errorHandler: handle the error response, and clean
* @param {Response} response
* @return {object}
*/
errorHandler(response) {
if (!response.ok) return {
error: !response.ok,
text: response.statusText,
url: response.url
};
return response.json();
}
filterBroken(data, type){
if (Array.isArray(data)){
if (this.validation[type.toLowerCase()]){
return data.filter(this.validation[type])
} else {
return data
}
} else { // unlikely case?
if (this.validation[type.toLowerCase()]){
if (this.validation[type](data)){
return data
}else{
return undefined
}
}
}
}
/**
* find marks matching slide and/or marktype
* will search by slide field as exactly given and by the oid slide of that name
* @param {string} [name] - the associated slide name
* @param {string} [slide] - the associated marktype name, supporting regex match
* @returns {promise} - promise which resolves with data
**/
findMark(slide, name, specimen, study, footprint, source, x0, x1, y0, y1) {
var suffix = "Mark/find"
var url = this.base + suffix;
var query = {}
var bySlideId
if (slide) {
query.slide = slide
}
if (name) {
query.name = name
}
if (specimen) {
query.specimen = specimen
}
if (study) {
query.study = study
}
if (footprint) {
query.footprint = footprint
}
if (source) {
query.source = source
}
if (x0){
query.x0 = x0;
}
if (x1){
query.x1 = x1;
}
if (y0){
query.y0 = y0;
}
if (y1){
query.y1 = y1;
}
let bySlide = fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "mark"))
if (!slide) {
return bySlide
} else {
bySlideId = this.findSlide(slide).then(x => {
if (x.length == 0) {
return []
} else {
query.slide = x[0]['_id']['$oid']
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "mark"))
}
})
// return as if we did one query by flattening these promises
return Promise.all([bySlide, bySlideId]).then(x => [].concat.apply([], x))
}
}
/**
* find marks which contain a given point
* NOTE: this works only by exact match
* @param {number} x0 - x min position of rect to search
* @param {number} y0 - y min position of rect to search
* @param {number} x1 - x max position of rect to search
* @param {number} y1 - y max position of rect to search
* @param {string} [name] - the associated slide name
* @param {string} [slide] - the associated marktype name, supporting regex match
* @returns {promise} - promise which resolves with data
**/
findMarkSpatial(x0, y0, x1, y1, name, slide, key) {
var suffix = "Mark/findBound"
var url = this.base + suffix;
var query = {}
query.x0 = x0
query.y0 = y0
query.x1 = x1
query.y1 = y1
if (name) {
query.name = name
}
if (slide) {
query.slide = slide
}
if (key) {
query.key = key
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "mark"))
}
getMarkByIds(ids, slide, study, specimen, source, footprint, x0, x1, y0, y1) {
if (!Array.isArray(ids) || !slide) {
return {
hasError: true,
message: 'args are illegal'
}
}
var bySlideId
var suffix = "Mark/multi"
var url = this.base + suffix;
var query = {}
var stringifiedIds = ids.map(id => `"${id}"`).join(',');
query.name = `[${stringifiedIds}]`;
query.slide = slide;
if (study){
query.study = study;
}
if (specimen){
query.specimen = specimen;
}
if (source){
query.source = source;
}
if (footprint){
query.footprint = footprint;
}
if (x0){
query.x0 = x0;
}
if (x1){
query.x1 = x1;
}
if (y0){
query.y0 = y0;
}
if (y1){
query.y1 = y1;
}
let bySlide = fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "mark"))
if (!slide) {
return bySlide
} else {
bySlideId = this.findSlide(slide).then(x => {
if (x.length == 0) {
return []
} else {
query.slide = x[0]['_id']['$oid']
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "mark"))
}
})
// return as if we did one query by flattening these promises
return Promise.all([bySlide, bySlideId]).then(x => [].concat.apply([], x))
}
}
/**
* get mark by id
* @param {string} id - the mark id
* @returns {promise} - promise which resolves with data
**/
getMark(id) {
var suffix = "Mark/get"
var url = this.base + suffix;
var query = {
'id': id
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "mark"))
}
/**
* post mark
* @param {object} json - the mark data
* @returns {promise} - promise which resolves with response
**/
addMark(json) {
var suffix = "Mark/post"
var url = this.base + suffix;
if (this.validation.mark && !this.validation.mark(json)){
console.warn(this.validation.mark.errors)
}
return fetch(url, {
method: "POST",
credentials: "include",
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify(json)
}).then(this.errorHandler)
}
/**
* delete mark
* @param {object} id - the mark object id
* @param {object} slide - the associated slide
* @returns {promise} - promise which resolves with response
**/
deleteMark(id, slide) {
var suffix = "Mark/delete"
var url = this.base + suffix;
var query = {
id: id,
slide: slide
}
return fetch(url + "?" + objToParamStr(query), {
method: "DELETE",
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
/**
* find marktypes given slide and name
* @param {string} [name] - the associated slide name
* @param {string} [slide] - the marktype name, supporting regex match
* @returns {promise} - promise which resolves with data
**/
findMarkTypes(slide, name) {
var suffix = "Mark/types"
var url = this.base + suffix;
var query = {}
var bySlideId
if (name) {
query.name = name
}
if (slide) {
query.slide = slide
}
let bySlide = fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
if (!slide) {
return bySlide
} else {
bySlideId = this.findSlide(slide).then(x => {
if (x.length == 0) {
return []
} else {
query.slide = x[0]['_id']['$oid']
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
})
// return as if we did one query by flattening these promises
return Promise.all([bySlide, bySlideId]).then(x => [].concat.apply([], x))
}
}
findHeatmap(slide, name) {
var suffix = "Heatmap/find"
var url = this.base + suffix;
var query = {}
var bySlideId
if (name) {
query.name = name
}
if (slide) {
query.slide = slide
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "heatmap"))
}
findHeatmapType(slide, name) {
var suffix = "Heatmap/types"
var url = this.base + suffix;
var query = {}
var bySlideId
if (name) {
query.name = name
}
if (slide) {
query.slide = slide
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "heatmap"))
}
/**
* get heatmap by id
* @param {string} id - the heatmap id
* @returns {promise} - promise which resolves with data
**/
getHeatmap(caseId, execId) {
var suffix = "Heatmap/get"
var url = this.base + suffix;
var query = {};
query.caseId = caseId;
query.execId = execId;
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "heatmap"))
}
/**
* post heatmap
* @param {object} json - the mark data
* @returns {promise} - promise which resolves with response
**/
addHeatmap(json) {
var suffix = "Heatmap/post"
var url = this.base + suffix;
if (this.validation.heatmap && !this.validation.heatmap(json)){
console.warn(this.validation.heatmap.errors)
}
return fetch(url, {
method: "POST",
credentials: "include",
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify(json)
}).then(this.errorHandler)
}
/**
* delete heatmap
* @param {object} id - the heatmap object id
* @param {object} slide - the associated slide
* @returns {promise} - promise which resolves with response
**/
deleteHeatmap(id, slide) {
var suffix = "Heatmap/delete"
var url = this.base + suffix;
var query = {
id: id,
slide: slide
}
return fetch(url + "?" + objToParamStr(query), {
method: "DELETE",
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
/**
* find overlays matching name and/or type
* @param {string} [name] - the overlay, supporting regex match
* @param {string} [slide] - the associated slide id
* @returns {promise} - promise which resolves with data
**/
findOverlay(name, slide) {
var suffix = "Overlay/find"
var url = this.base + suffix;
var query = {}
if (name) {
query.name = name
}
if (slide) {
query.slide = slide
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
/**
* get overlay by id
* @param {string} id - the overlay id
* @returns {promise} - promise which resolves with data
**/
getOverlay(id) {
var suffix = "Overlay/get"
var url = this.base + suffix;
var query = {
'id': id
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
/**
* find overlays matching name and/or type
* @param {string} [name] - the slide name
* @param {string} [location] - the slide location, supporting regex match
* @returns {promise} - promise which resolves with data
**/
findSlide(slide, specimen, study, location) {
var suffix = "Slide/find"
var url = this.base + suffix;
var query = {}
if (slide) {
query.slide = slide
}
if (location) {
query.location = location
}
if (specimen) {
query.specimen = specimen
}
if (study) {
query.study = study
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
/**
* get slide by id
* @param {string} id - the slide id
* @returns {promise} - promise which resolves with data
**/
getSlide(id) {
var suffix = "Slide/get"
var url = this.base + suffix;
var query = {
'id': id
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "slide"))
}
/**
* find templates matching name and/or type
* @param {string} [name] - the template name, supporting regex match
* @param {string} [type] - the template type, supporting regex match
* @returns {promise} - promise which resolves with data
**/
findTemplate(name, type) {
var suffix = "Template/find"
var url = this.base + suffix;
var query = {}
if (name) {
query.name = name
}
if (type) {
query.slide = slide
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "template"))
}
/**
* get template by id
* @param {string} id - the template id
* @returns {promise} - promise which resolves with data
**/
getTemplate(id) {
var suffix = "Template/get"
var url = this.base + suffix;
var query = {
'id': id
}
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler).then(x=>this.filterBroken(x, "template"))
}
/**
* post data
* @param {string} type - the datatype to post
* @param {object} data - the data to post
* @param {object} [query] - the query of url parameters
* @returns {promise} - promise which resolves with data
**/
post(type, query, data) {
var url = this.base + type + "/post";
return fetch(url + "?" + objToParamStr(query), {
method: "POST",
mode: "cors",
body: JSON.stringify(data),
credentials: "include",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(this.errorHandler)
}
/**
* update data
* @param {string} type - the datatype to get
* @param {object} query - the query of url parameters
* @param {object} data - the data to update
* @returns {promise} - promise which resolves with data
**/
update(type, query, data) {
var url = this.base + type + "/update";
return fetch(url + "?" + objToParamStr(query), {
method: "UPDATE",
mode: "cors",
body: JSON.stringify(data),
credentials: "include",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(this.errorHandler)
}
/**
* delete data
* @param {string} type - the datatype to get
* @param {object} query - the query of url parameters
* @returns {promise} - promise which resolves with data
**/
delete(type, query) {
var url = this.base + type + "/delete";
return fetch(url + "?" + objToParamStr(query), {
credentials: "include",
mode: "cors"
}).then(this.errorHandler)
}
} |
JavaScript | class LinkedList {
deleteNode( head, d ) {
let prev = null;
let current = head;
while (current) {
if (current.data === d) {
break;
}
prev = current;
current = current.next;
}
// key not found in list
if (!current) {
return head;
}
// if node to be deleted is head node
if (current === head) {
return head.next;
}
// for all other cases
prev.next = current.next;
return head;
}
deleteNode2(head, key) {
let current = head;
let prev = null;
while (current) {
if (current.data === key) {
if (current === head) {
head = head.next;
} else {
prev.next = current.next;
}
return head;
} else {
prev = current;
current = current.next;
}
}
return head;
}
print( node ) {
let current = node;
let str = ''
while( current ) {
str += current.data + " -> ";
current = current.next;
}
str += 'null';
console.log( str );
}
} |
JavaScript | class DockerSdk extends BaseEmulator {
constructor(options) {
super(options);
this._docker = new Docker();
this._container = null;
}
/**
* Start the emulator. If need pull the image
* @returns {Promise}
*/
start() {
const self = this;
return new Promise((resolve, reject) => {
if (this._state)
throw new Error('Datastore (Docker) emulator is already running.');
super._start(resolve, reject);
let cmd = ['gcloud'].concat(self._getCommandParameters());
const port = EMULATOR_PORT + '/tcp';
const bind = [];
// If data directory set then map the local directory to the container directory
if (self._options.dataDir) {
const abs = path.resolve(self._options.dataDir);
bind.push(abs + ':/.config/gcloud/emulators/datastore');
}
self._pullImage()
.then(() => {
return self._docker.createContainer({
Hostname: EMULATOR_HOST_NAME,
Image: self._options.dockerImage,
AttachStdin: false,
AttachStdout: true,
AttachStderr: true,
Tty: true,
Cmd: cmd,
OpenStdin: false,
StdinOnce: false,
ExposedPorts: {
[port]: {}
},
HostConfig: {
PortBindings: {
[port]: [
{
HostPort: self._options.port.toString()
}
]
},
Binds: bind
}
})
})
.then((container) => {
self._container = container;
// attach streams to the container
container.attach({ stream: true, stdout: true, stderr: true }, function (err, stream) {
/* istanbul ignore if */
if (err)
return reject(err);
// all stream data pass to the processor.
stream.on('data', (data) => {
const msg = data.toString();
self._writeDebug(msg);
self._processStd(msg);
});
});
return self._container.start();
})
.catch(reject)
})
}
/**
* Stop the container
* @returns {Promise}
*/
stop() {
if (this._state !== EmulatorStates.RUNNING || !this._container)
return Promise.resolve();
return new Promise((resolve, reject) => {
super._stop()
.then(resolve)
.catch(reject);
this._container.stop()
.then(() => {
this._setState(EmulatorStates.EXIT, 0);
})
.catch(reject);
})
}
/**
* Pull the docker image
* @returns {Object}
* @private
*/
_pullImage() {
const self = this;
return new Promise((resolve, reject) => {
self._docker.pull(self._options.dockerImage, function (err, stream) {
if(err)
return reject(err);
self._docker.modem.followProgress(stream, onFinished, onProgress);
function onFinished(err, output) {
self._writeDebug(output);
if (err) return reject(err);
return resolve();
}
function onProgress(event) {
self._writeDebug(event);
}
});
})
}
/**
* Set the host and port setting for emulator
* @param params
* @protected
*/
_setHostPort(params) {
params.push(`--host-port=${EMULATOR_HOST_NAME}:${EMULATOR_PORT}`);
}
/**
* Override the base class abstract method. Not redirect the default working directory when use Docker image
* @param params
* @protected
*/
_setDatadir(params) {
}
/**
* Override the base class method. Set the consistency level of the emulator
* @param params
* @protected
*/
_setConsistency(params) {
if (this._options.consistency) {
params.push(`--consistency=${this._options.consistency}`)
}
}
} |
JavaScript | class Equipment extends Item {
constructor(info) {
super(info);
this.maxHp = _.get(info, 'maxHp', 0);
this.force = _.get(info, 'force', 0);
this.technique = _.get(info, 'technique', 0);
this.crit = _.get(info, 'crit', 0);
this.defence = _.get(info, 'defence', 0);
this.dodge = _.get(info, 'dodge', 0);
this.level = _.get(info, 'level', 1);
this.properties = _.get(info, 'properties', []);
}
/**
* Get the fields to display when this item is examined.
*
* @param {Character} character - The character examining this item.
*
* @return {array}
*/
getExamineFields(character) {
let fields = super.getExamineFields(character);
if (this.minDamage) {
fields.add("Damage", `${this.minDamage}-${this.maxDamage}`, true);
}
if (this.force) {
fields.add( Text.getLongAttributeName('force'), this.force, true);
}
if (this.technique) {
fields.add( Text.getLongAttributeName('technique'), this.technique, true);
}
if (this.crit) {
fields.add( Text.getLongAttributeName('crit'), this.crit, true);
}
if (this.defence) {
fields.add( Text.getLongAttributeName('defence'), this.defence, true);
}
if (this.dodge) {
fields.add( Text.getLongAttributeName('dodge'), this.dodge, true);
}
if (this.properties.length) {
let properties = this.properties.map((property) => Text.getPropertyName(property, character));
fields.add("Properties", ` ${properties.join(", ")}`, true);
}
return fields;
}
/**
* Get the text to display for buying a new item of this type.
*
* @param {Character} character - The character looking at buying this item.
* @param {string} oldItem - The item being replaced.
* @param {string} newItem - The new item.
* @param {string} choice - Whether to keep or sell the old item.
*/
getBuyText(character, oldItem, newItem, choice) {
const newName = newItem.getDisplayName(character);
const oldName = oldItem.getDisplayName(character);
if (choice === 'keep') {
return `You buy and equip a brand-new ${newName}, tucking your ${oldName} away for later.`;
}
else {
const sellPrice = oldItem.getSellPriceDescription(character);
return `You sell your old ${oldName} for ${sellPrice}, and equip a brand-new ${newName} in its place.`;
}
}
/**
* If the provided character can afford and equip this item.
*
* @param {Character} character - The character looking to buy the item.
* @param {integer} quantity - The quantity of this item to purchase.
*
* @return boolean
*/
canBePurchasedBy(character, quantity = 1) {
return super.canBePurchasedBy(character, quantity) && character.level >= this.level;
}
/**
* Unequip this item from the specified character.
*
* @param {Character} character - The character to unequip the item from.
*/
unequipFrom(character) { }
/**
* Equip this item to the specified character.
*
* @param {Character} character - The character to equip the item to.
*/
equipTo(character) { }
/**
* Perform any post-fight success actions and return the messages arising from them.
*
* @param {Character} character - The character who won the fight.
* @param {array} messages - Messages that have already been generated.
*
* @return {array}
*/
doFightSuccess(character, messages) {
return messages;
}
/**
* Get a description of how this item will change the provided character's stats.
*
* @param {Equipment} oldEquipment - The old equipment to compare to this equipment.
* @param {array} attributes - The attributes to compare on.
*
* @return string
*/
getEquipmentShopDescription(oldEquipment, attributes) {
if (oldEquipment.type === this.type) {
return "--Equipped--";
}
let differences = [];
for (let attribute of attributes) {
if (oldEquipment[attribute] !== this[attribute]) {
let change = this[attribute] - oldEquipment[attribute];
let sign = change > 0 ? '+' : '';
differences.push(`${sign}${change} ${Text.getLongAttributeName(attribute)}`);
}
}
return differences.join(', ');
}
/**
* Do any actions that might happen after each round of combat (regen, etc.)
*
* @param {Character} character - The character in combat.
*
* @return {array} The messages generated by these actions.
*/
doPostRoundActions(character) {
return [];
}
} |
JavaScript | class Interface {
//-------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------
/**
* @constructs
* @param {function(new:Implementable)} implementable
* @param {string} name
* @param {Interface=} superinterface
*/
constructor(implementable, name, superinterface) {
/**
* @private
* @type {function(new:Implementable)}
*/
this.implementable = implementable;
/**
* @private
* @type {string}
*/
this.name = name;
/**
* @private
* @type {Interface}
*/
this.superinterface = superinterface;
}
//-------------------------------------------------------------------------------
// Getters and Setters
//-------------------------------------------------------------------------------
/**
* @return {function(new:Implementable)}
*/
getImplementable() {
return this.implementable;
}
/**
* @return {string}
*/
getName() {
return this.name;
}
/**
* @return {Interface}
*/
getSuperinterface() {
return this.superinterface;
}
//-------------------------------------------------------------------------------
// Public Static Methods
//-------------------------------------------------------------------------------
/**
* @static
* @param {Object.<string, function(..):*>} declaration
* @return {function(new:Implementable)}
*/
static declare(declaration) {
return Interface.extend(Implementable, declaration);
}
/**
* @static
* @param {function(new:Implementable)} implementable
* @param {Object.<string, function(..):*>} declaration
* @return {function(new:Implementable)}
*/
static extend(implementable, declaration) {
if (!_.isFunction(implementable)) {
throw new Error('implementable must be a function');
}
const prototype = new implementable();
const interfaceName = declaration['_name'] || implementable.name;
delete declaration['_name'];
for (const name in declaration) {
if (Object.prototype.hasOwnProperty.call(declaration, name)) {
if (_.isFunction(declaration[name])) {
prototype[name] = declaration[name];
} else {
throw new Error('Interface can only declare functions');
}
}
}
const newImplementable = function() {
};
newImplementable.prototype = prototype;
newImplementable.constructor = newImplementable;
_.assign(newImplementable, {
getInterface: function() {
return newImplementable._interface;
}
});
const newInterface = new Interface(newImplementable, interfaceName, implementable.getInterface());
Object.defineProperty(newImplementable, '_interface', {
value: newInterface,
writable: false,
enumerable: false,
configurable: false
});
Interface.implementableToInterfaceMap.set(newImplementable, newInterface);
return newImplementable;
}
/**
* @static
* @param {function(new:T)} implementable
* @return {Interface<T>}
* @template {T}
*/
static get(implementable) {
return Interface.implementableToInterfaceMap.get(implementable);
}
//-------------------------------------------------------------------------------
// Private Static Methods
//-------------------------------------------------------------------------------
/**
* @private
* @static
* @type {WeakMap<function(new:T), Interface<T>>}
* @template {T}
*/
static implementableToInterfaceMap = new WeakMap();
} |
JavaScript | class Registration {
constructor (registration) {
Joi.assert(registration, JOI_REGISTRATION, 'Invalid Registration Object');
this.$name = registration.$name;
this.$inject = (registration.$inject || []).map(Injection.create);
this.$value = registration.$value;
this.$factory = registration.$factory;
this.$service = registration.$service;
}
get isValue () {
return exists(this.$value);
}
get isFactory () {
return exists(this.$factory);
}
get isService () {
return exists(this.$service);
}
get dependencies () {
return map(this.$inject, 'source');
}
static create (registration) {
return new Registration(registration);
}
} |
JavaScript | class Injection {
constructor (injector) {
if (!isString(injector)) {
throw new Error('Injection constructor expects first argument to be a string.');
}
let result = injector.match(REGEX_MATCH_INJECTOR_AS_SYNTAX);
if (isArray(result) && result.length === 3) { // has 'as' in it.
this.source = result[1];
this.target = result[2];
} else {
this.source = injector;
this.target = injector;
}
this.original = injector;
Joi.assert(this, JOI_INJECTION, 'Invalid Injection');
}
static create (injector) {
return new Injection(injector);
}
} |
JavaScript | class Champion {
/**
* Constructor for the Champion class.
* @param {Object} config Represents the configuration previously set in
* <br>the DataDragon class constructor.
*/
constructor(config) {
this.CONFIG = config;
}
/**
* Gets the information listed for all champions.
*/
async get_all() {
let data = await this.CONFIG.fetch(`data/${this.CONFIG.LANG}/champion.json`);
let champions = data.data;
return champions;
}
/**
* Gets the square image file of the requested champion.
* @param {string} champion_name The name of the champion requested. Case sensitive, no spaces.
*/
async get_champion_img(champion_name) {
let image = this.CONFIG.fetch(`img/champion/${champion_name}.png`);
return image;
}
} |
JavaScript | class QueryRealtimeTransformer {
realtime(realtime) {
this.$__realtime = realtime;
}
executeQuery(query, callback) {
if(false === query instanceof Query)
{
throw new Error('The given object is not an instance of `Query`.');
}
// Send the query to the server
this.$__realtime.send('bazalt:query', query.toObject(), function(response) {
if('function' === typeof callback)
{
// Transform response to error / result format
callback(response.error, response.result);
}
});
}
transformer() {
var self = this;
// Return the transformer for Query
return function(callback) {
// Transfer the query
self.executeQuery(this, callback);
};
}
} |
JavaScript | class ARDataPriceOracleEstimator extends ar_data_price_estimator_1.AbstractARDataPriceEstimator {
constructor(oracle = new gateway_oracle_1.GatewayOracle()) {
super();
this.oracle = oracle;
}
/**
* Generates a price estimate, in Winston, for an upload of size `byteCount`.
*
* @param byteCount the number of bytes for which a price estimate should be generated
*
* @returns Promise for the price of an upload of size `byteCount` in Winston
*/
getBaseWinstonPriceForByteCount(byteCount) {
return __awaiter(this, void 0, void 0, function* () {
return this.oracle.getWinstonPriceForByteCount(byteCount);
});
}
} |
JavaScript | class GaussianRNG
{
constructor()
{
this.nextValue = NaN;
}
getNextRandom()
{
if ( !Number.isNaN( this.nextValue ) )
{
const ret = this.nextValue;
this.nextValue = NaN;
return ret;
}
let u, v, s = 0;
while ( s > 1 || s == 0 )
{
u = Math.random() * 2.0 - 1.0;
v = Math.random() * 2.0 - 1.0;
s = u * u + v * v;
}
const mult = Math.sqrt( -2.0 * Math.log( s ) / s );
this.nextValue = v * mult;
return u * mult;
}
} |
JavaScript | class AppliedReservations {
/**
* Create a AppliedReservations.
* @member {string} [id] Identifier of the applied reservations
* @member {string} [name] Name of resource
* @member {string} [type] Type of resource.
* "Microsoft.Capacity/AppliedReservations"
* @member {object} [reservationOrderIds]
* @member {array} [reservationOrderIds.value]
* @member {string} [reservationOrderIds.nextLink] Url to get the next page
* of reservations
*/
constructor() {
}
/**
* Defines the metadata of AppliedReservations
*
* @returns {object} metadata of AppliedReservations
*
*/
mapper() {
return {
required: false,
serializedName: 'AppliedReservations',
type: {
name: 'Composite',
className: 'AppliedReservations',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
reservationOrderIds: {
required: false,
serializedName: 'properties.reservationOrderIds',
type: {
name: 'Composite',
className: 'AppliedReservationList'
}
}
}
}
};
}
} |
JavaScript | class RpcConfig {
/**
* @constructor
* @constructs RpcConfig
* @property {String} host the RabbitMQ Server.
*/
constructor (host) {
this.host = host || 'localhost'
}
/**
* @static
* @returns {RpcConfig}
* @param {Object} object The object to use
*/
static getConfigFromAnyObject (object) {
return new RpcConfig(object.host)
}
/**
* @static
* @returns {RpcConfig}
*
*/
static getConfigFromEnvironment () {
return new RpcConfig(
process.env.LAVA_RPC_HOST
)
}
} |
JavaScript | class RPC {
/**
* @constructs RPC
* @constructor
* @param {RpcConfig} config The configuration of the rpc server
*/
constructor (config) {
this.waited = new Map()
console.log('Connecting to RabbitMq')
amqp.connect(`amqp://${config.host}`, (erro0, connection) => {
if (erro0) {
console.error('Can\'t connect to RabbitMq', erro0)
process.exit(1)
}
console.info('Connected to the RabbitMq server.')
connection.createChannel((error1, channel) => {
if (error1) {
console.error('Can\'t create the RabbitMq channel', error1)
process.exit(1)
}
console.info('Connected to the channel.')
this.channel = channel
channel.assertQueue('', {
exclusive: true
}, (error2, queue) => {
if (error2) {
console.error('Can\'t create the rpc callback queue', error1)
process.exit(1)
}
console.info('Created the custom queue')
this.queue = queue
// Registering the listner.
this.channel.consume(this.queue.queue, (msg) => {
if (this.waited.has(msg.properties.correlationId)) {
const wait = this.waited.get(msg.properties.correlationId)
clearTimeout(wait.timeout)
wait.callback(null, msg.content)
}
}, {
noAck: true
})
})
})
})
}
/**
* Calls a rpc method.
* @param {String} callName The rpc call name.
* @param {Object} payload The payload to send to the rpc queue.
* @param {Function} callback The callback to call once the request is finished.
*/
rpcCall (callName, payload, callback) {
const correlationId = RPC.generateUuid()
this.channel.sendToQueue('rpc_lavapodler', Buffer.from(JSON.stringify({
call: callName,
...payload
})), {
correlationId: correlationId,
replyTo: this.queue.queue
})
const timeout = setTimeout(() => callback(new Error('RPC timeout'), null), 5000)
this.waited.set(correlationId, {
timeout: timeout,
callback
})
}
/**
* Generate a random id.
* @static
*/
static generateUuid () {
return Math.random().toString() +
Math.random().toString() +
Math.random().toString()
}
} |
JavaScript | class SurveyInfo extends State {
constructor(obj) {
super(SurveyInfo.getClass(), [obj.department, obj.createdAt]);
this.currentState = null;
Object.assign(this, obj);
}
getDepartment() {
return this.department;
}
getCreatedAt() {
return this.createdAt;
}
getUpdatedAt() {
return this.updatedAt;
}
getManagerID() {
return this.managerID;
}
getStartDate() {
return this.startDate;
}
getFinishDate() {
return this.finishDate;
}
getCurrentState() {
return this.currentState;
}
setCreatedAt(newTime) {
this.createdAt = newTime;
}
setUpdatedAt(newTime) {
this.updatedAt = newTime;
}
setRegistered() {
this.currentState = surveyState.REGISTERED;
}
setSurveying() {
this.currentState = surveyState.SURVEYING;
}
setFinished() {
this.currentState = surveyState.FINISHED;
}
setRemoved() {
this.currentState = surveyState.REMOVED;
}
isRegistered() {
return this.currentState === surveyState.REGISTERED;
}
isSurveying() {
return this.currentState === surveyState.SURVEYING;
}
isFinished() {
return this.currentState === surveyState.FINISHED;
}
isRemoved() {
return this.currentState === surveyState.REMOVED;
}
static makeKey(keyParts) {
keyParts.unshift(SurveyInfo.getClass());
return State.makeKey(keyParts);
}
static createInstance(department, createdAt, managerID, title, startDate, finishDate) {
return new SurveyInfo({ department, createdAt, managerID, title, startDate, finishDate });
}
static getClass() {
return 'org.jnu.surveyinfo';
}
} |
JavaScript | class Wsdl extends Resource {
/**
* Constructor of the WSDL API client
* @param {*} client SwaggerClient object
*/
constructor(client = null) {
super();
if (client == null) {
this.apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment()).client;
} else {
this.apiClient = client;
}
}
/**
* Download the WSDL of an API for the given gateway environment
*
* @static
* @param {string} apiId API UUID
* @param {string} environmentName name of the gateway environment
* @returns {*} WSDL validation response
* @memberof Wsdl
*/
downloadWSDLForEnvironment(apiId, environmentName = null) {
return this.apiClient.then((client) => {
return client.apis.APIs.getWSDLOfAPI({ apiId, environmentName });
});
}
} |
JavaScript | class MyApp extends Component {
constructor(props) {
super(props);
// If the user has logged in, grab info from sessionStorage
this.state = window.__PRELOADED_STATE__;
// just gotta do this cause React
this.loggedIn = this.loggedIn.bind(this);
this.logIn = this.logIn.bind(this);
this.logOut = this.logOut.bind(this);
}
// is the respondent logged in?
loggedIn() {
return this.state.respondentId;
}
// Log a respondent in
logIn(respondentId) {
console.log(`called login function with ${respondentId}`);
// backend call to log a respondent in
axios.post('/api/respondent/login', {
respondentId
}).then(res => {
this.setState(res.data);
}).catch(err => {
alert("An unexpected error occurred.");
console.log(err);
});
}
logOut() {
// backend call to log a respondent out
axios.post('/api/respondent/logout', {}).then(res => {
this.setState(null);
}).catch(err => {
alert("An unexpected error occurred.");
console.log(err);
});
}
render() {
return (
<div>
<Header/>
{/* BrowserRouter is around so other paths can be created */}
<BrowserRouter>
<Route path="/" render={props =>
// if loggedIn, display the search menu
// if not, show login page
this.loggedIn() ?
(<HouseSearch {...props} respondentId={this.state.respondentId}/>):
(<Login {...props} logIn={this.logIn}/>)
}/>
</BrowserRouter>
</div>
);
}
} |
JavaScript | class Player {
/**
* @constructor
* @param {object} img - player img
*/
constructor(img) {
this.row_no = 0
this.img = img
this.x = 0
this.y = 440
this.dx = 50
this.dy = 85
}
/**
* @increment
* @param {int} x
* @param {int} y
*/
increment({x=0, y=0}) {
if(x)
this.x += this.dx
if(y) {
this.y += this.dy
this.row_no--
}
}
/**
* @decrement
* @param {int} x
* @param {int} y
*/
decrement({x=0, y=0}) {
if(x)
this.x -= this.dx
if(y) {
this.y -= this.dy
// this.y < 200 ? this.y -= this.y : this.y -= this.dy
this.row_no++
}
}
/**
* @reset_row - get back to row 0
*/
reset_row() {
this.y = 440
this.row_no = 0
}
/**
* @reset_pos - reset to original position
*/
reset_pos() {
this.y = 440
this.x = 0
this.row_no = 0
}
} |
JavaScript | class BasicTable extends Component {
render() {
const title = brand.name + ' - Table';
const description = brand.desc;
return (
<div>
<Helmet>
<title>{title}</title>
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="twitter:title" content={title} />
<meta
property="twitter:description"
content={description}
/>
</Helmet>
<PapperBlock
title="Table"
whiteBg
icon="ios-menu-outline"
desc="User table"
>
<div>
<StrippedTable />
</div>
</PapperBlock>
</div>
);
}
} |
JavaScript | class DiscoverSelect extends Component {
static propTypes = {
label: PropTypes.string,
options: PropTypes.arrayOf(React.PropTypes.string),
currentOption: PropTypes.string,
onSelect: PropTypes.func.isRequired
}
static defaultProps = {
currentOption: ''
}
constructor(props) {
super(props);
this.state = {
opened: false
}
this.onClick = this.onClick.bind(this);
this.onClickOutsideRef = this.onClickOutside.bind(this);
}
render() {
const { label, options, currentOption } = this.props;
const { opened } = this.state;
return (
<div className='DiscoverSelect'>
<div className='DiscoverSelect-label'>{ label }</div>
<div className='DiscoverSelect-selected' onClick={this.onClick}>
<span>{ currentOption }</span>
<span className='arrow--bottom'></span>
</div>
{opened ? (
<div className='DiscoverSelect-menu' onClick={e => e.nativeEvent.stopImmediatePropagation()}>
<ul>
{options && options.map(option => <li onClick={this.onMenuItemClickMiddleware(option)}>{ option.replace(/\s+/g, nbsp) }</li>)}
</ul>
</div>
) : null}
</div>
)
}
componentDidMount() {
document.addEventListener('click', this.onClickOutsideRef);
}
componentWillUnmount() {
document.removeEventListener('click', this.onClickOutsideRef);
}
onClick(e) {
this.setState({opened: !this.state.opened});
e.nativeEvent.stopImmediatePropagation();
}
onClickOutside() {
this.setState({opened: false});
}
onMenuItemClickMiddleware(option) {
const { onSelect } = this.props;
return () => {
onSelect(option);
this.setState({opened: false});
}
}
} |
JavaScript | class SendHouse extends Component {
render() {
return (
<div className='col-auto'>
{this.props.houseTokenBalance === 0 ? <h2>No House Tokens Owned!</h2> : (
<>
<h2 className='mb-3'>Send House Token
<img src={sendhouse} className='ml-2' width='75' height='75' alt='send-house'/>
</h2>
<form className='mb-3' onSubmit={(event) => {
event.preventDefault()
let amount, targetAddress
amount = this.inputAmount.value.toString()
targetAddress = this.targetAddress.value
this.props.sendTokens(amount, targetAddress)
this.inputAmount.value = null
this.targetAddress = null
}}>
<div className='row justify-content-center'>
<div className='form-group mb-4 col-auto'>
<label className='mx-2'>Address</label>
<input
type='text'
ref={(targetAddress) => { this.targetAddress = targetAddress }}
className='form-control form-control-lg'
placeholder='0x0...'
required />
</div>
<div className='form-group mb-4 col-auto'>
<label className='mx-2'>House ID</label>
<select className='form-control form-control-lg' id='houseIDSelect' ref={(inputAmount) => { this.inputAmount = inputAmount }}>
{this.props.houseTokenList.map(house => (
<React.Fragment key={house.houseID}>
{this.props.account === house.owner ? (
<option key={house.houseID}>
{house.houseID}
</option>
) : null}
</React.Fragment>
))}
</select>
</div>
</div>
<button type='submit' className='btn btn-primary btn-lg col-auto' >
Send!
</button>
</form>
</>
)}
</div>
);
}
} |
JavaScript | class StateSelectBox extends Component {
render() {
return (
<div className="form-group">
<Input type="select" innerRef={this.props.reference} className="form-control">
<option value="0" >Select a State</option>
{this.props.options.map(option => {
return <option value={option._id} key={option.stateName}>{option.stateName.toUpperCase()}</option>
})}
</Input>
</div>
)
}
} |
JavaScript | class Terminal {
static TERMINAL_NAME = "CHRONOS";
static TERMINAL_VERS = "V10.4";
static TERMINAL_COPY = "APPIX SYSTEMS TECHNOLOGIES INC. ©1984";
static TERMINAL_COMP = "COMPILED 1984-11-06 04:18:00";
/**
* Caches loaded instructions from JS files.
*
* @type {Object.<string,function(UserProgram,any[]):any>}
*/
static LOADED_INSTRUCTIONS = {};
/**
* @type {SScreen}
*/
screen;
/**
* Constructs a new Terminal with a screen targeting the input element.
* @param {HTMLElement} screenEl
*/
constructor(screenEl) {
this.screen = new SScreen(screenEl);
}
/**
* @param {string[]} programInput
*/
async init(programInput = []) {
while (true) {
this.screen.clear();
// When no previous input is available, print copyright info.
if (programInput.length == 0) {
await this.screen.print(
Terminal.TERMINAL_NAME +
" " +
Terminal.TERMINAL_VERS +
"\n" +
Terminal.TERMINAL_COPY +
"\n" +
Terminal.TERMINAL_COMP +
"\n" +
"\n",
{ speed: 10 }
);
await this.screen.print("RAM................16384B", {
speed: 15,
});
await this.screen.print("INPUT..............OK", { speed: 15 });
const creds = await Messaging.post({
instruction: "gjcreds",
command: "read",
args: {},
});
const netStatus = creds.id ?? "LOCALNET";
await this.screen.print("NET ID............." + netStatus, {
speed: 15,
});
await this.screen.print("\n", { speed: 15 });
}
const prg = await UserProgram.createFromScreenRead(
this,
programInput
);
try {
await this._runProgram(prg);
} catch (error) {
console.debug("Caught program execution error", error);
// Unmute here so we can properly continue with the error message.
this.screen.setMuted(false);
this.screen.clear();
if (error instanceof InterruptError) {
await this.screen.print(
"^C PROGRAM TERMINATED BY USER.\n\n"
);
} else if (error instanceof UnknownInstructionError) {
await this._printError("UNKNOWN INSTR ERROR", {
instr: "`" + error.instr + "`",
});
} else if (error instanceof InvokeError) {
await this._printError("SYSTEM INVOKE ERROR", {
type: error.prevName,
msg: error.prevMessage,
data: JSON.stringify(error.data),
});
} else if (error instanceof UserSyntaxError) {
await this._printError("SYNTAX ERROR", {
msg: error.message,
line: (error.lineNum * 10).toString(),
code: "`" + error.line + "`",
});
}
}
programInput = await this._programCleanup(prg.lines);
}
}
/**
* Prints a user program error to the screen.
* @param {string} title
* @param {Object.<string,string>} details
*/
async _printError(title, details = {}) {
// Print error title in box-like design
const titleTop = "╭" + "─".repeat(title.length) + "╮\n";
await this.screen.print(titleTop);
const titleText = " " + title + " \n";
await this.screen.print(titleText, { color: "red" });
const titleBottom = "╰" + "─".repeat(title.length) + "╯\n";
await this.screen.print(titleBottom);
// Print error details below (if given).
const detailKeys = Object.keys(details);
if (detailKeys.length > 0) {
// Get longest length of detail keys to pad others.
const len = Math.max(...detailKeys.map((i) => i.length));
for (const detailKey of detailKeys) {
const detailKeyText = detailKey.padEnd(len, " ").toUpperCase();
await this.screen.print(
detailKeyText + ": " + details[detailKey] + "\n"
);
}
await this.screen.print("\n");
}
}
/**
* Executes a user program in this terminal.
* @param {UserProgram} prg
*/
async _runProgram(prg) {
this.screen.clear();
await this.screen.print("EXECUTING PROGRAM...\n\n", { speed: 10 });
await prg.run();
await this.screen.print("\nPROGRAM EXECUTION COMPLETED\n\n", {
speed: 10,
});
}
/**
* Prompts the user after the user program execution finished.
*
* @param {string[]} lines
* @return {Promise<string[]>}
*/
async _programCleanup(lines) {
const result = await this.screen.prompt(["EXIT", "CONTINUE"]);
let programInput = [];
if (result == "CONTINUE") {
programInput = lines;
}
return programInput;
}
/**
* Instructs the terminal to load an instruction.
* @param {string} instruction The instruction name.
* @return {Promise<function(UserProgram,any[]):any>} The instruction function.
*/
async loadInstruction(instruction) {
// If the requested instruction is not yet loaded, try to load it now.
if (!Terminal.LOADED_INSTRUCTIONS[instruction]) {
await new Promise((resolve, reject) => {
// Create new script element to append to the doc, which will load in its source.
const scriptEl = document.createElement("script");
// Handle successful append and load.
scriptEl.onload = () => {
console.debug("Loaded instruction", instruction);
scriptEl.remove();
resolve();
};
// Handle failure (instruction does not exist or cannot be accessed.)
scriptEl.onerror = () => {
console.debug("Failed to load instruction", instruction);
scriptEl.remove();
reject(new UnknownInstructionError(instruction));
};
// Add src and append.
// Find the source path to the instructions list from the current program location.
// Step backwards until SRC is reached, from there walk into the instr dir.
let src =
"components/terminal/instr/" +
instruction.toLowerCase() +
".js";
let locPath = location.pathname.split("/");
locPath.pop(); // Removes "index.html"/file entry.
while (
locPath[locPath.length - 1] !== "programs" &&
locPath.length > 0
) {
locPath.pop();
src = "../" + src;
}
// Walk up once more.
locPath.pop();
src = "../" + src;
scriptEl.src = src;
document.body.appendChild(scriptEl);
});
}
// Return the instruction function after it loaded.
if (Terminal.LOADED_INSTRUCTIONS[instruction]) {
return Terminal.LOADED_INSTRUCTIONS[instruction];
}
// Failsafe (this should never happen as the failure to load throws as well).
throw new UnknownInstructionError(instruction);
}
} |
JavaScript | class UserProgram {
/**
* This program's name (`"INLINE"` for programs directly written in the terminal).
* @type {string}
*/
name;
/**
* Parent terminal this program was created in.
* @type {Terminal}
*/
terminal;
/**
* Lines of program code of this program.
* @type {string[]}
*/
lines;
/**
* Gets set when the user interrupts the execution of this program.
*/
_interruptFlag = false;
/**
* @param {Terminal} terminal
* @param {string[]} lines
*/
constructor(terminal, lines) {
this.terminal = terminal;
this.lines = lines;
}
/**
* Creates a user program by prompting the user for input, then creates a program from it.
* @param {Terminal} terminal
* @param {string[]} input Previous input the read should start with.
*/
static async createFromScreenRead(terminal, input = []) {
const lines = await terminal.screen.read(input);
const prg = new this(terminal, lines);
prg.name = "INLINE";
return prg;
}
/**
* Executes this program.
* @return {Promise<any>} Returns the result of the last instruction of this program.
* @throws Throws various errors when failures during execution arise.
*/
async run() {
// Set up interruption handler.
const interruptCallback = this._checkInterrupt.bind(this);
document.addEventListener("keydown", interruptCallback);
try {
return await this._runCode();
} catch (error) {
// Rethrow any errors that arise during code execution.
// This try...catch is here so we can finally the event listener removal.
throw error;
} finally {
// Remove interruption handler.
document.removeEventListener("keydown", interruptCallback);
}
}
/**
* Runs this program's code.
* @return {Promise<any>} Returns the result of the last instruction of this program.
*/
async _runCode() {
let cursor = 0;
let lastReturn = null;
while (cursor < this.lines.length) {
const line = this.lines[cursor];
// Advance cursor to next line.
cursor++;
// Skip empty line.
if (line == "") {
continue;
}
const chain = this._parseLine(line, cursor);
let lastChainReturn = null;
for (let i = 0; i < chain.length; i++) {
const link = chain[i];
// When it's not the last part of the chain, mute the screen.
this.terminal.screen.setMuted(i < chain.length - 1);
const instrName = link.instr;
const instrArgs = link.args;
// When we are in the chain and have received a return from a previous
// instr, append it to the next instr's args.
if (lastChainReturn !== null) {
instrArgs.push(lastChainReturn);
}
// Run the instr.
lastChainReturn = await this.runInstruction(
instrName,
instrArgs
);
}
lastReturn = lastChainReturn;
}
return lastReturn;
}
/**
* Parses a line into a chain of instructions with args.
* @param {string} line
* @param {number} lineNum
* @return {{instr:string,args:string[]}[]}
*/
_parseLine(line, lineNum) {
line = line.trim();
// Cannot have these characters at start/end.
if (
line.startsWith(">") ||
line.startsWith('"') ||
line.endsWith(">")
) {
throw new UserSyntaxError("INVALID CONTROL CHAR", line, lineNum);
}
const chain = [];
let cursor = 0;
let isQuoted = false;
let current = "";
let isInstr = true;
let instrName = "";
let instrArgs = [];
let acceptEmptyArg = false;
const pushCurrentLink = () => {
// When still parsing instr, finish it now.
if (isInstr) {
finishInstr();
}
// Otherwise, push the current arg.
else {
pushArg();
}
// Push when at least an instr was parsed.
instrName = instrName.trim();
if (instrName) {
chain.push({
instr: instrName,
args: instrArgs,
});
}
// Reset state.
instrName = "";
instrArgs = [];
current = "";
isInstr = true;
acceptEmptyArg = false;
};
const pushArg = () => {
if (current.length > 0 || acceptEmptyArg) {
instrArgs.push(current);
current = "";
}
acceptEmptyArg = false;
};
const finishInstr = () => {
isInstr = false;
instrName = current.trim();
current = "";
instrArgs = [];
// Special handling for files.
// The "write" command can be omitted, for any consecutive links in a chain,
// and a file target is identified as starting with "/".
if (instrName.startsWith("/")) {
// This is a syntax error when done as the first link in a chain.
if (chain.length == 0) {
throw new UserSyntaxError(
"INVALID FILENAME AT POS 0",
line,
lineNum
);
}
instrArgs.push(instrName);
instrName = "WRITE";
}
// Make sure the instr name is valid.
if (!/^[a-zA-Z0-9]{2,16}$/.test(instrName)) {
throw new UserSyntaxError("INVALID INSTR NAME", line, lineNum);
}
};
while (cursor < line.length) {
const c = line[cursor];
cursor++;
if (isQuoted) {
// At the end of a quote, the arg ends. Push it.
if (c == '"') {
isQuoted = false;
acceptEmptyArg = true; // An arg like `""` can be accepted here.
pushArg();
}
// While quoted, keep concatenating any chars.
else {
current += c;
}
// Ignore any other logic.
continue;
}
switch (c) {
case '"':
// Quotes during instr name is a syntax error.
if (isInstr) {
throw new UserSyntaxError(
"QUOTES IN INSTR NAME",
line,
lineNum
);
}
isQuoted = true;
break;
case " ":
// Ignore any spaces before the first real char.
if (current == "") {
break;
}
// First space in chain link finishes instruction.
if (isInstr) {
finishInstr();
break;
}
// End of arg.
pushArg();
break;
case ">":
pushCurrentLink();
break;
default:
current += c;
break;
}
}
// Throw syntax error when last quote was not closed.
if (isQuoted) {
throw new UserSyntaxError("NO END QUOTE", line, lineNum);
}
pushCurrentLink();
return chain;
}
/**
* Runs an instruction within the program.
* @param {string} instruction The instruction name.
* @param {any[]} args Arguments to be passed to the instruction.
* @return {Promise<any>} The result of the run instruction.
*/
async runInstruction(instruction, args) {
// When the user interrupted the program during the last instruction, throw now.
if (this._interruptFlag) {
throw new InterruptError();
}
// Load instruction and execute.
const instr = await this.terminal.loadInstruction(instruction);
return instr(this, args);
}
/**
* Interrupt check that reacts on keyboard input.
* Interrupts the program when user presses CTRL+C.
* @param {KeyboardEvent} e
*/
_checkInterrupt(e) {
if (!this._interruptFlag && e.key == "c" && e.ctrlKey) {
console.debug("User program interrupt", this.name);
this._interruptFlag = true;
}
}
} |
JavaScript | class FlatButton extends Component {
static muiName = 'FlatButton';
static propTypes = {
/**
* @property {PropTypes.string} backgroundColor - Color of button when mouse is not hovering over it.
*/
backgroundColor: PropTypes.string,
/**
* @property {PropTypes.node} children - This is what will be displayed inside the button.
* If a label is specified, the text within the label prop will
* be displayed. Otherwise, the component will expect children
* which will then be displayed. (In our example,
* we are nesting an `<input type="file" />` and a `span`
* that acts as our label to be displayed.) This only
* applies to flat and raised buttons.
*/
children: PropTypes.node,
/**
* @property {PropTypes.string} className - The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* @property {string|element} containerElement - The element to use as the container for the FlatButton. Either a string to
* use a DOM element or a ReactElement. This is useful for wrapping the
* FlatButton in a custom Link component. If a ReactElement is given, ensure
* that it passes all of its given props through to the underlying DOM
* element and renders its children prop for proper integration.
*/
containerElement: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
/**
* @property {PropTypes.bool} disableTouchRipple - If true, the element's ripple effect will be disabled.
*/
disableTouchRipple: PropTypes.bool,
/**
* @property {PropTypes.bool} disabled - Disables the button if set to true.
*/
disabled: PropTypes.bool,
/**
* @property {PropTypes.bool} fullWidth - If true, the button will take up the full width of its container.
*/
fullWidth: PropTypes.bool,
/**
* @property {PropTypes.string} hoverColor - Color of button when mouse hovers over.
*/
hoverColor: PropTypes.string,
/**
* @property {PropTypes.string} href - The URL to link to when the button is clicked.
*/
href: PropTypes.string,
/**
* @property {PropTypes.node} icon - Use this property to display an icon.
*/
icon: PropTypes.node,
/**
* @property {custom} label - Label for the button.
*/
label: validateLabel,
/**
* @property {['before','after']} labelPosition - Place label before or after the passed children.
*/
labelPosition: PropTypes.oneOf([
'before',
'after',
]),
/**
* @property {PropTypes.object} labelStyle - Override the inline-styles of the button's label element.
*/
labelStyle: PropTypes.object,
/**
* @property {PropTypes.func} onClick - Callback function fired when the button is touch-tapped.
*
* @param {object} event TouchTap event targeting the button.
*/
onClick: PropTypes.func,
/**
* @property {PropTypes.func} onKeyboardFocus - Callback function fired when the element is focused or blurred by the keyboard.
*
* @param {object} event `focus` or `blur` event targeting the element.
* @param {boolean} isKeyboardFocused Indicates whether the element is focused.
*/
onKeyboardFocus: PropTypes.func,
/** @ignore */
onMouseEnter: PropTypes.func,
/** @ignore */
onMouseLeave: PropTypes.func,
/** @ignore */
onTouchStart: PropTypes.func,
/**
* @property {PropTypes.bool} primary - If true, colors button according to
* primaryTextColor from the Theme.
*/
primary: PropTypes.bool,
/**
* @property {PropTypes.string} rippleColor - Color for the ripple after button is clicked.
*/
rippleColor: PropTypes.string,
/**
* @property {PropTypes.bool} secondary - If true, colors button according to secondaryTextColor from the theme.
* The primary prop has precendent if set to true.
*/
secondary: PropTypes.bool,
/**
* @property {PropTypes.object} style - Override the inline-styles of the root element.
*/
style: PropTypes.object,
};
static defaultProps = {
disabled: false,
fullWidth: false,
labelStyle: {},
labelPosition: 'after',
onKeyboardFocus: () => {},
onMouseEnter: () => {},
onMouseLeave: () => {},
onTouchStart: () => {},
primary: false,
secondary: false,
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
state = {
hovered: false,
isKeyboardFocused: false,
touch: false,
};
componentWillReceiveProps(nextProps) {
if (nextProps.disabled) {
this.setState({
hovered: false,
});
}
}
handleKeyboardFocus = (event, isKeyboardFocused) => {
this.setState({isKeyboardFocused: isKeyboardFocused});
this.props.onKeyboardFocus(event, isKeyboardFocused);
};
handleMouseEnter = (event) => {
// Cancel hover styles for touch devices
if (!this.state.touch) this.setState({hovered: true});
this.props.onMouseEnter(event);
};
handleMouseLeave = (event) => {
this.setState({hovered: false});
this.props.onMouseLeave(event);
};
handleTouchStart = (event) => {
this.setState({touch: true});
this.props.onTouchStart(event);
};
render() {
const {
backgroundColor,
children,
disabled,
fullWidth,
hoverColor,
icon,
label,
labelStyle,
labelPosition,
primary,
rippleColor,
secondary,
style,
...other
} = this.props;
const {
borderRadius,
button: {
height: buttonHeight,
minWidth: buttonMinWidth,
textTransform: buttonTextTransform,
},
flatButton: {
buttonFilterColor,
color: buttonColor,
disabledTextColor,
fontSize,
fontWeight,
primaryTextColor,
secondaryTextColor,
textColor,
textTransform = buttonTextTransform || 'uppercase',
},
} = this.context.muiTheme;
const defaultTextColor = disabled ? disabledTextColor :
primary ? primaryTextColor :
secondary ? secondaryTextColor :
textColor;
const defaultHoverColor = fade(buttonFilterColor, 0.2);
const defaultRippleColor = buttonFilterColor;
const buttonHoverColor = hoverColor || defaultHoverColor;
const buttonRippleColor = rippleColor || defaultRippleColor;
const buttonBackgroundColor = backgroundColor || buttonColor;
const hovered = (this.state.hovered || this.state.isKeyboardFocused) && !disabled;
const mergedRootStyles = Object.assign({}, {
height: buttonHeight,
lineHeight: `${buttonHeight}px`,
minWidth: fullWidth ? '100%' : buttonMinWidth,
color: defaultTextColor,
transition: transitions.easeOut(),
borderRadius,
userSelect: 'none',
overflow: 'hidden',
backgroundColor: hovered ? buttonHoverColor : buttonBackgroundColor,
padding: 0,
margin: 0,
textAlign: 'center',
}, style);
let iconCloned;
const labelStyleIcon = {};
if (icon) {
const iconStyles = Object.assign({
verticalAlign: 'middle',
marginLeft: label && labelPosition !== 'before' ? 12 : 0,
marginRight: label && labelPosition === 'before' ? 12 : 0,
}, icon.props.style);
iconCloned = React.cloneElement(icon, {
color: icon.props.color || mergedRootStyles.color,
style: iconStyles,
key: 'iconCloned',
});
if (labelPosition === 'before') {
labelStyleIcon.paddingRight = 8;
} else {
labelStyleIcon.paddingLeft = 8;
}
}
const mergedLabelStyles = Object.assign({
letterSpacing: 0,
textTransform: textTransform,
fontWeight: fontWeight,
fontSize: fontSize,
}, labelStyleIcon, labelStyle);
const labelElement = label ? (
<FlatButtonLabel key="labelElement" label={label} style={mergedLabelStyles} />
) : undefined;
// Place label before or after children.
const enhancedButtonChildren = labelPosition === 'before' ?
[
labelElement,
iconCloned,
children,
] :
[
children,
iconCloned,
labelElement,
];
return (
<EnhancedButton
{...other}
disabled={disabled}
focusRippleColor={buttonRippleColor}
focusRippleOpacity={0.3}
onKeyboardFocus={this.handleKeyboardFocus}
onMouseLeave={this.handleMouseLeave}
onMouseEnter={this.handleMouseEnter}
onTouchStart={this.handleTouchStart}
style={mergedRootStyles}
touchRippleColor={buttonRippleColor}
touchRippleOpacity={0.3}
>
{enhancedButtonChildren}
</EnhancedButton>
);
}
} |
JavaScript | class Counter extends React.Component {
// construct the counter
constructor(props) {
super(props);
const start = typeof props.start !== 'undefined' ? parseInt(props.start) : 0;
this.state = {count : start};
this.onClick = this.onClick.bind(this);
}
/**
* handles the button click
* increment the current count
*/
onClick () {
let newCount = this.state.count + 1;
this.setState({count: newCount});
}
/**
* renders the view
*
* @returns {XML}
*/
render() {
const {onSave} = this.props;
return (
<div>
Count : <span>{this.state.count}</span>
<div>
<button onClick={this.onClick}>Count one more</button>
<button onClick={() => onSave(this.state.count)}>Save count</button>
</div>
</div>
);
}
} |
JavaScript | class SmoothContext {
static eventEmitter = new EventEmitter()
static DEFAULT_FILE_NAME = 'DEFAULT_FILE_NAME'
static PREAMBLE_FILE_NAME = 'PREAMBLE_FILE_NAME'
static SILENT_OPTION_STRING = 'option_silence'
static NO_MATCH_OPTION_STRING = 'option_no_match'
static HIDDEN_OPTION_STRING = 'option_hidden'
// this.predefinedVariables.OPTIONS_NO_BUTTONS = false
// this.predefinedVariables.OPTIONS_BUTTON_DELAY = 0
// this.predefinedVariables.OPTIONS_SHOW_TEXT_INPUT = false
// this.predefinedVariables.CURRENT_FACE = ''
static randomId = 0
constructor (state) {
var preamble = {
text: '',
preamble: '',
title: '',
faces: {},
firestore: {}
}
if (!state) {
state = JSON.parse(JSON.stringify(preamble))
}
preamble.text = state.preamble
this.files = {}
this.defaultFile = new SmoothFile(state)
this.preambleFile = new SmoothFile(preamble)
this.files[SmoothContext.DEFAULT_FILE_NAME] = this.defaultFile
this.files[SmoothContext.PREAMBLE_FILE_NAME] = this.preambleFile
this.currentFile = SmoothContext.DEFAULT_FILE_NAME
this.initialFace = this.defaultFile.initialFace
this.functions = {}
this.functionReturns = []
this.variables = {}
this.lineNumber = 0
this.indent = 0
this.voices = {}
// Lookup faces by ID (store, chats view)
this.faces = {}
// Lookup faces by name (player)
this.faceNameToId = {}
this.predefinedVariables = {}
this.options = []
this.voice = null
this.faceVoice = null
this.currentFaceId = null
this.recognitionLanguage = null
this.evaluationOptions = {
unattended: false,
emitEvents: true,
evaluateVariables: true
}
this.htmlOutput = ''
this.setupPredefinedVariables()
this.readFunctions(this.defaultFile.functions)
}
getLines () {
var lines = []
if (this.currentFile && this.files[this.currentFile]) {
lines = this.files[this.currentFile].lines
}
return lines
}
getLabels () {
var labels = {}
if (this.currentFile && this.files[this.currentFile]) {
labels = this.files[this.currentFile].labels
}
return labels
}
speechRecognitionBlocked () {
console.warn('Warning: speech recognition may be blocked.')
}
readFunctions (functionLines) {
var cachedLineNumber = this.lineNumber
for (var i = 0; i < functionLines.length; ++i) {
this.lineNumber = functionLines[i]
let functionNameAndArgs = null
let line = this.getLines()[this.lineNumber]
if ((functionNameAndArgs = SmoothSyntax.functionNameAndArgs.exec(line)) !== null) {
var functionName = functionNameAndArgs[1]
if (functionName === 'function') {
SmoothFunctions.execFunc(this, functionName, functionNameAndArgs[2])
} else {
throw new Error('Expected function: ' + line)
}
}
}
this.lineNumber = cachedLineNumber
}
isLocalStorageAvailable () {
try {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('feature_test', 'yes')
if (localStorage.getItem('feature_test') === 'yes') {
localStorage.removeItem('feature_test')
return true
}
}
return false
} catch (e) {
return false
}
}
setupPredefinedVariables () {
this.predefinedVariables.OPTIONS_NO_BUTTONS = false
// Hide buttons until delay or wrong answer
this.predefinedVariables.OPTIONS_BUTTON_DELAY = 0
this.predefinedVariables.OPTIONS_SHOW_TEXT_INPUT = false
this.predefinedVariables.CURRENT_FACE = ''
this.predefinedVariables.webkitSpeechRecognition = 'webkitSpeechRecognition' in window
this.predefinedVariables.webkitSpeechRecognitionPermission = false
if (this.isLocalStorageAvailable()) {
var permission = window.localStorage.getItem('webkitSpeechRecognitionPermission')
if (permission === null) {
this.predefinedVariables.webkitSpeechRecognitionPermission = false
} else {
this.predefinedVariables.webkitSpeechRecognitionPermission = permission
}
this.predefinedVariables.localStorageAvailable = true
} else {
this.predefinedVariables.localStorageAvailable = false
}
this.predefinedVariables.numSpeechSynthesisVoices = 0
if (typeof (speechSynthesis) !== 'undefined') {
this.predefinedVariables.numSpeechSynthesisVoices = speechSynthesis.getVoices().length
}
this.predefinedVariables.LAST_RESPONSE = ''
}
processNonFunctionLine (str) {
str = SmoothExpressions.replaceAndEvaluateEscapedExpressions(this, str)
// Warning!! SmoothScript does not do any sanitization of HTML
// This is a security risk, allowing XSS attacks if you have a site
// that hosts user-created content. It is your responsibility to
// sanitize the content!
this.htmlOutput += str + ' '
return Promise.resolve()
}
outputHTML () {
var voice = this.voice || this.faceVoice
if (voice) {
// strip HTML tags
var str = this.htmlOutput.replace(/(<([^>]+)>)/ig, '')
str = str.replace(/ /g, ' ')
this.htmlOutput = ''
if (!str.length) {
return Promise.resolve()
}
return new Promise((resolve, reject) => {
setTimeout(() => {
this.emitEvent('tts', {
text: str,
faceId: this.currentFaceId,
voice: voice,
onFinished: () => {
resolve()
},
onError: (error) => {
throw new Error(error)
}})
}, 0)
})
} else {
this.emitEvent('appendHTML', {html: this.htmlOutput})
this.htmlOutput = ''
return Promise.resolve()
}
}
finish () {
if (this.currentFile !== SmoothContext.PREAMBLE_FILE_NAME) {
return this.outputHTML().then(() => {
this.emitEvent('finished')
return Promise.resolve('finished')
})
} else {
return Promise.resolve()
}
}
playLineFromCurrent (handleResolveDataFn) {
var lines = this.getLines()
if (this.lineNumber >= lines.length) {
return this.finish()
}
this.lineNumber = SmoothHelper.nextImportantLine(this.lineNumber, this.getLines())
if (this.lineNumber >= lines.length) {
return this.finish()
}
var playNextLineWhenDone = (newLine) => {
this.lineNumber = newLine
return this.playLineFromCurrent(handleResolveDataFn)
}
if (!handleResolveDataFn) {
handleResolveDataFn = (resolveData) => {
if ('finished' in resolveData && resolveData.finished) {
return this.finish()
}
if ('line' in resolveData) {
return playNextLineWhenDone(resolveData.line)
}
if ('options' in resolveData) {
// Options should not be returned except for "testing" when handleResolveDataFn is overriden
throw new Error('Internal Error.')
}
throw new Error('Unknown function return promise')
}
}
var line = lines[this.lineNumber]
let functionNameAndArgs = null
if ((functionNameAndArgs = SmoothSyntax.functionNameAndArgs.exec(line)) !== null) {
var functionName = functionNameAndArgs[1]
if (SmoothFunctions.hasFunc(functionName)) {
var promise = SmoothFunctions.execFunc(this, functionName, functionNameAndArgs[2])
if (!promise || typeof promise.then !== 'function') {
throw new Error(functionName + ' failed to return a promise!')
}
return promise.then(
(resolveData) => {
return handleResolveDataFn(resolveData)
}
)
} else {
throw new Error('Unknown function: ' + functionName)
}
} else {
return this.processNonFunctionLine(line).then(() => {
return playNextLineWhenDone(this.lineNumber + 1)
})
}
}
play (handleResolveDataPreambleFn, handleResolveDataFn) {
this.lineNumber = 0
if (this.files[SmoothContext.PREAMBLE_FILE_NAME].lines.length) {
this.currentFile = SmoothContext.PREAMBLE_FILE_NAME
return this.playLineFromCurrent(handleResolveDataPreambleFn).then(() => {
this.currentFile = SmoothContext.DEFAULT_FILE_NAME
this.lineNumber = 0
return this.playLineFromCurrent(handleResolveDataFn)
})
} else {
this.currentFile = SmoothContext.DEFAULT_FILE_NAME
return this.playLineFromCurrent(handleResolveDataFn)
}
}
emitEvent (name, payload) {
if (this.evaluationOptions.emitEvents) {
SmoothContext.eventEmitter.emit(name, payload)
} else if (payload) {
if (payload.onFinished) {
// tts
payload.onFinished()
}
if (payload.onLoaded) {
// face
payload.onLoaded()
}
}
}
setOptions (options) {
this.options = options
this.randomId = Math.random()
var cachededRandom = this.randomId
;((cachededRandom) => {
var displayMatchFunction = () => {
if (!this.predefinedVariables.OPTIONS_NO_BUTTONS && this.randomId === cachededRandom) {
this.emitEvent('displayMatches', options)
}
}
if (this.predefinedVariables.OPTIONS_NO_BUTTONS ||
options.hiddenOptions.length ||
this.recognitionLanguage ||
this.predefinedVariables.OPTIONS_SHOW_TEXT_INPUT) {
this.emitEvent('startListening', this.recognitionLanguage)
}
setTimeout(() => {
displayMatchFunction()
}, this.predefinedVariables.OPTIONS_BUTTON_DELAY)
})(cachededRandom)
}
submitInput (input, bIsFinal) {
var result = this.options.submitInput(input, bIsFinal)
if (input !== SmoothContext.SILENT_OPTION_STRING) {
this.predefinedVariables.LAST_RESPONSE = input
}
if (result) {
this.randomId = Math.random()
this.lineNumber = result.line
this.emitEvent('clearHTML')
this.indent = SmoothHelper.getIndent(this.getLines()[this.lineNumber])
this.emitEvent('stopListening')
this.emitEvent('hideMatches')
this.options.resolveFunc(result)
} else if (bIsFinal && !this.predefinedVariables.OPTIONS_NO_BUTTONS) {
this.emitEvent('displayMatches', this.options)
}
}
} |
JavaScript | class Checkbox {
/**
* Sets up the checkbox's settings from a standard input data
* object and sets the type of error messages this class
* will render if the checkbox isn't valid.
*
* @param {Object} inputObj - contains all the configurations
* to render this input.
* @param {class} errorMessages - a class that will render the
* specific type of error messages based on this UI's settings.
*/
constructor(inputObj = {}, errorMessages = ErrorMessages) {
let {input, tags = '', settings = {}, errors = {}} = inputObj;
/**
* This checkbox's input configuration
* @type {Object}
*/
this.input = input;
/**
* Any custom tags passed down from the rendering library.
* @type {String}
*/
this.tags = tags;
/**
* Settings for this whole input including the container
* @type {Object}
*/
this.settings = settings;
/**
* A class of errors created by the rendering library to
* hide and show various errors.
* @type {class}
*/
this.errors = errors;
/**
* This UI's rendering of this error messages.
* @type {class}
*/
this.errorMessages = errorMessages;
}
/**
* Adds a default class to this checkbox input
* @type {String}
*/
get uiClasses() {
return ''
}
/**
* Any UI specific attributes
* @type {String}
*/
get uiAttributes() {
return ''
}
/**
* Attributes that required for this checkbox input
* to be used and rendered properly.
* @return {String} - A string of all attributes to load
* this input including its id, name and type.
*/
get requiredAttributes() {
let {input} = this;
let {id, name} = input;
return `id="${id}" name="${name}" type="checkbox"`;
}
/**
* Renders the HTML for this checkbox from the given attributes
* and classes.
* @example
* uiClasses = "class-1";
* input.classes = "class-2";
* requiredAttributes = "id='id-1' name='checkbox-name' type='checkbox'"
* // Renders To:
* <label class="class-1 class-2">
* <input id='id-1' name='checkbox-name' type='checkbox'>
* </label>
* @return {String} - html of the fully created checkbox
*/
renderCheckboxContainer(classes, attributes) {
let {input, settings} = this;
let {label = '', labelHTML, name = '', id = ''} = input;
let {showLabel = true} = settings;
if (labelHTML) label = labelHTML;
return `
<label class="${classes} ivx-input-label ivx-input-label-checkbox">
<input class="ivx-input ivx-input-checkbox" ${attributes}>
${label}
</label>
`;
}
get beforeClasses(){
return 'ivx-input-before ivx-input-before-checkbox';
}
get afterClasses(){
return 'ivx-input-after ivx-input-after-checkbox';
}
/**
* Sets up and renders all the HTML for this checkbox based on the settings.
*
* @type {String}
*/
get html() {
let {tags, settings = {}, errors, input, uiClasses, uiAttributes, requiredAttributes, beforeClasses : defaultBeforeClasses, afterClasses : defaultAfterClasses } = this;
let {input: inputSettings = {}} = settings;
let {classes = ''} = inputSettings;
let { id, name, label = '', beforeHtml : beforeSettings = {}, afterHtml : afterSettings = {} } = input;
let { messages = [], attributes = {}, tags: errorTags = ''} = this.errors;
let errorAttributes = attributes;
let errorHTML = new this.errorMessages(messages).html;
let allClasses = `${classes} ${uiClasses}`;
let allAttributes = `${requiredAttributes} ${uiAttributes} ${tags} ${errorTags}`
let checkboxHTML = this.renderCheckboxContainer(allClasses, allAttributes);
const {html : beforeHtml = "", classes : beforeClasses = ""} = beforeSettings;
const {html : afterHtml = "", classes : afterClasses = ""} = afterSettings;
let inputHTML = `
<div class="${beforeClasses} ${defaultBeforeClasses}">${beforeHtml}</div>
${checkboxHTML}
${errorHTML}
<div class="${afterClasses} ${defaultAfterClasses}">${afterHtml}</div>
`;
return `${inputHTML}`;
}
} |
JavaScript | class TreeSearchRequest {
/**
* Constructs a new <code>TreeSearchRequest</code>.
* @alias module:model/TreeSearchRequest
* @class
*/
constructor() {
}
/**
* Constructs a <code>TreeSearchRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/TreeSearchRequest} obj Optional instance to populate.
* @return {module:model/TreeSearchRequest} The populated <code>TreeSearchRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new TreeSearchRequest();
if (data.hasOwnProperty('Query')) {
obj['Query'] = TreeQuery.constructFromObject(data['Query']);
}
if (data.hasOwnProperty('Size')) {
obj['Size'] = ApiClient.convertToType(data['Size'], 'Number');
}
if (data.hasOwnProperty('From')) {
obj['From'] = ApiClient.convertToType(data['From'], 'Number');
}
if (data.hasOwnProperty('Details')) {
obj['Details'] = ApiClient.convertToType(data['Details'], 'Boolean');
}
}
return obj;
}
/**
* @member {module:model/TreeQuery} Query
*/
Query = undefined;
/**
* @member {Number} Size
*/
Size = undefined;
/**
* @member {Number} From
*/
From = undefined;
/**
* @member {Boolean} Details
*/
Details = undefined;
} |
JavaScript | class JWTPolicy extends BasePolicy {
/**
* Checks if the request needs to be authenticated
* Checks if the request contains the request header if it needs to be authenticated
* @param {Object} Request Validator
* @return {Boolean}
*/
static _approve(requestValidator) {
try {
let t = requestValidator.decodeJWTHeader()
} catch(e) {
return false
}
return true
}
} |
JavaScript | class FinalPrice extends Component {
constructor(props) {
super(props)
this.state = {
price: getIn(this.props.formik.values, 'price'),
}
}
// componentDidUpdate(prevProps) {
// if (prevProps.formik !== this.props.formik) {
// this.props.onChange(this.props.formik, prevProps.formik);
// }
// }
render() {
// All FormikProps available on props.formik!
const price = getIn(this.props.formik.values, 'price');
let priceResult = price;
const { defaultProteinPrice, defaultVeggiesPrice, protein, veggies } = this.props.formik.values;
const proteinCost = protein.reduce((accumulator, item) => accumulator + parseFloat(item.qty * item.price), 0)
if(proteinCost > defaultProteinPrice) {
priceResult += (proteinCost - defaultProteinPrice);
}
const veggiesCost = veggies.reduce((accumulator, item) => accumulator + parseFloat(item.qty * item.price), 0)
if(veggiesCost > defaultVeggiesPrice) {
priceResult += (veggiesCost - defaultVeggiesPrice);
}
if(price !== priceResult) {
this.props.onChange(priceResult)
}
return priceResult.toFixed(2);
}
} |
JavaScript | class DB {
/**
* Establishes connection to the database and returns the connection object.
*
* @static
* @returns { object } The connection object provided by mongoose.
* @memberof DB
*/
static async connect() {
await mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log('connection successful');
return mongoose.connection;
}
} |
JavaScript | class VAutoComplete extends VBase {
constructor(options, url, params, event) {
super(options);
this.element_id = options.target;
this.url = url;
this.params = params;
this.event = event;
}
call(results) {
// Clear the timeout if it has already been set.
// This will prevent the previous task from executing
// if it has been less than <MILLISECONDS>
let parentElement = this.parentElement();
let updateElement = this.createUpdateElementHandler(this);
let promiseObj = new Promise(function (resolve) {
clearTimeout(parentElement.vTimeout);
// Make a new timeout
parentElement.vTimeout = setTimeout(updateElement, 500);
results.push({action:'autocomplete', statusCode: 200});
resolve(results);
});
return promiseObj;
}
// This is used to get a proper binding of the object
// https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
createUpdateElementHandler(_this_) {
return function () {
_this_.updateElement();
};
}
updateElement() {
this.clearErrors();
this.getData(this.populateOptions);
}
dataList() {
return this.root.getElementById(this.element_id);
}
getData(funcProcessData) {
let comp = this.component();
console.log(comp);
if(comp.value().length < 2){
return;
}
let httpRequest = new XMLHttpRequest();
if (!httpRequest) {
throw new Error('Cannot talk to server! Please upgrade your browser to one that supports XMLHttpRequest.');
}
let dataList = this.dataList();
let url = this.buildURL(this.url, this.params, this.inputValues());
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
console.log(httpRequest.status + ':' + this.getResponseHeader('content-type'));
if (httpRequest.status === 200) {
let response = JSON.parse(httpRequest.responseText);
funcProcessData(response, dataList);
} else {
console.error("Unable to autocomplete! ElementId: " + this.element_id);
}
}
};
console.log('GET:' + url);
httpRequest.open('GET', url, true);
httpRequest.send();
}
populateOptions(response, dataList) {
dataList.innerHTML = "";
response.forEach(function (item) {
let value = item;
let key = null;
if (Array.isArray(item)) {
value = item[0];
key = item[1];
}
// Create a new <option> element.
let option = document.createElement('option');
option.value = value;
option.dataset.key = key;
dataList.appendChild(option);
});
}
} |
JavaScript | class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<>
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
</>
);
}
} |
JavaScript | class ADispatcher {
/**
* Creates an instance of ADispatcher.
*
* @param {AxonClient} axon
*
* @memberof ADispatcher
*/
constructor(axon) {
if (this.constructor === 'ADispatcher') {
throw new NoAbstractInstanceException();
}
this._axon = axon;
}
/**
* ADispatcher main method.
* Need to be overrided, any parameters can be used.
*
* @memberof ADispatcher
*/
dispatch() {
throw new NotImplementedException();
}
} |
JavaScript | class Asset
{
/**
* Create the new asset.
* @param {String} url Asset URL / identifier.
*/
constructor(url)
{
this._url = url;
this._waitingCallbacks = [];
}
/**
* Register a method to be called when asset is ready.
* If asset is already in ready state, will invoke immediately.
* @param {Function} callback Callback to invoke when asset is ready.
*/
onReady(callback)
{
if (this.valid || this._waitingCallbacks === null) {
callback(this);
return;
}
this._waitingCallbacks.push(callback);
}
/**
* Return a promise to resolve when ready.
* @returns {Promise} Promise to resolve when ready.
*/
waitForReady()
{
return new Promise((resolve, reject) => {
this.onReady(resolve);
});
}
/**
* Notify all waiting callbacks that this asset is ready.
* @private
*/
_notifyReady()
{
if (this._waitingCallbacks) {
for (let i = 0; i < this._waitingCallbacks.length; ++i) {
this._waitingCallbacks[i](this);
}
this._waitingCallbacks = null;
}
}
/**
* Get asset's URL.
* @returns {String} Asset URL.
*/
get url()
{
return this._url;
}
/**
* Get if this asset is loaded and valid.
* @returns {Boolean} True if asset is loaded and valid, false otherwise.
*/
get valid()
{
throw new Error("Not Implemented!");
}
/**
* Load the asset from it's URL.
* @param {*} params Optional additional params.
* @returns {Promise} Promise to resolve when fully loaded.
*/
load(params)
{
throw new Error("Not Implemented!");
}
/**
* Create the asset from data source.
* @param {*} source Data to create asset from.
* @param {*} params Optional additional params.
* @returns {Promise} Promise to resolve when asset is ready.
*/
create(source)
{
throw new Error("Not Supported for this asset type.");
}
/**
* Destroy the asset, freeing any allocated resources in the process.
*/
destroy()
{
throw new Error("Not Implemented!");
}
} |
JavaScript | class Assets extends IManager
{
/**
* Create the manager.
*/
constructor()
{
super();
this._loaded = null;
this._waitingAssets = new Set();
this._failedAssets = new Set();
this._successfulLoadedAssetsCount = 0;
/**
* Optional URL root to prepend to all loaded assets URLs.
* For example, if all your assets are under '/static/assets/', you can set this url as root and omit it when loading assets later.
*/
this.root = '';
/**
* Optional suffix to add to all loaded assets URLs.
* You can use this for anti-cache mechanism if you want to reload all assets. For example, you can set this value to "'?dt=' + Date.now()".
*/
this.suffix = '';
}
/**
* Wrap a URL with 'root' and 'suffix'.
* @param {String} url Url to wrap.
* @returns {String} Wrapped URL.
*/
_wrapUrl(url)
{
if (!url) { return url; }
return this.root + url + this.suffix;
}
/**
* Get list of assets waiting to be loaded.
* This list will be reset if you call clearCache().
* @returns {Array<string>} URLs of assets waiting to be loaded.
*/
get pendingAssets()
{
return Array.from(this._waitingAssets);
}
/**
* Get list of assets that failed to load.
* This list will be reset if you call clearCache().
* @returns {Array<string>} URLs of assets that had error loading.
*/
get failedAssets()
{
return Array.from(this._failedAssets);
}
/**
* Return a promise that will be resolved only when all pending assets are loaded.
* If an asset fails, will reject.
* @example
* await Shaku.assets.waitForAll();
* console.log("All assets are loaded!");
* @returns {Promise} Promise to resolve when all assets are loaded, or reject if there are failed assets.
*/
waitForAll()
{
return new Promise((resolve, reject) => {
_logger.debug("Waiting for all assets..");
// check if all assets are loaded or if there are errors
let checkAssets = () => {
// got errors?
if (this._failedAssets.size !== 0) {
_logger.warn("Dont waiting for assets: had errors.");
return reject(this.failedAssets);
}
// all done?
if (this._waitingAssets.size === 0) {
_logger.debug("Dont waiting for assets: everything loaded successfully.");
return resolve();
}
// try again in 1 ms
setTimeout(checkAssets, 1);
};
checkAssets();
});
}
/**
* @inheritdoc
* @private
*/
setup()
{
return new Promise((resolve, reject) => {
_logger.info("Setup assets manager..");
this._loaded = {};
resolve();
});
}
/**
* @inheritdoc
* @private
*/
startFrame()
{
}
/**
* @inheritdoc
* @private
*/
endFrame()
{
}
/**
* Get already-loaded asset from cache.
* @private
* @param {String} url Asset URL.
* @param {type} type If provided will make sure asset is of this type. If asset found but have wrong type, will throw exception.
* @returns Loaded asset or null if not found.
*/
_getFromCache(url, type)
{
let cached = this._loaded[url] || null;
if (cached && type) {
if (!(cached instanceof type)) {
throw new Error(`Asset with URL '${url}' is already loaded, but has unexpected type (expecting ${type})!`);
}
}
return cached;
}
/**
* Load an asset of a given type and add to cache when done.
* @private
* @param {Asset} newAsset Asset instance to load.
* @param {*} params Optional loading params.
*/
async _loadAndCacheAsset(newAsset, params)
{
// extract url and typename, and add to cache
let url = newAsset.url;
let typeName = newAsset.constructor.name;
this._loaded[url] = newAsset;
this._waitingAssets.add(url);
// initiate loading
return new Promise(async (resolve, reject) => {
// load asset
_logger.debug(`Load asset [${typeName}] from URL '${url}'.`);
try {
await newAsset.load(params);
}
catch (e) {
_logger.warn(`Failed to load asset [${typeName}] from URL '${url}'.`);
this._failedAssets.add(url);
return reject(e);
}
// update waiting assets count
this._waitingAssets.delete(url);
// make sure valid
if (!newAsset.valid) {
_logger.warn(`Failed to load asset [${typeName}] from URL '${url}'.`);
this._failedAssets.add(url);
return reject("Loaded asset is not valid!");
}
_logger.debug(`Successfully loaded asset [${typeName}] from URL '${url}'.`);
// resolve
this._successfulLoadedAssetsCount++;
resolve(newAsset);
});
}
/**
* Get asset directly from cache, synchronous and without a Promise.
* @param {String} url Asset URL or name.
* @returns {Asset} Asset or null if not loaded.
*/
getCached(url)
{
url = this._wrapUrl(url);
return this._loaded[url] || null;
}
/**
* Get / load asset of given type, and return a promise to be resolved when ready.
* @private
*/
_loadAssetType(url, typeClass, params)
{
// normalize URL
url = this._wrapUrl(url);
// try to get from cache
let _asset = this._getFromCache(url, typeClass);
// check if need to create new and load
var needLoad = false;
if (!_asset) {
_asset = new typeClass(url);
needLoad = true;
}
// create promise to load asset
let promise = new Promise(async (resolve, reject) => {
if (needLoad) {
await this._loadAndCacheAsset(_asset, params);
}
_asset.onReady(() => {
resolve(_asset);
});
});
// return promise with asset attached to it
promise.asset = _asset;
return promise;
}
/**
* Create and init asset of given class type.
* @private
*/
_createAsset(name, classType, initMethod)
{
// create asset
name = this._wrapUrl(name);
var _asset = new classType(name || generateRandomAssetName());
// generate render target in async
let promise = new Promise(async (resolve, reject) => {
// make sure not in cache
if (name && this._loaded[name]) { return reject(`Asset of type '${classType.name}' to create with URL '${name}' already exist in cache!`); }
// create and return
initMethod(_asset);
if (name) { this._loaded[name] = _asset; }
resolve(_asset);
});
// attach asset to promise
promise.asset = _asset;
return promise;
}
/**
* Load a sound asset. If already loaded, will use cache.
* @example
* let sound = await Shaku.assets.loadSound("assets/my_sound.ogg");
* @param {String} url Asset URL.
* @returns {Promise<Asset>} promise to resolve with asset instance, when loaded. You can access the loading asset with `.asset` on the promise.
*/
loadSound(url)
{
return this._loadAssetType(url, SoundAsset, undefined);
}
/**
* Load a texture asset. If already loaded, will use cache.
* @example
* let texture = await Shaku.assets.loadTexture("assets/my_texture.png", {generateMipMaps: false});
* @param {String} url Asset URL.
* @param {*} params Optional params dictionary. See TextureAsset.load() for more details.
* @returns {Promise<Asset>} promise to resolve with asset instance, when loaded. You can access the loading asset with `.asset` on the promise.
*/
loadTexture(url, params)
{
return this._loadAssetType(url, TextureAsset, params);
}
/**
* Create a render target texture asset. If already loaded, will use cache.
* @example
* let width = 512;
* let height = 512;
* let renderTarget = await Shaku.assets.createRenderTarget("optional_render_target_asset_id", width, height);
* @param {String} name Asset name (matched to URLs when using cache). If null, will not add to cache.
* @param {Number} width Texture width.
* @param {Number} height Texture height.
* @param {Number} channels Texture channels count. Defaults to 4 (RGBA).
* @returns {Promise<Asset>} promise to resolve with asset instance, when loaded. You can access the loading asset with `.asset` on the promise.
*/
createRenderTarget(name, width, height, channels)
{
// make sure we have valid size
if (!width || !height) {
throw new Error("Missing or invalid size!");
}
// create asset and return promise
return this._createAsset(name, TextureAsset, (asset) => {
asset.createRenderTarget(width, height, channels);
});
}
/**
* Load a font texture asset. If already loaded, will use cache.
* @example
* let fontTexture = await Shaku.assets.loadFontTexture('assets/DejaVuSansMono.ttf', {fontName: 'DejaVuSansMono'});
* @param {String} url Asset URL.
* @param {*} params Optional params dictionary. See FontTextureAsset.load() for more details.
* @returns {Promise<Asset>} promise to resolve with asset instance, when loaded. You can access the loading asset with `.asset` on the promise.
*/
loadFontTexture(url, params)
{
return this._loadAssetType(url, FontTextureAsset, params);
}
/**
* Load a json asset. If already loaded, will use cache.
* @example
* let jsonData = await Shaku.assets.loadJson('assets/my_json_data.json');
* console.log(jsonData.data);
* @param {String} url Asset URL.
* @returns {Promise<Asset>} promise to resolve with asset instance, when loaded. You can access the loading asset with `.asset` on the promise.
*/
loadJson(url)
{
return this._loadAssetType(url, JsonAsset);
}
/**
* Create a new json asset. If already exist, will reject promise.
* @example
* let jsonData = await Shaku.assets.createJson('optional_json_data_id', {"foo": "bar"});
* // you can now load this asset from anywhere in your code using 'optional_json_data_id' as url
* @param {String} name Asset name (matched to URLs when using cache). If null, will not add to cache.
* @param {Object|String} data Optional starting data.
* @returns {Promise<Asset>} promise to resolve with asset instance, when ready. You can access the loading asset with `.asset` on the promise.
*/
createJson(name, data)
{
// make sure we have valid data
if (!data) {
return reject("Missing or invalid data!");
}
// create asset and return promise
return this._createAsset(name, JsonAsset, (asset) => {
asset.create(data);
});
}
/**
* Load a binary data asset. If already loaded, will use cache.
* @example
* let binData = await Shaku.assets.loadBinary('assets/my_bin_data.dat');
* console.log(binData.data);
* @param {String} url Asset URL.
* @returns {Promise<Asset>} promise to resolve with asset instance, when loaded. You can access the loading asset with `.asset` on the promise.
*/
loadBinary(url)
{
return this._loadAssetType(url, BinaryAsset);
}
/**
* Create a new binary asset. If already exist, will reject promise.
* @example
* let binData = await Shaku.assets.createBinary('optional_bin_data_id', [1,2,3,4]);
* // you can now load this asset from anywhere in your code using 'optional_bin_data_id' as url
* @param {String} name Asset name (matched to URLs when using cache). If null, will not add to cache.
* @param {Array<Number>|Uint8Array} data Binary data to set.
* @returns {Promise<Asset>} promise to resolve with asset instance, when ready. You can access the loading asset with `.asset` on the promise.
*/
createBinary(name, data)
{
// make sure we have valid data
if (!data) {
return reject("Missing or invalid data!");
}
// create asset and return promise
return this._createAsset(name, BinaryAsset, (asset) => {
asset.create(data);
});
}
/**
* Destroy and free asset from cache.
* @example
* Shaku.assets.free("my_asset_url");
* @param {String} url Asset URL to free.
*/
free(url)
{
url = this._wrapUrl(url);
let asset = this._loaded[url];
if (asset) {
asset.destroy();
delete this._loaded[url];
}
}
/**
* Free all loaded assets from cache.
* @example
* Shaku.assets.clearCache();
*/
clearCache()
{
for (let key in this._loaded) {
this._loaded[key].destroy();
}
this._loaded = {};
this._waitingAssets = new Set();
this._failedAssets = new Set();
}
/**
* @inheritdoc
* @private
*/
destroy()
{
this.clearCache();
}
} |
JavaScript | class BinaryAsset extends Asset
{
/** @inheritdoc */
constructor(url)
{
super(url);
this._data = null;
}
/**
* Load the binary data from the asset URL.
* @returns {Promise} Promise to resolve when fully loaded.
*/
load()
{
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
request.open('GET', this.url, true);
request.responseType = 'arraybuffer';
// on load, validate audio content
request.onload = () =>
{
if (request.readyState == 4) {
if (request.response) {
this._data = new Uint8Array(request.response);
this._notifyReady();
resolve();
}
else {
reject(request.statusText);
}
}
}
// on load error, reject
request.onerror = (e) => {
reject(e);
}
// initiate request
request.send();
});
}
/**
* Create the binary data asset from array or Uint8Array.
* @param {Array<Number>|Uint8Array} source Data to create asset from.
* @returns {Promise} Promise to resolve when asset is ready.
*/
create(source)
{
return new Promise((resolve, reject) => {
if (source instanceof Array) { source = new Uint8Array(source); }
if (!(source instanceof Uint8Array)) { return reject("Binary asset source must be of type 'Uint8Array'!"); }
this._data = source;
this._notifyReady();
resolve();
});
}
/** @inheritdoc */
get valid()
{
return Boolean(this._data);
}
/** @inheritdoc */
destroy()
{
this._data = null;
}
/**
* Get binary data.
* @returns {Uint8Array} Data as bytes array.
*/
get data()
{
return this._data;
}
/**
* Convert and return data as string.
* @returns {String} Data converted to string.
*/
string()
{
return (new TextDecoder()).decode(this._data);
}
} |
JavaScript | class FontTextureAsset extends Asset
{
/** @inheritdoc */
constructor(url)
{
super(url);
this._fontName = null;
this._fontSize = null;
this._placeholderChar = null;
this._sourceRects = null;
this._texture = null;
this._lineHeight = 0;
}
/**
* Get line height.
*/
get lineHeight()
{
return this._lineHeight;
}
/**
* Get font name.
*/
get fontName()
{
return this._fontName;
}
/**
* Get font size.
*/
get fontSize()
{
return this._fontSize;
}
/**
* Get placeholder character.
*/
get placeholderCharacter()
{
return this._placeholderChar;
}
/**
* Get the texture.
*/
get texture()
{
return this._texture;
}
/**
* Generate the font texture from a font found in given URL.
* @param {*} params Additional params. Possible values are:
* - fontName: mandatory font name. on some browsers if the font name does not match the font you actually load via the URL, it will not be loaded properly.
* - missingCharPlaceholder (default='?'): character to use for missing characters.
* - smoothFont (default=true): if true, will set font to smooth mode.
* - fontSize (default=52): font size in texture. larget font size will take more memory, but allow for sharper text rendering in larger scales.
* - enforceTexturePowerOfTwo (default=true): if true, will force texture size to be power of two.
* - maxTextureWidth (default=1024): max texture width.
* - charactersSet (default=FontTextureAsset.defaultCharactersSet): which characters to set in the texture.
* - extraPadding (default=0,0): Optional extra padding to add around characters in texture.
* @returns {Promise} Promise to resolve when fully loaded.
*/
load(params)
{
return new Promise(async (resolve, reject) => {
if (!params || !params.fontName) {
return reject("When loading font texture you must provide params with a 'fontName' value!");
}
// set default missing char placeholder + store it
this._placeholderChar = (params.missingCharPlaceholder || '?')[0];
// set smoothing mode
let smooth = params.smoothFont === undefined ? true : params.smoothFont;
// set extra margins
let extraPadding = params.extraPadding || {x: 0, y: 0};
// set max texture size
let maxTextureWidth = params.maxTextureWidth || 1024;
// default chars set
let charsSet = params.charactersSet || FontTextureAsset.defaultCharactersSet;
// make sure charSet got the placeholder char
if (charsSet.indexOf(this._placeholderChar) === -1) {
charsSet += this._placeholderChar;
}
// load font
let fontFace = new FontFace(params.fontName, `url(${this.url})`);
await fontFace.load();
document.fonts.add(fontFace);
// store font name and size
this._fontName = params.fontName;
this._fontSize = params.fontSize || 52;
let margin = {x: 10, y: 5};
// measure font height
let fontFullName = this.fontSize.toString() + 'px ' + this.fontName;
let fontHeight = measureTextHeight(this.fontName, this.fontSize, undefined, extraPadding.y);
let fontWidth = measureTextWidth(this.fontName, this.fontSize, undefined, extraPadding.x);
// set line height
this._lineHeight = fontHeight;
// calc estimated size of a single character in texture
let estimatedCharSizeInTexture = new Vector2(fontWidth + margin.x * 2, fontHeight + margin.y * 2);
// calc texture size
let charsPerRow = Math.floor(maxTextureWidth / estimatedCharSizeInTexture.x);
let textureWidth = Math.min(charsSet.length * estimatedCharSizeInTexture.x, maxTextureWidth);
let textureHeight = Math.ceil(charsSet.length / charsPerRow) * (estimatedCharSizeInTexture.y);
// make width and height powers of two
if (params.enforceTexturePowerOfTwo || params.enforceTexturePowerOfTwo === undefined) {
textureWidth = makePowerTwo(textureWidth);
textureHeight = makePowerTwo(textureHeight);
}
// a dictionary to store the source rect of every character
this._sourceRects = {};
// create a canvas to generate the texture on
let canvas = document.createElement('canvas');
canvas.width = textureWidth;
canvas.height = textureHeight;
if (!smooth) {
canvas.style.webkitFontSmoothing = "none";
canvas.style.fontSmooth = "never";
canvas.style.textRendering = "geometricPrecision";
}
let ctx = canvas.getContext('2d');
// set font and white color
ctx.font = fontFullName;
ctx.fillStyle = '#ffffffff';
ctx.imageSmoothingEnabled = smooth;
// draw the font texture
let x = 0; let y = 0;
for (let i = 0; i < charsSet.length; ++i) {
// get actual width of current character
let currChar = charsSet[i];
let currCharWidth = Math.ceil(ctx.measureText(currChar).width + extraPadding.x);
// check if need to break line down in texture
if (x + currCharWidth > textureWidth) {
y += Math.round(fontHeight + margin.y);
x = 0;
}
// calc source rect
let sourceRect = new Rectangle(x, y + Math.round(fontHeight / 4), currCharWidth, fontHeight);
this._sourceRects[currChar] = sourceRect;
// draw character
ctx.fillText(currChar, x, y + fontHeight);
// move to next spot in texture
x += Math.round(currCharWidth + margin.x);
}
// do threshold effect
if (!smooth) {
let imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
let data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
if (data[i+3] > 0 && (data[i+3] < 255 || data[i] < 255 || data[i+1] < 255 || data[i+2] < 255)) {
data[i + 3] = 0;
}
}
ctx.putImageData(imageData, 0, 0);
}
// convert canvas to image
let img = new Image();
img.src = canvas.toDataURL("image/png");
img.onload = () => {
// convert image to texture
let texture = new TextureAsset(this.url + '__font-texture');
texture.fromImage(img);
// success!
this._texture = texture;
this._notifyReady();
resolve();
};
});
}
/** @inheritdoc */
get valid()
{
return Boolean(this._texture);
}
/**
* Get the source rectangle for a given character in texture.
* @param {Character} character Character to get source rect for.
* @returns {Rectangle} Source rectangle for character.
*/
getSourceRect(character)
{
return this._sourceRects[character] || this._sourceRects[this.placeholderCharacter];
}
/** @inheritdoc */
destroy()
{
if (this._texture) this._texture.destroy();
this._fontName = null;
this._fontSize = null;
this._placeholderChar = null;
this._sourceRects = null;
this._texture = null;
this._lineHeight = 0;
}
} |
JavaScript | class JsonAsset extends Asset
{
/** @inheritdoc */
constructor(url)
{
super(url);
this._data = null;
}
/**
* Load the JSON data from the asset URL.
* @returns {Promise} Promise to resolve when fully loaded.
*/
load()
{
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
request.open('GET', this.url, true);
request.responseType = 'json';
// on load, validate audio content
request.onload = () =>
{
if (request.readyState == 4) {
if (request.response) {
this._data = request.response;
this._notifyReady();
resolve();
}
else {
if (request.status === 200) {
reject("Response is not a valid JSON!");
}
else {
reject(request.statusText);
}
}
}
}
// on load error, reject
request.onerror = (e) => {
reject(e);
}
// initiate request
request.send();
});
}
/**
* Create the JSON data asset from object or string.
* @param {Object|String} source Data to create asset from.
* @returns {Promise} Promise to resolve when asset is ready.
*/
create(source)
{
return new Promise((resolve, reject) => {
// make sure data is a valid json + clone it
try
{
if (source) {
if (typeof source === 'string') {
source = JSON.parse(source);
}
else {
source = JSON.parse(JSON.stringify(source));
}
}
else {
source = {};
}
}
catch (e)
{
return reject("Data is not a valid JSON serializable object!");
}
// store data and resolve
this._data = source;
this._notifyReady();
resolve();
});
}
/**
* Get json data.
* @returns {*} Data as dictionary.
*/
get data()
{
return this._data;
}
/** @inheritdoc */
get valid()
{
return Boolean(this._data);
}
/** @inheritdoc */
destroy()
{
this._data = null;
}
} |
JavaScript | class SoundAsset extends Asset
{
/** @inheritdoc */
constructor(url)
{
super(url);
this._valid = false;
}
/**
* Load the sound asset from its URL.
* Note that loading sounds isn't actually necessary to play sounds, this method merely pre-load the asset (so first time we play
* the sound would be immediate and not delayed) and validate the data is valid.
* @returns {Promise} Promise to resolve when fully loaded.
*/
load()
{
// for audio files we force preload and validation of the audio file.
// note: we can't use the Audio object as it won't work without page interaction.
return new Promise((resolve, reject) => {
// create request to load audio file
let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var request = new XMLHttpRequest();
request.open('GET', this.url, true);
request.responseType = 'arraybuffer';
// on load, validate audio content
request.onload = () =>
{
var audioData = request.response;
this._valid = true; // <-- good enough for now, as decodeAudio won't work before user's input
this._notifyReady();
audioCtx.decodeAudioData(audioData, function(buffer) {
resolve();
},
(e) => {
reject(e.err);
});
}
// on load error, reject
request.onerror = (e) => {
reject(e);
}
// initiate request
request.send();
});
}
/** @inheritdoc */
get valid()
{
return this._valid;
}
/** @inheritdoc */
destroy()
{
this._valid = false;
}
} |
JavaScript | class TextureAsset extends Asset
{
/** @inheritdoc */
constructor(url)
{
super(url);
this._image = null;
this._width = 0;
this._height = 0;
this._texture = null;
this._filter = null;
this._wrapMode = null;
this._ctxForPixelData = null;
}
/**
* Set the WebGL context.
* @private
*/
static _setWebGl(_gl)
{
gl = _gl;
}
/**
* Get texture magnifying filter, or null to use default.
* @see Shaku.gfx.TextureFilterModes
*/
get filter()
{
return this._filter;
}
/**
* Set texture magnifying filter.
* @see Shaku.gfx.TextureFilterModes
* @param {TextureFilterModes} value Filter mode to use or null to use default.
*/
set filter(value)
{
this._filter = value;
}
/**
* Get texture wrapping mode, or null to use default.
* @see Shaku.gfx.TextureWrapModes
*/
get wrapMode()
{
return this._wrapMode;
}
/**
* Set texture wrapping mode.
* @see Shaku.gfx.TextureWrapModes
* @param {TextureWrapModes} value Wrapping mode to use or null to use default.
*/
set wrapMode(value)
{
this._wrapMode = value;
}
/**
* Load the texture from it's image URL.
* @param {*} params Optional additional params. Possible values are:
* - generateMipMaps (default=false): should we generate mipmaps for this texture?
* @returns {Promise} Promise to resolve when fully loaded.
*/
load(params)
{
// default params
params = params || {};
return new Promise((resolve, reject) => {
if (!gl) {
return reject("Can't load textures before initializing gfx manager!");
}
// create image to load
const image = new Image();
image.onload = async () =>
{
try {
await this.create(image, params);
this._notifyReady();
resolve();
}
catch (e) {
reject(e);
}
};
image.onerror = () => {
reject("Failed to load texture image!");
}
// initiate image load
image.src = this.url;
});
}
/**
* Create this texture as an empty render target.
* @param {Number} width Texture width.
* @param {Number} height Texture height.
* @param {Number} channels Texture channels count. Defaults to 4 (RGBA).
*/
createRenderTarget(width, height, channels)
{
// create to render to
const targetTextureWidth = width;
const targetTextureHeight = height;
const targetTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, targetTexture);
// calculate format
var _format = gl.RGBA;
if (channels !== undefined) {
switch (channels) {
case 1:
_format = gl.LUMINANCE;
break;
case 3:
_format = gl.RGB;
break;
case 4:
_format = gl.RGBA;
break;
default:
throw new Error("Unknown render target format!");
}
}
{
// create texture
const level = 0;
const internalFormat = _format;
const border = 0;
const format = _format;
const type = gl.UNSIGNED_BYTE;
const data = null;
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
targetTextureWidth, targetTextureHeight, border,
format, type, data);
// set default wrap and filter modes
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
// store texture
this._width = width;
this._height = height;
this._texture = targetTexture;
this._notifyReady();
}
/**
* Create texture from loaded image instance.
* @see TextureAsset.load for params.
* @param {Image} image Image to create texture from. Image must be loaded!
* @param {*} params Optional additional params. See load() for details.
*/
fromImage(image, params)
{
if (image.width === 0) {
throw new Error("Image to build texture from must be loaded and have valid size!");
}
if (this.valid) {
throw new Error("Texture asset is already initialized!");
}
// default params
params = params || {};
// store image
this._image = image;
this._width = image.width;
this._height = image.height;
// create texture
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// set texture
const level = 0;
const internalFormat = gl.RGBA;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, srcFormat, srcType, image);
// WebGL1 has different requirements for power of 2 images
// vs non power of 2 images so check if the image is a
// power of 2 in both dimensions.
if (params.generateMipMaps) {
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
_logger.warn("Tried to generate MipMaps for a texture with size that is *not* a power of two. This might not work as expected.");
}
gl.generateMipmap(gl.TEXTURE_2D);
}
// default wrap and filters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
// success!
this._texture = texture;
this._notifyReady();
}
/**
* Create the texture from an image.
* @see TextureAsset.load for params.
* @param {Image|String} source Image or Image source URL to create texture from.
* @param {*} params Optional additional params. See load() for details.
* @returns {Promise} Promise to resolve when asset is ready.
*/
create(source, params)
{
return new Promise(async (resolve, reject) => {
if (typeof source === "string") {
let img = new Image();
img.onload = () => {
this.fromImage(source, params);
this._notifyReady();
resolve();
}
img.src = source;
}
else {
this.fromImage(source, params);
resolve();
}
});
}
/**
* Get raw image.
* @returns {Image} Image instance.
*/
get image()
{
return this._image;
}
/**
* Get texture width.
* @returns {Number} Texture width.
*/
get width()
{
return this._width;
}
/**
* Get texture height.
* @returns {Number} Texture height.
*/
get height()
{
return this._height;
}
/**
* Get texture size as a vector.
* @returns {Vector2} Texture size.
*/
get size()
{
return new Vector2(this.width, this.height);
}
/**
* Get texture instance for WebGL.
*/
get texture()
{
return this._texture;
}
/**
* Get pixel color from image.
* @param {Number} x Pixel X value.
* @param {Number} y Pixel Y value.
* @returns {Color} Pixel color.
*/
getPixel(x, y)
{
if (!this._image) {
throw new Error("'getPixel()' only works on textures loaded from image!");
}
// build internal canvas and context to get pixel data
if (!this._ctxForPixelData) {
let canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
this._ctxForPixelData = canvas.getContext('2d');
}
// get pixel data
let ctx = this._ctxForPixelData;
ctx.drawImage(this._image, x, y, 1, 1, 0, 0, 1, 1);
let pixelData = ctx.getImageData(0, 0, 1, 1).data;
return Color.fromBytesArray(pixelData);
}
/** @inheritdoc */
get valid()
{
return Boolean(this._texture);
}
/** @inheritdoc */
destroy()
{
gl.deleteTexture(this._texture);
this._image = null;
this._width = this._height = 0;
this._ctxForPixelData = null;
this._texture = null;
}
} |
JavaScript | class Collision extends IManager
{
/**
* Create the manager.
*/
constructor()
{
super();
/**
* The collision resolver we use to detect collision between different shapes.
* You can use this object directly without creating a collision world, if you just need to test collision between shapes.
*/
this.resolver = new CollisionResolver();
}
/**
* @inheritdoc
* @private
**/
setup()
{
return new Promise((resolve, reject) => {
_logger.info("Setup collision manager..");
this.resolver._init();
this.resolver.setHandler(PointShape, PointShape, ResolverImp.pointPoint);
this.resolver.setHandler(PointShape, CircleShape, ResolverImp.pointCircle);
this.resolver.setHandler(PointShape, RectangleShape, ResolverImp.pointRectangle);
this.resolver.setHandler(PointShape, LinesShape, ResolverImp.pointLine);
this.resolver.setHandler(PointShape, TilemapShape, ResolverImp.pointTilemap);
this.resolver.setHandler(CircleShape, CircleShape, ResolverImp.circleCircle);
this.resolver.setHandler(CircleShape, RectangleShape, ResolverImp.circleRectangle);
this.resolver.setHandler(CircleShape, LinesShape, ResolverImp.circleLine);
this.resolver.setHandler(CircleShape, TilemapShape, ResolverImp.circleTilemap);
this.resolver.setHandler(RectangleShape, RectangleShape, ResolverImp.rectangleRectangle);
this.resolver.setHandler(RectangleShape, LinesShape, ResolverImp.rectangleLine);
this.resolver.setHandler(RectangleShape, TilemapShape, ResolverImp.rectangleTilemap);
this.resolver.setHandler(LinesShape, LinesShape, ResolverImp.lineLine);
this.resolver.setHandler(LinesShape, TilemapShape, ResolverImp.lineTilemap);
resolve();
});
}
/**
* Create a new collision world object.
* @param {Number|Vector2} gridCellSize Collision world grid cell size.
* @returns {CollisionWorld} Newly created collision world.
*/
createWorld(gridCellSize)
{
return new CollisionWorld(this.resolver, gridCellSize);
}
/**
* Get the collision reactanle shape class.
*/
get RectangleShape()
{
return RectangleShape
}
/**
* Get the collision point shape class.
*/
get PointShape()
{
return PointShape;
}
/**
* Get the collision circle shape class.
*/
get CircleShape()
{
return CircleShape;
}
/**
* Get the collision lines shape class.
*/
get LinesShape()
{
return LinesShape;
}
/**
* Get the tilemap collision shape class.
*/
get TilemapShape()
{
return TilemapShape;
}
/**
* @inheritdoc
* @private
**/
startFrame()
{
}
/**
* @inheritdoc
* @private
**/
endFrame()
{
}
/**
* @inheritdoc
* @private
**/
destroy()
{
}
} |
JavaScript | class CollisionWorld
{
/**
* Create the collision world.
* @param {CollisionResolver} resolver Collision resolver to use for this world.
* @param {Number|Vector2} gridCellSize For optimize collision testing, the collision world is divided into a collision grid. This param determine the grid cell size.
*/
constructor(resolver, gridCellSize)
{
/**
* Collision resolver used in this collision world.
* By default, will inherit the collision manager default resolver.
*/
this.resolver = resolver;
// set grid cell size
if (typeof gridCellSize === 'undefined') { gridCellSize = new Vector2(512, 512); }
else if (typeof gridCellSize === 'number') { gridCellSize = new Vector2(gridCellSize, gridCellSize); }
else { gridCellSize = gridCellSize.clone(); }
this._gridCellSize = gridCellSize;
// create collision grid
this._grid = {};
// shapes that need updates and grid chunks to delete
this._shapesToUpdate = new Set();
this._cellsToDelete = new Set();
}
/**
* Do collision world updates, if we have any.
* @private
*/
_performUpdates()
{
// delete empty grid cells
if (this._cellsToDelete.size > 0) {
for (let key of this._cellsToDelete) {
if (this._grid[key] && this._grid[key].size === 0) {
delete this._grid[key];
}
}
this._cellsToDelete.clear();
}
// update all shapes
if (this._shapesToUpdate.size > 0) {
for (let shape of this._shapesToUpdate) {
this._updateShape(shape);
}
this._shapesToUpdate.clear();
}
}
/**
* Update a shape in collision world after it moved or changed.
* @private
*/
_updateShape(shape)
{
// sanity - if no longer in this collision world, skip
if (shape._world !== this) {
return;
}
// get new range
let bb = shape._getBoundingBox();
let minx = Math.floor(bb.left / this._gridCellSize.x);
let miny = Math.floor(bb.top / this._gridCellSize.y);
let maxx = Math.ceil(bb.right / this._gridCellSize.x);
let maxy = Math.ceil(bb.bottom / this._gridCellSize.y);
// change existing grid cells
if (shape._worldRange)
{
// range is the same? skip
if (shape._worldRange[0] === minx &&
shape._worldRange[1] === miny &&
shape._worldRange[2] === maxx &&
shape._worldRange[3] === maxy) {
return;
}
// get old range
let ominx = shape._worldRange[0];
let ominy = shape._worldRange[1];
let omaxx = shape._worldRange[2];
let omaxy = shape._worldRange[3];
// first remove from old chunks we don't need
for (let i = ominx; i < omaxx; ++i) {
for (let j = ominy; j < omaxy; ++j) {
// if also in new range, don't remove
if (i >= minx && i < maxx && j >= miny && j < maxy) {
continue;
}
// remove from cell
let key = i + ',' + j;
let currSet = this._grid[key];
if (currSet) {
currSet.delete(shape);
if (currSet.size === 0) {
this._cellsToDelete.add(key);
}
}
}
}
// now add to new cells
for (let i = minx; i < maxx; ++i) {
for (let j = miny; j < maxy; ++j) {
// if was in old range, don't add
if (i >= ominx && i < omaxx && j >= ominy && j < omaxy) {
continue;
}
// add to new cell
let key = i + ',' + j;
let currSet = this._grid[key];
if (!currSet) {
this._grid[key] = currSet = new Set();
}
currSet.add(shape);
}
}
}
// first-time adding to grid
else {
for (let i = minx; i < maxx; ++i) {
for (let j = miny; j < maxy; ++j) {
let key = i + ',' + j;
let currSet = this._grid[key];
if (!currSet) {
this._grid[key] = currSet = new Set();
}
currSet.add(shape);
}
}
}
// update new range
shape._worldRange = [minx, miny, maxx, maxy];
}
/**
* Request update for this shape on next updates call.
* @private
*/
_queueUpdate(shape)
{
this._shapesToUpdate.add(shape);
}
/**
* Iterate all shapes in world.
* @param {Function} callback Callback to invoke on all shapes. Return false to break iteration.
*/
iterateShapes(callback)
{
for (let key in this._grid) {
let cell = this._grid[key];
if (cell) {
for (let shape of cell)
{
if (callback(shape) === false) {
return;
}
}
}
}
}
/**
* Add a collision shape to this world.
* @param {CollisionShape} shape Shape to add.
*/
addShape(shape)
{
// add shape
shape._setParent(this);
// add shape to grid
this._updateShape(shape);
// do general updates
this._performUpdates();
}
/**
* Remove a collision shape from this world.
* @param {CollisionShape} shape Shape to remove.
*/
removeShape(shape)
{
// sanity
if (shape._world !== this) {
_logger.warn("Shape to remove is not in this collision world!");
return;
}
// remove from grid
if (shape._worldRange) {
let minx = shape._worldRange[0];
let miny = shape._worldRange[1];
let maxx = shape._worldRange[2];
let maxy = shape._worldRange[3];
for (let i = minx; i < maxx; ++i) {
for (let j = miny; j < maxy; ++j) {
let key = i + ',' + j;
let currSet = this._grid[key];
if (currSet) {
currSet.delete(shape);
if (currSet.size === 0) {
this._cellsToDelete.add(key);
}
}
}
}
}
// remove shape
this._shapesToUpdate.delete(shape);
shape._setParent(null);
// do general updates
this._performUpdates();
}
/**
* Iterate shapes that match broad phase test.
* @private
* @param {CollisionShape} shape Shape to test.
* @param {Function} handler Method to run on all shapes in phase. Return true to continue iteration, false to break.
* @param {Number} mask Optional mask of bits to match against shapes collisionFlags. Will only return shapes that have at least one common bit.
* @param {Function} predicate Optional filter to run on any shape we're about to test collision with.
*/
_iterateBroadPhase(shape, handler, mask, predicate)
{
// get grid range
let bb = shape._getBoundingBox();
let minx = Math.floor(bb.left / this._gridCellSize.x);
let miny = Math.floor(bb.top / this._gridCellSize.y);
let maxx = Math.ceil(bb.right / this._gridCellSize.x);
let maxy = Math.ceil(bb.bottom / this._gridCellSize.y);
// shapes we checked
let checked = new Set();
// iterate options
for (let i = minx; i < maxx; ++i) {
for (let j = miny; j < maxy; ++j) {
// get current grid chunk
let key = i + ',' + j;
let currSet = this._grid[key];
// iterate shapes in grid chunk
if (currSet) {
for (let other of currSet) {
// check collision flags
if (mask && ((other.collisionFlags & mask) === 0)) {
continue;
}
// skip if checked
if (checked.has(other)) {
continue;
}
checked.add(other);
// skip self
if (other === shape) {
continue;
}
// use predicate
if (predicate && !predicate(other)) {
continue;
}
// invoke handler on shape
let proceedLoop = Boolean(handler(other));
// break loop
if (!proceedLoop) {
return;
}
}
}
}
}
}
/**
* Test collision with shapes in world, and return just the first result found.
* @param {CollisionShape} sourceShape Source shape to check collision for. If shape is in world, it will not collide with itself.
* @param {Boolean} sortByDistance If true will return the nearest collision found (based on center of shapes).
* @param {Number} mask Optional mask of bits to match against shapes collisionFlags. Will only return shapes that have at least one common bit.
* @param {Function} predicate Optional filter to run on any shape we're about to test collision with. If the predicate returns false, we will skip this shape.
* @returns {CollisionTestResult} A collision test result, or null if not found.
*/
testCollision(sourceShape, sortByDistance, mask, predicate)
{
// do updates before check
this._performUpdates();
// result to return
var result = null;
// hard case - single result, sorted by distance
if (sortByDistance)
{
// build options array
var options = [];
this._iterateBroadPhase(sourceShape, (other) => {
options.push(other);
return true;
}, mask, predicate);
// sort options
sortByDistanceShapes(sourceShape, options);
// check collision sorted
for (let i = 0; i < options.length; ++i) {
result = this.resolver.test(sourceShape, options[i]);
if (result) {
break;
}
}
}
// easy case - single result, not sorted
else
{
// iterate possible shapes and test collision
this._iterateBroadPhase(sourceShape, (other) => {
// test collision and continue iterating if we don't have a result
result = this.resolver.test(sourceShape, other);
return !result;
}, mask, predicate);
}
// return result
return result;
}
/**
* Test collision with shapes in world, and return all results found.
* @param {CollisionShape} sourceShape Source shape to check collision for. If shape is in world, it will not collide with itself.
* @param {Boolean} sortByDistance If true will sort results by distance.
* @param {Number} mask Optional mask of bits to match against shapes collisionFlags. Will only return shapes that have at least one common bit.
* @param {Function} predicate Optional filter to run on any shape we're about to test collision with. If the predicate returns false, we will skip this shape.
* @param {Function} intermediateProcessor Optional method to run after each positive result with the collision result as param. Return false to stop and return results.
* @returns {Array<CollisionTestResult>} An array of collision test results, or empty array if none found.
*/
testCollisionMany(sourceShape, sortByDistance, mask, predicate, intermediateProcessor)
{
// do updates before check
this._performUpdates();
// get collisions
var ret = [];
this._iterateBroadPhase(sourceShape, (other) => {
let result = this.resolver.test(sourceShape, other);
if (result) {
ret.push(result);
if (intermediateProcessor && intermediateProcessor(result) === false) {
return false;
}
}
return true;
}, mask, predicate);
// sort by distance
if (sortByDistance) {
sortByDistanceResults(sourceShape, ret);
}
// return results
return ret;
}
/**
* Return array of shapes that touch a given position, with optional radius.
* @example
* let shapes = world.pick(Shaku.input.mousePosition);
* @param {*} position Position to pick.
* @param {*} radius Optional picking radius to use a circle instead of a point.
* @param {*} sortByDistance If true, will sort results by distance from point.
* @param {*} mask Collision mask to filter by.
* @param {*} predicate Optional predicate method to filter by.
* @returns {Array<CollisionShape>} Array with collision shapes we picked.
*/
pick(position, radius, sortByDistance, mask, predicate)
{
let shape = ((radius || 0) <= 1) ? new PointShape(position) : new CircleShape(new Circle(position, radius));
let ret = this.testCollisionMany(shape, sortByDistance, mask, predicate);
return ret.map(x => x.second);
}
/**
* Debug-draw the current collision world.
* @param {Color} gridColor Optional grid color (default to black).
* @param {Color} gridHighlitColor Optional grid color for cells with shapes in them (default to red).
* @param {Number} opacity Optional opacity factor (default to 0.5).
* @param {Camera} camera Optional camera for offset and viewport.
*/
debugDraw(gridColor, gridHighlitColor, opacity, camera)
{
// do updates before check
this._performUpdates();
// default grid colors
if (!gridColor) {
gridColor = Color.black;
gridColor.a *= 0.75;
}
if (!gridHighlitColor) {
gridHighlitColor = Color.red;
gridHighlitColor.a *= 0.75;
}
// default opacity
if (opacity === undefined) {
opacity = 0.5;
}
// set grid color opacity
gridColor.a *= opacity;
gridHighlitColor.a *= opacity;
// all shapes we rendered
let renderedShapes = new Set();
// get visible grid cells
let bb = camera ? camera.getRegion() : gfx.getRenderingRegion(false);
let minx = Math.floor(bb.left / this._gridCellSize.x);
let miny = Math.floor(bb.top / this._gridCellSize.y);
let maxx = minx + Math.ceil(bb.width / this._gridCellSize.x);
let maxy = miny + Math.ceil(bb.height / this._gridCellSize.y);
for (let i = minx; i <= maxx; ++i) {
for (let j = miny; j <= maxy; ++j) {
// get current cell
let cell = this._grid[i + ',' + j];
// draw grid cell
let color = (cell && cell.size) ? gridHighlitColor : gridColor;
let cellRect = new Rectangle(i * this._gridCellSize.x, j * this._gridCellSize.y, this._gridCellSize.x-1, this._gridCellSize.y-1);
gfx.outlineRect(cellRect, color, gfx.BlendModes.AlphaBlend, 0);
// draw shapes in grid
if (cell) {
for (let shape of cell)
{
if (renderedShapes.has(shape)) {
continue;
}
renderedShapes.add(shape);
shape.debugDraw(opacity);
}
}
}
}
}
} |
JavaScript | class CollisionResolver
{
/**
* Create the resolver.
*/
constructor()
{
this._handlers = {};
}
/**
* Initialize the resolver.
* @private
*/
_init()
{
}
/**
* Set the method used to test collision between two shapes.
* Note: you don't need to register the same handler twice for reverse order, its done automatically inside.
* @param {Class} firstShapeClass The shape type the handler recieves as first argument.
* @param {Class} secondShapeClass The shape type the handler recieves as second argument.
* @param {Function} handler Method to test collision between the shapes. Return false if don't collide, return either Vector2 with collision position or 'true' for collision.
*/
setHandler(firstShapeClass, secondShapeClass, handler)
{
_logger.debug(`Register handler for shapes '${firstShapeClass.name}' and '${secondShapeClass.name}'.`);
// register handler
if (!this._handlers[firstShapeClass.name]) { this._handlers[firstShapeClass.name] = {}; }
this._handlers[firstShapeClass.name][secondShapeClass.name] = handler;
// register reverse order handler
if (firstShapeClass !== secondShapeClass) {
if (!this._handlers[secondShapeClass.name]) { this._handlers[secondShapeClass.name] = {}; }
this._handlers[secondShapeClass.name][firstShapeClass.name] = (f, s) => { return handler(s, f); };
}
}
/**
* Check a collision between two shapes.
* @param {CollisionShape} first First collision shape to test.
* @param {CollisionShape} second Second collision shape to test.
* @returns {CollisionTestResult} collision detection result or null if they don't collide.
*/
test(first, second)
{
// get method and make sure we got a handler
let handler = this._getCollisionMethod(first, second);
if (!handler) {
_logger.warn(`Missing collision handler for shapes '${first.constructor.name}' and '${second.constructor.name}'.`);
return null;
}
// test collision
let result = handler(first, second);
// collision
if (result) {
let position = (result instanceof Vector2) ? result : null;
return new CollisionTestResult(position, first, second);
}
// no collision
return null;
}
/**
* Get the collision detection method for two given shapes.
* @private
* @param {CollisionShape} first First collision shape to test.
* @param {CollisionShape} second Second collision shape to test.
* @returns {Function} collision detection method or null if not found.
*/
_getCollisionMethod(first, second)
{
if (this._handlers[first.constructor.name]) {
return this._handlers[first.constructor.name][second.constructor.name] || null;
}
return null;
}
} |
JavaScript | class CollisionTestResult
{
/**
* Create the collision result.
* @param {Vector2} position Optional collision position.
* @param {CollisionShape} first First shape in the collision check.
* @param {CollisionShape} second Second shape in the collision check.
*/
constructor(position, first, second)
{
/**
* Collision position, only relevant when there's a single touching point.
* For shapes with multiple touching points, this will be null.
*/
this.position = position;
/**
* First collided shape.
*/
this.first = first;
/**
* Second collided shape.
*/
this.second = second;
}
} |
JavaScript | class CircleShape extends CollisionShape
{
/**
* Create the collision shape.
* @param {Circle} circle the circle shape.
*/
constructor(circle)
{
super();
this.setShape(circle);
}
/**
* Set this collision shape from circle.
* @param {Circle} circle Circle shape.
*/
setShape(circle)
{
this._circle = circle;
this._position = circle.center;
this._boundingBox = new Rectangle(circle.center.x - circle.radius, circle.center.y - circle.radius, circle.radius * 2, circle.radius * 2);
this._shapeChanged();
}
/**
* @inheritdoc
*/
_getRadius()
{
return this._circle.radius;
}
/**
* @inheritdoc
*/
getCenter()
{
return this._position.clone();
}
/**
* @inheritdoc
*/
_getBoundingBox()
{
return this._boundingBox;
}
/**
* Debug draw this shape.
* @param {Number} opacity Shape opacity factor.
*/
debugDraw(opacity)
{
if (opacity === undefined) opacity = 1;
let color = this._getDebugColor();
color.a *= opacity;
gfx.outlineCircle(this._circle, color, gfx.BlendModes.AlphaBlend, 14);
color.a *= 0.25;
gfx.fillCircle(this._circle, color, gfx.BlendModes.AlphaBlend, 14);
}
} |
JavaScript | class LinesShape extends CollisionShape
{
/**
* Create the collision shape.
* @param {Array<Line>|Line} lines Starting line / lines.
*/
constructor(lines)
{
super();
this._lines = [];
this.addLines(lines);
}
/**
* Add line or lines to this collision shape.
* @param {Array<Line>|Line} lines Line / lines to add.
*/
addLines(lines)
{
// convert to array
if (!Array.isArray(lines)) {
lines = [lines];
}
// add lines
for (let i = 0; i < lines.length; ++i)
{
this._lines.push(lines[i]);
}
// get all points
let points = [];
for (let i = 0; i < this._lines.length; ++i) {
points.push(this._lines[i].from);
points.push(this._lines[i].to);
}
// reset bounding box and circle
this._boundingBox = Rectangle.fromPoints(points);
this._circle = new Circle(this._boundingBox.getCenter(), Math.max(this._boundingBox.width, this._boundingBox.height));
this._shapeChanged();
}
/**
* Set this shape from line or lines array.
* @param {Array<Line>|Line} lines Line / lines to set.
*/
setLines(lines)
{
this._lines = [];
this.addLines(lines);
}
/**
* @inheritdoc
*/
_getRadius()
{
return this._circle.radius;
}
/**
* @inheritdoc
*/
getCenter()
{
return this._circle.center.clone();
}
/**
* @inheritdoc
*/
_getBoundingBox()
{
return this._boundingBox;
}
/**
* Debug draw this shape.
* @param {Number} opacity Shape opacity factor.
*/
debugDraw(opacity)
{
if (opacity === undefined) opacity = 1;
let color = this._getDebugColor();
color.a *= opacity;
for (let i = 0; i < this._lines.length; ++i) {
gfx.drawLine(this._lines[i].from, this._lines[i].to, color, gfx.BlendModes.AlphaBlend);
}
}
} |
JavaScript | class PointShape extends CollisionShape
{
/**
* Create the collision shape.
* @param {Vector2} position Point position.
*/
constructor(position)
{
super();
this.setPosition(position);
}
/**
* Set this collision shape from vector2.
* @param {Vector2} position Point position.
*/
setPosition(position)
{
this._position = position.clone();
this._boundingBox = new Rectangle(position.x, position.y, 1, 1);
this._shapeChanged();
}
/**
* Get point position.
* @returns {Vector2} Point position.
*/
getPosition()
{
return this._position.clone();
}
/**
* @inheritdoc
*/
getCenter()
{
return this._position.clone();
}
/**
* @inheritdoc
*/
_getRadius()
{
return 1;
}
/**
* @inheritdoc
*/
_getBoundingBox()
{
return this._boundingBox;
}
/**
* Debug draw this shape.
* @param {Number} opacity Shape opacity factor.
*/
debugDraw(opacity)
{
if (opacity === undefined) opacity = 1;
let color = this._getDebugColor();
color.a *= opacity;
gfx.outlineCircle(new Circle(this.getPosition(), 3), color, gfx.BlendModes.AlphaBlend, 4);
}
} |
JavaScript | class RectangleShape extends CollisionShape
{
/**
* Create the collision shape.
* @param {Rectangle} rectangle the rectangle shape.
*/
constructor(rectangle)
{
super();
this.setShape(rectangle);
}
/**
* Set this collision shape from rectangle.
* @param {Rectangle} rectangle Rectangle shape.
*/
setShape(rectangle)
{
this._rect = rectangle;
this._center = rectangle.getCenter();
this._radius = this._rect.getBoundingCircle().radius;
this._shapeChanged();
}
/**
* @inheritdoc
*/
_getRadius()
{
return this._radius;
}
/**
* @inheritdoc
*/
_getBoundingBox()
{
return this._rect;
}
/**
* @inheritdoc
*/
getCenter()
{
return this._center.clone();
}
/**
* Debug draw this shape.
* @param {Number} opacity Shape opacity factor.
*/
debugDraw(opacity)
{
if (opacity === undefined) opacity = 1;
let color = this._getDebugColor();
color.a *= opacity;
gfx.outlineRect(this._rect, color, gfx.BlendModes.AlphaBlend);
color.a *= 0.25;
gfx.fillRect(this._rect, color, gfx.BlendModes.AlphaBlend);
}
} |
JavaScript | class CollisionShape
{
/**
* Create the collision shape.
*/
constructor()
{
this._world = null;
this._worldRange = null;
this._debugColor = null;
this._forceDebugColor = null;
this._collisionFlags = Number.MAX_SAFE_INTEGER;
}
/**
* Get collision flags (matched against collision mask when checking collision).
*/
get collisionFlags()
{
return this._collisionFlags;
}
/**
* Set collision flags (matched against collision mask when checking collision).
*/
set collisionFlags(value)
{
this._debugColor = null;
this._collisionFlags = value;
return this._collisionFlags;
}
/**
* Set the debug color to use to draw this shape.
* @param {Color} color Color to set or null to use default.
*/
setDebugColor(color)
{
this._forceDebugColor = color;
}
/**
* Debug draw this shape.
* @param {Number} opacity Shape opacity factor.
*/
debugDraw(opacity)
{
throw new Error("Not Implemented!");
}
/**
* Get shape center position.
* @returns {Vector2} Center position.
*/
getCenter()
{
throw new Error("Not Implemented!");
}
/**
* Remove self from parent world object.
*/
remove()
{
if (this._world) {
this._world.removeShape(this);
}
}
/**
* Get debug drawing color.
* @private
*/
_getDebugColor()
{
// use forced debug color
if (this._forceDebugColor) {
return this._forceDebugColor.clone();
}
// calculate debug color
if (!this._debugColor) {
this._debugColor = this._getDefaultDebugColorFor(this.collisionFlags);
}
// return color
return this._debugColor.clone();
}
/**
* Get default debug colors for given collision flags.
* @private
*/
_getDefaultDebugColorFor(flags)
{
return defaultDebugColors[flags % defaultDebugColors.length];
}
/**
* Get collision shape's estimated radius box.
* @private
* @returns {Number} Shape's radius
*/
_getRadius()
{
throw new Error("Not Implemented!");
}
/**
* Get collision shape's bounding box.
* @private
* @returns {Rectangle} Shape's bounding box.
*/
_getBoundingBox()
{
throw new Error("Not Implemented!");
}
/**
* Set the parent collision world this shape is currently in.
* @private
* @param {CollisionWorld} world New parent collision world or null to remove.
*/
_setParent(world)
{
// same world? skip
if (world === this._world) {
return;
}
// we already have a world but try to set a new one? error
if (this._world && world) {
throw new Error("Cannot add collision shape to world while its already in another world!");
}
// set new world
this._world = world;
this._worldRange = null;
}
/**
* Called when the collision shape changes and we need to update the parent world.
* @private
*/
_shapeChanged()
{
if (this._world) {
this._world._queueUpdate(this);
}
}
} |
JavaScript | class TilemapShape extends CollisionShape
{
/**
* Create the collision tilemap.
* @param {Vector2} offset Tilemap top-left corner.
* @param {Vector2} gridSize Number of tiles on X and Y axis.
* @param {Vector2} tileSize The size of a single tile.
* @param {Number} borderThickness Set a border collider with this thickness.
*/
constructor(offset, gridSize, tileSize, borderThickness)
{
super();
borderThickness = borderThickness || 0;
this._offset = offset.clone();
this._intBoundingRect = new Rectangle(offset.x, offset.y, gridSize.x * tileSize.x, gridSize.y * tileSize.y);
this._boundingRect = this._intBoundingRect.resize(borderThickness * 2);
this._center = this._boundingRect.getCenter();
this._radius = this._boundingRect.getBoundingCircle().radius;
this._borderThickness = borderThickness;
this._gridSize = gridSize.clone();
this._tileSize = tileSize.clone();
this._tiles = {};
}
/**
* Get tile key from vector index.
* Also validate range.
* @private
* @param {Vector2} index Index to get key for.
* @returns {String} tile key.
*/
_indexToKey(index)
{
if (index.x < 0 || index.y < 0 || index.x >= this._gridSize.x || index.y >= this._gridSize.y) {
throw new Error(`Collision tile with index ${index.x},${index.y} is out of bounds!`);
}
return index.x +',' + index.y;
}
/**
* Set the state of a tile.
* @param {Vector2} index Tile index.
* @param {Boolean} haveCollision Does this tile have collision?
* @param {Number} collisionFlags Optional collision flag to set for this tile.
*/
setTile(index, haveCollision, collisionFlags)
{
let key = this._indexToKey(index);
if (haveCollision) {
let rect = this._tiles[key] || new RectangleShape(
new Rectangle(
this._offset.x + index.x * this._tileSize.x,
this._offset.y + index.y * this._tileSize.y,
this._tileSize.x,
this._tileSize.y)
);
if (collisionFlags !== undefined) {
rect.collisionFlags = collisionFlags;
}
this._tiles[key] = rect;
}
else {
delete this._tiles[key];
}
}
/**
* Get the collision shape of a tile at a given position.
* @param {Vector2} position Position to get tile at.
* @returns {RectangleShape} Collision shape at this position, or null if not set.
*/
getTileAt(position)
{
let index = new Vector2(Math.floor(position.x / this._tileSize.x), Math.floor(position.y / this._tileSize.y));
let key = index.x + ',' + index.y;
return this._tiles[key] || null;
}
/**
* Iterate all tiles in given region, represented by a rectangle.
* @param {Rectangle} region Rectangle to get tiles for.
* @param {Function} callback Method to invoke for every tile. Return false to break iteration.
*/
iterateTilesAtRegion(region, callback)
{
let topLeft = region.getTopLeft();
let bottomRight = region.getBottomRight();
let startIndex = new Vector2(Math.floor(topLeft.x / this._tileSize.x), Math.floor(topLeft.y / this._tileSize.y));
let endIndex = new Vector2(Math.floor(bottomRight.x / this._tileSize.x), Math.floor(bottomRight.y / this._tileSize.y));
for (let i = startIndex.x; i <= endIndex.x; ++i) {
for (let j = startIndex.y; j <= endIndex.y; ++j) {
let key = i + ',' + j;
let tile = this._tiles[key];
if (tile && (callback(tile) === false)) {
return;
}
}
}
}
/**
* Get all tiles in given region, represented by a rectangle.
* @param {Rectangle} region Rectangle to get tiles for.
* @returns {Array<RectangleShape>} Array with rectangle shapes or empty if none found.
*/
getTilesAtRegion(region)
{
let ret = [];
this.iterateTilesAtRegion(region, (tile) => { ret.push(tile); });
return ret;
}
/**
* @inheritdoc
*/
_getRadius()
{
return this._radius;
}
/**
* @inheritdoc
*/
_getBoundingBox()
{
return this._boundingRect;
}
/**
* @inheritdoc
*/
getCenter()
{
return this._center.clone();
}
/**
* Debug draw this shape.
* @param {Number} opacity Shape opacity factor.
*/
debugDraw(opacity)
{
if (opacity === undefined) opacity = 1;
let color = this._getDebugColor();
color.a *= opacity;
// draw borders
if (this._haveBorders) {
gfx.outlineRect(this._intBoundingRect, color, gfx.BlendModes.AlphaBlend);
gfx.outlineRect(this._boundingRect, color, gfx.BlendModes.AlphaBlend);
}
// draw tiles
for (let key in this._tiles) {
let tile = this._tiles[key];
tile.setDebugColor(this._forceDebugColor);
tile.debugDraw(opacity);
}
}
} |
JavaScript | class Camera
{
/**
* Create the camera.
* @param {Gfx} gfx The gfx manager instance.
*/
constructor(gfx)
{
/**
* Camera projection matrix.
* You can set it manually, or use 'orthographicOffset' / 'orthographic' / 'perspective' helper functions.
*/
this.projection = null;
this._region = null;
this._gfx = gfx;
this.orthographic();
this._viewport = null;
}
/**
* Get camera's viewport (drawing region to set when using this camera).
* @returns {Rectangle} Camera's viewport as rectangle.
*/
get viewport()
{
return this._viewport;
}
/**
* Set camera's viewport.
* @param {Rectangle} viewport New viewport to set or null to not use any viewport when using this camera.
*/
set viewport(viewport)
{
this._viewport = viewport;
return viewport;
}
/**
* Get the region this camera covers.
* @returns {Rectangle} region this camera covers.
*/
getRegion()
{
return this._region.clone();
}
/**
* Make this camera an orthographic camera with offset.
* @param {Vector2} offset Camera offset (top-left corner).
* @param {Boolean} ignoreViewportSize If true, will take the entire canvas size for calculation and ignore the viewport size, if set.
* @param {Number} near Near clipping plane.
* @param {Number} far Far clipping plane.
*/
orthographicOffset(offset, ignoreViewportSize, near, far)
{
let renderingSize = (ignoreViewportSize || !this.viewport) ? this._gfx.getCanvasSize() : this.viewport.getSize();
let region = new Rectangle(offset.x, offset.y, renderingSize.x, renderingSize.y);
this.orthographic(region, near, far);
}
/**
* Make this camera an orthographic camera.
* @param {Rectangle} region Camera left, top, bottom and right. If not set, will take entire canvas.
* @param {Number} near Near clipping plane.
* @param {Number} far Far clipping plane.
*/
orthographic(region, near, far)
{
if (region === undefined) {
region = this._gfx.getRenderingRegion();
}
this._region = region;
this.projection = Matrix.orthographic(region.left, region.right, region.bottom, region.top, near || -1, far || 400);
}
/**
* Make this camera a perspective camera.
* @private
* @param {*} fieldOfView Field of view angle in radians.
* @param {*} aspectRatio Aspect ratio.
* @param {*} near Near clipping plane.
* @param {*} far Far clipping plane.
*/
_perspective(fieldOfView, aspectRatio, near, far)
{
this.projection = Matrix.perspective(fieldOfView || (Math.PI / 2), aspectRatio || 1, near || 0.1, far || 1000)
}
} |
JavaScript | class BasicEffect extends Effect
{
/** @inheritdoc */
get vertexCode()
{
return vertexShader;
}
/** @inheritdoc */
get fragmentCode()
{
return fragmentShader;
}
/** @inheritdoc */
get uniformTypes()
{
return {
"texture": { type: Effect.UniformTypes.Texture, bind: Effect.UniformBinds.MainTexture },
"projection": { type: Effect.UniformTypes.Matrix, bind: Effect.UniformBinds.Projection },
"world": { type: Effect.UniformTypes.Matrix, bind: Effect.UniformBinds.World },
};
}
/** @inheritdoc */
get attributeTypes()
{
return {
"position": { size: 3, type: Effect.AttributeTypes.Float, normalize: false, bind: Effect.AttributeBinds.Position },
"coord": { size: 2, type: Effect.AttributeTypes.Float, normalize: false, bind: Effect.AttributeBinds.TextureCoords },
"color": { size: 4, type: Effect.AttributeTypes.Float, normalize: false, bind: Effect.AttributeBinds.Colors },
};
}
} |
JavaScript | class Effect
{
/**
* Build the effect.
* Called from gfx manager.
* @private
* @param {WebGl} gl WebGL context.
*/
_build(gl)
{
// create program
let program = gl.createProgram();
// build vertex shader
{
let shader = compileShader(gl, this.vertexCode, gl.VERTEX_SHADER);
gl.attachShader(program, shader);
}
// build fragment shader
{
let shader = compileShader(gl, this.fragmentCode, gl.FRAGMENT_SHADER);
gl.attachShader(program, shader);
}
// link program
gl.linkProgram(program)
// check for errors
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
_logger.error("Error linking shader program:");
_logger.error(gl.getProgramInfoLog(program));
throw new Error("Failed to link shader program.");
}
// store program and gl
this._gl = gl;
this._program = program;
// a set of dynamically-created setters to set uniform values
this.uniforms = {};
// dictionary to bind uniform to built-in roles, like main texture or color
this._uniformBinds = {};
// initialize uniform setters
for (let uniform in this.uniformTypes) {
// get uniform location
let uniformLocation = this._gl.getUniformLocation(this._program, uniform);
if (uniformLocation === -1) {
_logger.error("Could not find uniform: " + uniform);
throw new Error(`Uniform named '${uniform}' was not found in shader code!`);
}
// get gl setter method
let uniformData = this.uniformTypes[uniform];
if (!UniformTypes._values.has(uniformData.type)) {
_logger.error("Uniform has invalid type: " + uniformData.type);
throw new Error(`Uniform '${uniform}' have illegal value type '${uniformData.type}'!`);
}
// build setter method for matrices
if (uniformData.type === UniformTypes.Matrix) {
(function(_this, name, location, method) {
_this.uniforms[name] = (mat) => {
_this._gl[method](location, false, mat);
}
})(this, uniform, uniformLocation, uniformData.type);
}
// build setter method for textures
else if (uniformData.type === UniformTypes.Texture) {
(function(_this, name, location, method) {
_this.uniforms[name] = (texture, index) => {
index = index || 0;
const glTexture = texture.texture || texture;
const textureCode = _this._gl['TEXTURE' + (index || 0)];
_this._gl.activeTexture(textureCode);
_this._gl.bindTexture(_this._gl.TEXTURE_2D, glTexture);
_this._gl.uniform1i(location, (index || 0));
if (texture.filter) { _setTextureFilter(_this._gl, texture.filter); }
if (texture.wrapMode) { _setTextureWrapMode(_this._gl, texture.wrapMode); }
}
})(this, uniform, uniformLocation, uniformData.type);
}
// build setter method for other types
else {
(function(_this, name, location, method) {
_this.uniforms[name] = (v1, v2, v3, v4) => {
_this._gl[method](location, v1, v2, v3, v4);
}
})(this, uniform, uniformLocation, uniformData.type);
}
// set binding
let bindTo = uniformData.bind;
if (bindTo) {
this._uniformBinds[bindTo] = uniform;
}
}
// a set of dynamically-created setters to set attribute values
this.attributes = {};
// dictionary to bind attribute to built-in roles, like vertices positions or uvs
this._attributeBinds = {};
// get attribute locations
for (let attr in this.attributeTypes) {
// get attribute location
let attributeLocation = this._gl.getAttribLocation(this._program, attr);
if (attributeLocation === -1) {
_logger.error("Could not find attribute: " + attr);
throw new Error(`Attribute named '${attr}' was not found in shader code!`);
}
// get attribute data
let attributeData = this.attributeTypes[attr];
// build setter method
(function(_this, name, location, data) {
_this.attributes[name] = (buffer) => {
if (buffer) {
_this._gl.bindBuffer(_this._gl.ARRAY_BUFFER, buffer);
_this._gl.vertexAttribPointer(location, data.size, _this._gl[data.type] || _this._gl.FLOAT, data.normalize || false, data.stride || 0, data.offset || 0);
_this._gl.enableVertexAttribArray(location);
}
else {
_this._gl.disableVertexAttribArray(location);
}
}
})(this, attr, attributeLocation, attributeData);
// set binding
let bindTo = attributeData.bind;
if (bindTo) {
this._attributeBinds[bindTo] = attr;
}
}
// values we already set for this effect, so we won't set them again
this._cachedValues = {};
}
/**
* Get a dictionary with all shaders uniforms.
* Key = uniform name, as appears in shader code.
* Value = {
* type: UniformTypes to represent uniform type,
* bind: Optional bind to one of the built-in uniforms. See Effect.UniformBinds for details.
* }
* @returns {*} Dictionary with uniforms descriptions.
*/
get uniformTypes()
{
throw new Error("Not Implemented!");
}
/**
* Get a dictionary with all shader attributes.
* Key = attribute name, as appears in shader code.
* Value = {
* size: size of every value in this attribute.
* type: attribute type. See Effect.AttributeTypes for details.
* normalize: if true, will normalize values.
* stride: optional stride.
* offset: optional offset.
* bind: Optional bind to one of the built-in attributes. See Effect.AttributeBinds for details.
* }
* @returns {*} Dictionary with attributes descriptions.
*/
get attributeTypes()
{
throw new Error("Not Implemented!");
}
/**
* Make this effect active.
*/
setAsActive()
{
// use effect program
this._gl.useProgram(this._program);
// enable / disable some features
if (this.enableDepthTest) { this._gl.enable(this._gl.DEPTH_TEST); } else { this._gl.disable(this._gl.DEPTH_TEST); }
if (this.enableFaceCulling) { this._gl.enable(this._gl.CULL_FACE); } else { this._gl.disable(this._gl.CULL_FACE); }
if (this.enableStencilTest) { this._gl.enable(this._gl.STENCIL_TEST); } else { this._gl.disable(this._gl.STENCIL_TEST); }
if (this.enableDithering) { this._gl.enable(this._gl.DITHER); } else { this._gl.disable(this._gl.DITHER); }
// reset cached values
this._cachedValues = {};
}
/**
* Prepare effect before drawing it with batching.
* @param {Mesh} mesh Mesh we're about to draw.
* @param {Matrix} world World matrix.
*/
prepareToDrawBatch(mesh, world)
{
this._cachedValues = {};
this.setPositionsAttribute(mesh.positions);
this.setTextureCoordsAttribute(mesh.textureCoords);
this.setColorsAttribute(mesh.colors);
this.setWorldMatrix(world);
}
/**
* Get this effect's vertex shader code, as string.
* @returns {String} Vertex shader code.
*/
get vertexCode()
{
throw new Error("Not Implemented!");
}
/**
* Get this effect's fragment shader code, as string.
* @returns {String} Fragment shader code.
*/
get fragmentCode()
{
throw new Error("Not Implemented!");
}
/**
* Should this effect enable depth test?
*/
get enableDepthTest()
{
return false;
}
/**
* Should this effect enable face culling?
*/
get enableFaceCulling()
{
return false;
}
/**
* Should this effect enable stencil test?
*/
get enableStencilTest()
{
return false;
}
/**
* Should this effect enable dithering?
*/
get enableDithering()
{
return false;
}
/**
* Set the main texture.
* Only works if there's a uniform type bound to 'MainTexture'.
* @param {TextureAsset} texture Texture to set.
* @returns {Boolean} True if texture was changed, false if there was no need to change the texture.
*/
setTexture(texture)
{
let uniform = this._uniformBinds[Effect.UniformBinds.MainTexture];
if (uniform) {
if (texture === this._cachedValues.texture) { return false; }
this._cachedValues.texture = texture;
let glTexture = texture.texture || texture;
this._gl.activeTexture(this._gl.TEXTURE0);
this._gl.bindTexture(this._gl.TEXTURE_2D, glTexture);
this.uniforms[uniform](texture, 0);
return true;
}
return false;
}
/**
* Set the main tint color.
* Only works if there's a uniform type bound to 'Color'.
* @param {Color} color Color to set.
*/
setColor(color)
{
let uniform = this._uniformBinds[Effect.UniformBinds.Color];
if (uniform) {
if (color.equals(this._cachedValues.color)) { return; }
this._cachedValues.color = color.clone();
this.uniforms[uniform](color.floatArray);
}
}
/**
* Set uvOffset and uvScale params from source rectangle and texture.
* @param {Rectangle} sourceRect Source rectangle to set, or null to take entire texture.
* @param {TextureAsset} texture Texture asset to set source rect for.
*/
setUvOffsetAndScale(sourceRect, texture)
{
// skip if the same
if (sourceRect) {
if (sourceRect.equals(this._cachedValues.sourceRect)) { return; }
}
else {
if (this._cachedValues.sourceRect === null) { return; }
}
this._cachedValues.sourceRect = sourceRect ? sourceRect.clone() : null;
// default source rect
if (!sourceRect) { sourceRect = new Rectangle(0, 0, texture.width, texture.height); }
// set uv offset
let uvOffset = this._uniformBinds[Effect.UniformBinds.UvOffset];
if (uvOffset) {
this.uniforms[uvOffset](sourceRect.x / texture.width, sourceRect.y / texture.height);
}
// set uv scale
let uvScale = this._uniformBinds[Effect.UniformBinds.UvScale];
if (uvScale) {
this.uniforms[uvScale](sourceRect.width / texture.width, sourceRect.height / texture.height);
}
}
/**
* Set the projection matrix uniform.
* @param {Matrix} matrix Matrix to set.
*/
setProjectionMatrix(matrix)
{
let uniform = this._uniformBinds[Effect.UniformBinds.Projection];
if (uniform) {
if (matrix.equals(this._cachedValues.projection)) { return; }
this._cachedValues.projection = matrix.clone();
this.uniforms[uniform](matrix.values);
}
}
/**
* Set the world matrix uniform.
* @param {Matrix} matrix Matrix to set.
*/
setWorldMatrix(matrix)
{
let uniform = this._uniformBinds[Effect.UniformBinds.World];
if (uniform) {
this.uniforms[uniform](matrix.values);
}
}
/**
* Set the vertices position buffer.
* Only works if there's an attribute type bound to 'Position'.
* @param {WebGLBuffer} buffer Vertices position buffer.
*/
setPositionsAttribute(buffer)
{
let attr = this._attributeBinds[Effect.AttributeBinds.Position];
if (attr) {
if (buffer === this._cachedValues.positions) { return; }
this._cachedValues.positions = buffer;
this.attributes[attr](buffer);
}
}
/**
* Set the vertices texture coords buffer.
* Only works if there's an attribute type bound to 'TextureCoords'.
* @param {WebGLBuffer} buffer Vertices texture coords buffer.
*/
setTextureCoordsAttribute(buffer)
{
let attr = this._attributeBinds[Effect.AttributeBinds.TextureCoords];
if (attr) {
if (buffer === this._cachedValues.coords) { return; }
this._cachedValues.coords = buffer;
this.attributes[attr](buffer);
}
}
/**
* Set the vertices colors buffer.
* Only works if there's an attribute type bound to 'Colors'.
* @param {WebGLBuffer} buffer Vertices colors buffer.
*/
setColorsAttribute(buffer)
{
let attr = this._attributeBinds[Effect.AttributeBinds.Colors];
if (attr) {
if (buffer === this._cachedValues.colors) { return; }
this._cachedValues.colors = buffer;
this.attributes[attr](buffer);
}
}
} |
JavaScript | class Gfx extends IManager
{
/**
* Create the manager.
*/
constructor()
{
super();
this._gl = null;
this._initSettings = { antialias: true, alpha: true, depth: false, premultipliedAlpha: true, desynchronized: false };
this._canvas = null;
this._lastBlendMode = null;
this._activeEffect = null;
this._camera = null;
this._projection = null;
this._currIndices = null;
this._dynamicBuffers = null;
this._fb = null;
this.builtinEffects = {};
this.meshes = {};
this.defaultTextureFilter = TextureFilterModes.Nearest;
this.defaultTextureWrapMode = TextureWrapModes.Clamp;
this.whiteTexture = null;
this._renderTarget = null;
this._viewport = null;
this._drawCallsCount = 0;
this.spritesBatch = null;
}
/**
* Get how many sprites we can draw in a single batch.
* @private
* @returns {Number} batch max sprites count.
*/
get batchSpritesCount()
{
return 2048;
}
/**
* Maximum number of vertices we allow when drawing lines.
* @private
* @returns {Number} max vertices per lines strip.
*/
get maxLineSegments()
{
return 512;
}
/**
* Set WebGL init flags (passed as additional params to the getContext() call).
* You must call this *before* initializing *Shaku*.
*
* By default, *Shaku* will init WebGL context with the following flags:
* - antialias: true.
* - alpha: true.
* - depth: false.
* - premultipliedAlpha: true.
* - desynchronized: false.
* @example
* Shaku.gfx.setContextAttributes({ antialias: true, alpha: false });
* @param {Dictionary} flags WebGL init flags to set.
*/
setContextAttributes(flags)
{
if (this._gl) { throw new Error("Can't call setContextAttributes() after gfx was initialized!"); }
this._initSettings = flags;
}
/**
* Set the canvas element to initialize on.
* You must call this *before* initializing Shaku. Calling this will prevent Shaku from creating its own canvas.
* @example
* Shaku.gfx.setCanvas(document.getElementById('my-canvas'));
* @param {Canvas} element Canvas element to initialize on.
*/
setCanvas(element)
{
if (this._gl) { throw new Error("Can't call setCanvas() after gfx was initialized!"); }
this._canvas = element;
}
/**
* Get the canvas element controlled by the gfx manager.
* If you didn't provide your own canvas before initialization, you must add this canvas to your document after initializing `Shaku`.
* @example
* document.body.appendChild(Shaku.gfx.canvas);
* @returns {Canvas} Canvas we use for rendering.
*/
get canvas()
{
return this._canvas;
}
/**
* Get the Effect base class, which is required to implement custom effects.
* @see Effect
*/
get Effect()
{
return Effect;
}
/**
* Get the default Effect class, which is required to implement custom effects that inherit and reuse parts from the default effect.
* @see BasicEffect
*/
get BasicEffect()
{
return BasicEffect;
}
/**
* Get the sprite class.
* @see Sprite
*/
get Sprite()
{
return Sprite;
}
/**
* Get the sprites group object.
* @see SpritesGroup
*/
get SpritesGroup()
{
return SpritesGroup;
}
/**
* Get the matrix object.
* @see Matrix
*/
get Matrix()
{
return Matrix;
}
/**
* Get the text alignments options.
* * Left: align text to the left.
* * Right: align text to the right.
* * Center: align text to center.
* @see TextAlignment
*/
get TextAlignment()
{
return TextAlignment;
}
/**
* Create and return a new camera instance.
* @param {Boolean} withViewport If true, will create camera with viewport value equal to canvas' size.
* @returns {Camera} New camera object.
*/
createCamera(withViewport)
{
let ret = new Camera(this);
if (withViewport) {
ret.viewport = this.getRenderingRegion();
}
return ret;
}
/**
* Set default orthographic camera from offset.
* @param {Vector2} offset Camera top-left corner.
* @returns {Camera} Camera instance.
*/
setCameraOrthographic(offset)
{
let camera = this.createCamera();
camera.orthographicOffset(offset);
this.applyCamera(camera);
return camera;
}
/**
* Create and return an effect instance.
* @see Effect
* @param {Class} type Effect class type. Must inherit from Effect base class.
* @returns {Effect} Effect instance.
*/
createEffect(type)
{
if (!(type.prototype instanceof Effect)) { throw new Error("'type' must be a class type that inherits from 'Effect'."); }
let effect = new type();
effect._build(this._gl);
return effect;
}
/**
* Set resolution and canvas to the max size of its parent element or screen.
* If the canvas is directly under document body, it will take the max size of the page.
* @param {Boolean} limitToParent if true, will use parent element size. If false, will stretch on entire document.
* @param {Boolean} allowOddNumbers if true, will permit odd numbers, which could lead to small artefacts when drawing pixel art. If false (default) will round to even numbers.
*/
maximizeCanvasSize(limitToParent, allowOddNumbers)
{
// new width and height
let width = 0;
let height = 0;
// parent
if (limitToParent) {
let parent = this._canvas.parentElement;
width = parent.clientWidth - this._canvas.offsetLeft;
height = parent.clientHeight - this._canvas.offsetTop;
}
// entire screen
else {
width = window.innerWidth;
height = window.innerHeight;
this._canvas.style.left = '0px';
this._canvas.style.top = '0px';
}
// make sure even numbers
if (!allowOddNumbers) {
if (width % 2 !== 0) { width++; }
if (height % 2 !== 0) { height++; }
}
// if changed, set resolution
if ((this._canvas.width !== width) || (this._canvas.height !== height)) {
this.setResolution(width, height, true);
}
}
/**
* Set a render target (texture) to render on.
* @example
* // create render target
* let renderTarget = await Shaku.assets.createRenderTarget('_my_render_target', 800, 600);
*
* // use render target
* Shaku.gfx.setRenderTarget(renderTarget);
* // .. draw some stuff here
*
* // reset render target and present it on screen
* // note the negative height - render targets end up with flipped Y axis
* Shaku.gfx.setRenderTarget(null);
* Shaku.gfx.draw(renderTarget, new Shaku.utils.Vector2(screenX / 2, screenY / 2), new Shaku.utils.Vector2(screenX, -screenY));
* @param {TextureAsset|Array<TextureAsset>} texture Render target texture to set as render target, or null to reset and render back on canvas. Can also be array for multiple targets, which will take layouts 0-15 by their order.
* @param {Boolean} keepCamera If true, will keep current camera settings. If false (default) will reset camera.
*/
setRenderTarget(texture, keepCamera)
{
// present buffered data
this.presentBufferedData();
// if texture is null, remove any render target
if (texture === null) {
this._renderTarget = null;
//this._gl.drawBuffers([this._gl.BACK]);
this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, false);
if (!keepCamera) {
this.resetCamera();
}
return;
}
// convert texture to array
if (!(texture instanceof Array)) {
texture = [texture];
}
// bind the framebuffer
this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, this._fb);
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, false);
// set render targets
var drawBuffers = [];
for (let index = 0; index < texture.length; ++index) {
// attach the texture as the first color attachment
const attachmentPoint = this._gl['COLOR_ATTACHMENT' + index];
this._gl.framebufferTexture2D(this._gl.FRAMEBUFFER, attachmentPoint, this._gl.TEXTURE_2D, texture[index].texture, 0);
// index 0 is the "main" render target
if (index === 0) {
this._renderTarget = texture[index];
}
// to set drawBuffers in the end
drawBuffers.push(attachmentPoint);
}
// set draw buffers
this._gl.drawBuffers(drawBuffers);
// unbind frame buffer
//this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
// reset camera
if (!keepCamera) {
this.resetCamera();
}
}
/**
* Set effect to use for future draw calls.
* @example
* let effect = Shaku.gfx.createEffect(MyEffectType);
* Shaku.gfx.useEffect(effect);
* @param {Effect} effect Effect to use or null to use the basic builtin effect.
*/
useEffect(effect)
{
// present buffered data
this.presentBufferedData();
// if null, use default
if (effect === null) {
this.useEffect(this.builtinEffects.Basic);
return;
}
// same effect? skip
if (this._activeEffect === effect) {
return;
}
// set effect
effect.setAsActive();
this._activeEffect = effect;
if (this._projection) { this._activeEffect.setProjectionMatrix(this._projection); }
}
/**
* Set resolution and canvas size.
* @example
* // set resolution and size of 800x600.
* Shaku.gfx.setResolution(800, 600, true);
* @param {Number} width Resolution width.
* @param {Number} height Resolution height.
* @param {Boolean} updateCanvasStyle If true, will also update the canvas *css* size in pixels.
*/
setResolution(width, height, updateCanvasStyle)
{
this.presentBufferedData();
this._canvas.width = width;
this._canvas.height = height;
if (width % 2 !== 0 || height % 2 !== 0) {
_logger.warn("Resolution to set is not even numbers; This might cause minor artefacts when using texture atlases. Consider using even numbers instead.");
}
if (updateCanvasStyle) {
this._canvas.style.width = width + 'px';
this._canvas.style.height = height + 'px';
}
this._gl.viewport(0, 0, width, height);
this.resetCamera();
}
/**
* Reset camera properties to default camera.
*/
resetCamera()
{
this._camera = this.createCamera();
let size = this.getRenderingSize();
this._camera.orthographic(new Rectangle(0, 0, size.x, size.y));
this.applyCamera(this._camera);
}
/**
* Set viewport, projection and other properties from a camera instance.
* Changing the camera properties after calling this method will *not* update the renderer, until you call applyCamera again.
* @param {Camera} camera Camera to apply.
*/
applyCamera(camera)
{
this.presentBufferedData();
this._viewport = camera.viewport;
let viewport = this.getRenderingRegion(true);
this._gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
this._projection = camera.projection.clone();
if (this._activeEffect) { this._activeEffect.setProjectionMatrix(this._projection); }
}
/**
* Get current rendering region.
* @param {Boolean} includeOffset If true (default) will include viewport offset, if exists.
* @returns {Rectangle} Rectangle with rendering region.
*/
getRenderingRegion(includeOffset)
{
if (this._viewport) {
let ret = this._viewport.clone();
if (includeOffset === false) {
ret.x = ret.y = 0;
}
return ret;
}
return new Rectangle(0, 0, (this._renderTarget || this._canvas).width, (this._renderTarget || this._canvas).height);
}
/**
* Get current rendering size.
* Unlike 'canvasSize', this takes viewport and render target into consideration.
* @returns {Vector2} rendering size.
*/
getRenderingSize()
{
let region = this.getRenderingRegion();
return region.getSize();
}
/**
* Get canvas size as vector.
* @returns {Vector2} Canvas size.
*/
getCanvasSize()
{
return new Vector2(this._canvas.width, this._canvas.height);
}
/**
* @inheritdoc
* @private
*/
setup()
{
return new Promise(async (resolve, reject) => {
_logger.info("Setup gfx manager..");
// if no canvas is set, create one
if (!this._canvas) {
this._canvas = document.createElement('canvas');
}
// get gl context
this._gl = this._canvas.getContext('webgl2', this._initSettings) || this._canvas.getContext('webgl', this._initSettings);
if (!this._gl) {
_logger.error("Can't get WebGL context!");
return reject("Failed to get WebGL context from canvas!");
}
// create default effects
this.builtinEffects.Basic = this.createEffect(BasicEffect);
// setup textures assets gl context
TextureAsset._setWebGl(this._gl);
// create framebuffer (used for render targets)
this._fb = this._gl.createFramebuffer();
// create base meshes
let _meshGenerator = new MeshGenerator(this._gl);
this.meshes = {
quad: _meshGenerator.quad()
}
Object.freeze(this.meshes);
// create a useful single white pixel texture
let whitePixelImage = new Image();
whitePixelImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=';
await new Promise((resolve, reject) => { whitePixelImage.onload = resolve; });
this.whiteTexture = new TextureAsset('__runtime_white_pixel__');
this.whiteTexture.fromImage(whitePixelImage);
// dynamic buffers, used for batch rendering
this._dynamicBuffers = {
positionBuffer: this._gl.createBuffer(),
positionArray: new Float32Array(3 * 4 * this.batchSpritesCount),
textureCoordBuffer: this._gl.createBuffer(),
textureArray: new Float32Array(2 * 4 * this.batchSpritesCount),
colorsBuffer: this._gl.createBuffer(),
colorsArray: new Float32Array(4 * 4 * this.batchSpritesCount),
indexBuffer: this._gl.createBuffer(),
linesIndexBuffer: this._gl.createBuffer(),
}
// create the indices buffer for batching
let indices = new Uint16Array(this.batchSpritesCount * 6); // 6 = number of indices per sprite
let inc = 0;
for(let i = 0; i < indices.length; i += 6) {
indices[i] = inc;
indices[i+1] = inc + 1;
indices[i+2] = inc + 2;
indices[i+3] = inc + 1;
indices[i+4] = inc + 3;
indices[i+5] = inc + 2;
inc += 4;
}
this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, this._dynamicBuffers.indexBuffer);
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, indices, this._gl.STATIC_DRAW);
// create the indices buffer for drawing lines
let lineIndices = new Uint16Array(this.maxLineSegments);
for (let i = 0; i < lineIndices.length; i += 6) {
lineIndices[i] = i;
}
this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, this._dynamicBuffers.linesIndexBuffer);
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, lineIndices, this._gl.STATIC_DRAW);
// create sprites batch
this.spritesBatch = new SpriteBatch(this);
// use default effect
this.useEffect(null);
// create default camera
this._camera = this.createCamera();
this.applyCamera(this._camera);
// success!
resolve();
});
}
/**
* Generate a sprites group to render a string using a font texture.
* Take the result of this method and use with gfx.drawGroup() to render the text.
* This is what you use when you want to draw texts with `Shaku`.
* Note: its best to always draw texts with *batching* enabled.
* @example
* // load font texture
* let fontTexture = await Shaku.assets.loadFontTexture('assets/DejaVuSansMono.ttf', {fontName: 'DejaVuSansMono'});
*
* // generate 'hello world!' text (note: you don't have to regenerate every frame if text didn't change)
* let text1 = Shaku.gfx.buildText(fontTexture, "Hello World!");
* text1.position.set(40, 40);
*
* // draw text
* Shaku.gfx.drawGroup(text1, true);
* @param {FontTextureAsset} fontTexture Font texture asset to use.
* @param {String} text Text to generate sprites for.
* @param {Number} fontSize Font size, or undefined to use font texture base size.
* @param {Color|Array<Color>} color Text sprites color. If array is set, will assign each color to different vertex, starting from top-left.
* @param {TextAlignment} alignment Text alignment.
* @param {Vector2} offset Optional starting offset.
* @param {Vector2} marginFactor Optional factor for characters and line spacing. For example value of 2,1 will make double horizontal spacing.
* @returns {SpritesGroup} Sprites group containing the needed sprites to draw the given text with its properties.
*/
buildText(fontTexture, text, fontSize, color, alignment, offset, marginFactor)
{
// make sure text is a string
if (typeof text !== 'string') {
text = '' + text;
}
// sanity
if (!fontTexture || !fontTexture.valid) {
throw new Error("Font texture is invalid!");
}
// default alignment
alignment = alignment || TextAlignment.Left;
// default color
color = color || Color.black;
// default font size
fontSize = fontSize || fontTexture.fontSize;
// default margin factor
marginFactor = marginFactor || Vector2.one;
// get character scale factor
let scale = fontSize / fontTexture.fontSize;
// current character offset
let position = new Vector2(0, 0);
// current line characters and width
let currentLineSprites = [];
let lineWidth = 0;
// go line down
function breakLine()
{
// add offset to update based on alignment
let offsetX = 0;
switch (alignment) {
case TextAlignment.Right:
offsetX = -lineWidth;
break;
case TextAlignment.Center:
offsetX = -lineWidth / 2;
break;
}
// if we need to shift characters for alignment, do it
if (offsetX != 0) {
for (let i = 0; i < currentLineSprites.length; ++i) {
currentLineSprites[i].position.x += offsetX;
}
}
// update offset
position.x = 0;
position.y += fontTexture.lineHeight * scale * marginFactor.y;
// reset line width and sprites
currentLineSprites = [];
lineWidth = 0;
}
// create group to return and build sprites
let ret = new SpritesGroup();
for (let i = 0; i < text.length; ++i)
{
// get character and source rect
let character = text[i];
let sourceRect = fontTexture.getSourceRect(character);
// special case - break line
if (character === '\n') {
breakLine();
continue;
}
// calculate character size
let size = new Vector2(sourceRect.width * scale, sourceRect.height * scale);
// create sprite (unless its space)
if (character !== ' ') {
// create sprite and add to group
let sprite = new Sprite(fontTexture.texture, sourceRect);
sprite.size = size;
sprite.position.copy(position);
if (color instanceof Color) {
sprite.color.copy(color);
}
else {
sprite.color = [];
for (let col of color) {
sprite.color.push(col.clone());
}
}
sprite.origin.x = 0;
ret.add(sprite);
// add to current line sprites
currentLineSprites.push(sprite);
}
// update current line width
lineWidth += size.x * marginFactor.x;
// set position for next character
position.x += size.x * marginFactor.x;
}
// call break line on last line, to adjust alignment for last line
breakLine();
// set position
if (offset) {
ret.position.set(offset.x, offset.y);
}
// return group
return ret;
}
/**
* Draw a SpritesGroup object.
* A SpritesGroup is a collection of sprites we can draw in bulks with transformations to apply on the entire group.
* @example
* // load texture
* let texture = await Shaku.assets.loadTexture('assets/sprite.png');
*
* // create group and set entire group's position and scale
* let group = new Shaku.gfx.SpritesGroup();
* group.position.set(125, 300);
* group.scale.set(2, 2);
*
* // create 5 sprites and add to group
* for (let i = 0; i < 5; ++i) {
* let sprite = new Shaku.gfx.Sprite(texture);
* sprite.position.set(100 * i, 150);
* sprite.size.set(50, 50);
* group.add(sprite)
* }
*
* // draw the group with automatic culling of invisible sprites
* Shaku.gfx.drawGroup(group, true);
* @param {SpritesGroup} group Sprites group to draw.
* @param {Boolean} cullOutOfScreen If true and in batching mode, will cull automatically any quad that is completely out of screen.
*/
drawGroup(group, cullOutOfScreen)
{
this._drawBatch(group, Boolean(cullOutOfScreen));
}
/**
* Draw a single sprite object.
* Sprites are optional objects that store all the parameters for a `draw()` call. They are also used for batch rendering.
* @example
* // load texture and create sprite
* let texture = await Shaku.assets.loadTexture('assets/sprite.png');
* let sprite = new Shaku.gfx.Sprite(texture);
*
* // set position and size
* sprite.position.set(100, 150);
* sprite.size.set(50, 50);
*
* // draw sprite
* Shaku.gfx.drawSprite(sprite);
* @param {Sprite} sprite Sprite object to draw.
*/
drawSprite(sprite)
{
if (!sprite.texture || !sprite.texture.valid) { return; }
this.__startDrawingSprites(this._activeEffect, null);
this.spritesBatch.draw(sprite);
}
/**
* Draw a texture to cover a given destination rectangle.
* @example
* // cover the entire screen with an image
* let texture = await Shaku.assets.loadTexture('assets/sprite.png');
* Shaku.gfx.cover(texture, Shaku.gfx.getRenderingRegion());
* @example
* // draw with additional params
* let sourceRect = new Shaku.utils.Rectangle(0, 0, 64, 64);
* let color = Shaku.utils.Color.blue;
* let blendMode = Shaku.gfx.BlendModes.Multiply;
* let rotation = Math.PI / 4;
* let origin = new Shaku.utils.Vector2(0.5, 0.5);
* Shaku.gfx.draw(texture, position, size, sourceRect, color, blendMode, rotation, origin);
* @param {TextureAsset} texture Texture to draw.
* @param {Rectangle|Vector2} destRect Destination rectangle to draw on. If vector is provided, will draw from 0,0 with vector as size.
* @param {Rectangle} sourceRect Source rectangle, or undefined to use the entire texture.
* @param {Color|Array<Color>} color Tint color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
* @param {BlendModes} blendMode Blend mode, or undefined to use alpha blend.
*/
cover(texture, destRect, sourceRect, color, blendMode)
{
if ((destRect instanceof Vector2) || (destRect instanceof Vector3)) {
destRect = new Rectangle(0, 0, destRect.x, destRect.y);
}
return this.draw(texture, destRect.getCenter(), destRect.getSize(), sourceRect, color, blendMode);
}
/**
* Draw a texture.
* @example
* // a simple draw with position and size
* let texture = await Shaku.assets.loadTexture('assets/sprite.png');
* let position = new Shaku.utils.Vector2(100, 100);
* let size = new Shaku.utils.Vector2(75, 125); // if width == height, you can pass as a number instead of vector
* Shaku.gfx.draw(texture, position, size);
* @example
* // draw with additional params
* let sourceRect = new Shaku.utils.Rectangle(0, 0, 64, 64);
* let color = Shaku.utils.Color.blue;
* let blendMode = Shaku.gfx.BlendModes.Multiply;
* let rotation = Math.PI / 4;
* let origin = new Shaku.utils.Vector2(0.5, 0.5);
* Shaku.gfx.draw(texture, position, size, sourceRect, color, blendMode, rotation, origin);
* @param {TextureAsset} texture Texture to draw.
* @param {Vector2|Vector3} position Drawing position (at origin). If vector3 is provided, will pass z value to the shader code position attribute.
* @param {Vector2|Vector3|Number} size Drawing size. If vector3 is provided, will pass z value to the shader code position attribute for the bottom vertices, as position.z + size.z.
* @param {Rectangle} sourceRect Source rectangle, or undefined to use the entire texture.
* @param {Color|Array<Color>} color Tint color, or undefined to not change color. If array is set, will assign each color to different vertex, starting from top-left.
* @param {BlendModes} blendMode Blend mode, or undefined to use alpha blend.
* @param {Number} rotation Rotate sprite.
* @param {Vector2} origin Drawing origin. This will be the point at 'position' and rotation origin.
* @param {Vector2} skew Skew the drawing corners on X and Y axis, around the origin point.
*/
draw(texture, position, size, sourceRect, color, blendMode, rotation, origin, skew)
{
let sprite = new Sprite(texture, sourceRect);
sprite.position = position;
sprite.size = (typeof size === 'number') ? new Vector2(size, size) : size;
if (color) { sprite.color = color; }
if (blendMode) { sprite.blendMode = blendMode; }
if (rotation !== undefined) { sprite.rotation = rotation; }
if (origin) { sprite.origin = origin; }
if (skew) { sprite.skew = skew; }
this.drawSprite(sprite);
}
/**
* Draw a filled colored rectangle.
* @example
* // draw a 50x50 red rectangle at position 100x100, that will rotate over time
* Shaku.gfx.fillRect(new Shaku.utils.Rectangle(100, 100, 50, 50), Shaku.utils.Color.red, null, Shaku.gameTime.elapsed);
* @param {Rectangle} destRect Rectangle to fill.
* @param {Color|Array<Color>} color Rectangle fill color.
* @param {BlendModes} blend Blend mode.
* @param {Number} rotation Rotate the rectangle around its center.
*/
fillRect(destRect, color, blend, rotation)
{
this.draw(this.whiteTexture,
new Vector2(destRect.x + destRect.width / 2, destRect.y + destRect.height / 2),
new Vector2(destRect.width, destRect.height), null, color, blend || BlendModes.Opaque, rotation, null, null);
}
/**
* Draw a list of filled colored rectangles as a batch.
* @example
* // draw a 50x50 red rectangle at position 100x100, that will rotate over time
* Shaku.gfx.fillRects([new Shaku.utils.Rectangle(100, 100, 50, 50), new Shaku.utils.Rectangle(150, 150, 25, 25)], Shaku.utils.Color.red, null, Shaku.gameTime.elapsed);
* @param {Array<Rectangle>} destRects Rectangles to fill.
* @param {Array<Color>|Color} colors Rectangles fill color. If array is set, will assign each color to different vertex, starting from top-left.
* @param {BlendModes} blend Blend mode.
* @param {Array<Number>|Number} rotation Rotate the rectangles around its center.
*/
fillRects(destRects, colors, blend, rotation)
{
// build group
if (rotation === undefined) { rotation = 0; }
let group = new SpritesGroup();
for (let i = 0; i < destRects.length; ++i) {
let sprite = new Sprite(this.whiteTexture);
sprite.color = colors[i] || colors;
sprite.rotation = rotation.length ? rotation[i] : rotation;
sprite.blendMode = blend || BlendModes.Opaque;
let destRect = destRects[i];
sprite.size.set(destRect.width, destRect.height);
sprite.position.set(destRect.x + destRect.width / 2, destRect.y + destRect.width / 2);
sprite.origin.set(0.5, 0.5);
group.add(sprite);
}
// draw group
this.drawGroup(group);
}
/**
* Draw an outline colored rectangle.
* @example
* // draw a 50x50 red rectangle at position 100x100, that will rotate over time
* Shaku.gfx.outlineRect(new Shaku.utils.Rectangle(100, 100, 50, 50), Shaku.utils.Color.red, null, Shaku.gameTime.elapsed);
* @param {Rectangle} destRect Rectangle to draw outline for.
* @param {Color} color Rectangle outline color.
* @param {BlendModes} blend Blend mode.
* @param {Number} rotation Rotate the rectangle around its center.
*/
outlineRect(destRect, color, blend, rotation)
{
// get corners
let topLeft = destRect.getTopLeft();
let topRight = destRect.getTopRight();
let bottomRight = destRect.getBottomRight();
let bottomLeft = destRect.getBottomLeft();
// rotate vertices
if (rotation) {
// center rect
let center = destRect.getCenter();
topLeft.subSelf(center);
topRight.subSelf(center);
bottomLeft.subSelf(center);
bottomRight.subSelf(center);
// do rotation
let cos = Math.cos(rotation);
let sin = Math.sin(rotation);
function rotateVec(vector)
{
let x = (vector.x * cos - vector.y * sin);
let y = (vector.x * sin + vector.y * cos);
vector.set(x, y);
}
rotateVec(topLeft);
rotateVec(topRight);
rotateVec(bottomLeft);
rotateVec(bottomRight);
// return to original position
topLeft.addSelf(center);
topRight.addSelf(center);
bottomLeft.addSelf(center);
bottomRight.addSelf(center);
}
// draw rectangle with lines strip
this.drawLinesStrip([topLeft, topRight, bottomRight, bottomLeft], color, blend, true);
}
/**
* Draw an outline colored circle.
* @example
* // draw a circle at 50x50 with radius of 85
* Shaku.gfx.outlineCircle(new Shaku.utils.Circle(new Shaku.utils.Vector2(50, 50), 85), Shaku.utils.Color.red);
* @param {Circle} circle Circle to draw.
* @param {Color} color Circle outline color.
* @param {BlendModes} blend Blend mode.
* @param {Number} lineAmount How many lines to compose the circle from (bigger number = smoother circle).
*/
outlineCircle(circle, color, blend, lineAmount)
{
// defaults
if (lineAmount === undefined) { lineAmount = 32; }
// generate list of lines to draw circle
let lines = [];
const twicePi = 2 * Math.PI;
for (let i = 0; i <= lineAmount; i++) {
let point = new Vector2(
circle.center.x + (circle.radius * Math.cos(i * twicePi / lineAmount)),
circle.center.y + (circle.radius * Math.sin(i * twicePi / lineAmount))
);
lines.push(point);
}
// draw lines
this.drawLinesStrip(lines, color, blend);
}
/**
* Draw a filled colored circle.
* @example
* // draw a filled circle at 50x50 with radius of 85
* Shaku.gfx.fillCircle(new Shaku.utils.Circle(new Shaku.utils.Vector2(50, 50), 85), Shaku.utils.Color.red);
* @param {Circle} circle Circle to draw.
* @param {Color} color Circle fill color.
* @param {BlendModes} blend Blend mode.
* @param {Number} lineAmount How many lines to compose the circle from (bigger number = smoother circle).
*/
fillCircle(circle, color, blend, lineAmount)
{
// defaults
if (lineAmount === undefined) { lineAmount = 32; }
// generate list of lines to draw circle
let lines = [circle.center];
const twicePi = 2 * Math.PI;
for (let i = 0; i <= lineAmount; i++) {
let point = new Vector2(
circle.center.x + (circle.radius * Math.cos(i * twicePi / lineAmount)),
circle.center.y + (circle.radius * Math.sin(i * twicePi / lineAmount))
);
lines.push(point);
}
// prepare effect and buffers
let gl = this._gl;
this._fillShapesBuffer(lines, color, blend, (verts) => {
gl.drawArrays(gl.TRIANGLE_FAN, 0, verts.length);
this._drawCallsCount++;
}, true, 1);
}
/**
* Draw a list of filled colored circles using batches.
* @example
* // draw a filled circle at 50x50 with radius of 85
* Shaku.gfx.fillCircles([new Shaku.utils.Circle(new Shaku.utils.Vector2(50, 50), 85), new Shaku.utils.Circle(new Shaku.utils.Vector2(150, 125), 35)], Shaku.utils.Color.red);
* @param {Array<Circle>} circles Circles list to draw.
* @param {Color|Array<Color>} colors Circles fill color or a single color for all circles.
* @param {BlendModes} blend Blend mode.
* @param {Number} lineAmount How many lines to compose the circle from (bigger number = smoother circle).
*/
fillCircles(circles, colors, blend, lineAmount)
{
// defaults
if (lineAmount === undefined) { lineAmount = 32; }
// build vertices and colors arrays
let vertsArr = [];
let colorsArr = colors.length ? [] : null;
// generate vertices and colors
for (let i = 0; i < circles.length; ++i) {
let circle = circles[i];
let color = colors[i] || colors;
const twicePi = 2 * Math.PI;
for (let i = 0; i <= lineAmount; i++) {
// set vertices
vertsArr.push(new Vector2(
circle.center.x + (circle.radius * Math.cos(i * twicePi / lineAmount)),
circle.center.y + (circle.radius * Math.sin(i * twicePi / lineAmount))
));
vertsArr.push(new Vector2(
circle.center.x + (circle.radius * Math.cos((i+1) * twicePi / lineAmount)),
circle.center.y + (circle.radius * Math.sin((i+1) * twicePi / lineAmount))
));
vertsArr.push(circle.center);
// set colors
if (colorsArr) {
colorsArr.push(color);
colorsArr.push(color);
colorsArr.push(color);
}
}
}
// prepare effect and buffers
let gl = this._gl;
this._fillShapesBuffer(vertsArr, colorsArr || colors, blend, (verts) => {
gl.drawArrays(gl.TRIANGLES, 0, verts.length);
this._drawCallsCount++;
}, false, 3);
}
/**
* Draw a single line between two points.
* @example
* Shaku.gfx.drawLine(new Shaku.utils.Vector2(50,50), new Shaku.utils.Vector2(150,50), Shaku.utils.Color.red);
* @param {Vector2} startPoint Line start point.
* @param {Vector2} endPoint Line end point.
* @param {Color} color Line color.
* @param {BlendModes} blendMode Blend mode to draw lines with (default to Opaque).
*/
drawLine(startPoint, endPoint, color, blendMode)
{
return this.drawLines([startPoint, endPoint], color, blendMode, false);
}
/**
* Draw a strip of lines between an array of points.
* @example
* let lines = [new Shaku.utils.Vector2(50,50), new Shaku.utils.Vector2(150,50), new Shaku.utils.Vector2(150,150)];
* let colors = [Shaku.utils.Color.random(), Shaku.utils.Color.random(), Shaku.utils.Color.random()];
* Shaku.gfx.drawLinesStrip(lines, colors);
* @param {Array<Vector2>} points Points to draw line between.
* @param {Color|Array<Color>} colors Single lines color if you want one color for all lines, or an array of colors per segment.
* @param {BlendModes} blendMode Blend mode to draw lines with (default to Opaque).
* @param {Boolean} looped If true, will also draw a line from last point back to first point.
*/
drawLinesStrip(points, colors, blendMode, looped)
{
// prepare effect and buffers
let gl = this._gl;
// do loop - note: we can't use gl.LINE_LOOPED in case we need multiple buffers inside '_fillShapesBuffer' which will invoke more than one draw
if (looped) {
points = points.slice(0);
points.push(points[0]);
if (colors && colors.length) {
colors = colors.slice(0);
colors.push(colors[0]);
}
}
// draw lines
this._fillShapesBuffer(points, colors, blendMode, (verts) => {
gl.drawArrays(gl.LINE_STRIP, 0, verts.length);
this._drawCallsCount++;
}, true, 2);
}
/**
* Draw a list of lines from an array of points.
* @example
* let lines = [new Shaku.utils.Vector2(50,50), new Shaku.utils.Vector2(150,50), new Shaku.utils.Vector2(150,150)];
* let colors = [Shaku.utils.Color.random(), Shaku.utils.Color.random(), Shaku.utils.Color.random()];
* Shaku.gfx.drawLines(lines, colors);
* @param {Array<Vector2>} points Points to draw line between.
* @param {Color|Array<Color>} colors Single lines color if you want one color for all lines, or an array of colors per segment.
* @param {BlendModes} blendMode Blend mode to draw lines with (default to Opaque).
*/
drawLines(points, colors, blendMode)
{
// prepare effect and buffers
let gl = this._gl;
this._fillShapesBuffer(points, colors, blendMode, (verts) => {
gl.drawArrays(gl.LINES, 0, verts.length);
this._drawCallsCount++;
}, true, 2);
}
/**
* Draw a single point from vector.
* @example
* Shaku.gfx.drawPoint(new Shaku.utils.Vector2(50,50), Shaku.utils.Color.random());
* @param {Vector2} point Point to draw.
* @param {Color} color Point color.
* @param {BlendModes} blendMode Blend mode to draw point with (default to Opaque).
*/
drawPoint(point, color, blendMode)
{
return this.drawPoints([point], [color], blendMode);
}
/**
* Draw a list of points from an array of vectors.
* @example
* let points = [new Shaku.utils.Vector2(50,50), new Shaku.utils.Vector2(150,50), new Shaku.utils.Vector2(150,150)];
* let colors = [Shaku.utils.Color.random(), Shaku.utils.Color.random(), Shaku.utils.Color.random()];
* Shaku.gfx.drawPoints(points, colors);
* @param {Array<Vector2>} points Points to draw.
* @param {Color|Array<Color>} colors Single color if you want one color for all points, or an array of colors per point.
* @param {BlendModes} blendMode Blend mode to draw points with (default to Opaque).
*/
drawPoints(points, colors, blendMode)
{
let gl = this._gl;
this._fillShapesBuffer(points, colors, blendMode, (verts) => {
gl.drawArrays(gl.POINTS, 0, verts.length);
this._drawCallsCount++;
}, false, 1);
}
/**
* Make the renderer canvas centered.
*/
centerCanvas()
{
let canvas = this._canvas;
let parent = canvas.parentElement;
let pwidth = Math.min(parent.clientWidth, window.innerWidth);
let pheight = Math.min(parent.clientHeight, window.innerHeight);
canvas.style.left = Math.round(pwidth / 2 - canvas.clientWidth / 2) + 'px';
canvas.style.top = Math.round(pheight / 2 - canvas.clientHeight / 2) + 'px';
canvas.style.display = 'block';
canvas.style.position = 'relative';
}
/**
* Check if a given shape is currently in screen bounds, not taking camera into consideration.
* @param {Circle|Vector|Rectangle|Line} shape Shape to check.
* @returns {Boolean} True if given shape is in visible region.
*/
inScreen(shape)
{
let region = this.getRenderingRegion();
if (shape instanceof Circle) {
return region.collideCircle(shape);
}
else if (shape instanceof Vector2) {
return region.containsVector(shape);
}
else if (shape instanceof Rectangle) {
return region.collideRect(shape);
}
else if (shape instanceof Line) {
return region.collideLine(shape);
}
else {
throw new Error("Unknown shape type to check!");
}
}
/**
* Make a given vector the center of the camera.
* @param {Vector2} position Camera position.
* @param {Boolean} useCanvasSize If true, will always use cancas size when calculating center. If false and render target is set, will use render target's size.
*/
centerCamera(position, useCanvasSize)
{
let renderSize = useCanvasSize ? this.getCanvasSize() : this.getRenderingSize();
let halfScreenSize = renderSize.mul(0.5);
let centeredPos = position.sub(halfScreenSize);
this.setCameraOrthographic(centeredPos);
}
/**
* Prepare buffers, effect and blend mode for shape rendering.
* @private
*/
_fillShapesBuffer(points, colors, blendMode, onReady, isStrip, groupsSize)
{
// finish whatever we were drawing before
this.presentBufferedData();
// some defaults
colors = colors || _whiteColor;
blendMode = blendMode || BlendModes.Opaque;
// sanity - make sure colors and vertices match
if (colors.length !== undefined && colors.length !== points.length) {
_logger.error("When drawing shapes with colors array, the colors array and points array must have the same length!");
return;
}
// calculate actual max buffer size
let maxWithMargin = isStrip ? (this.maxLineSegments-1) : this.maxLineSegments;
if (groupsSize != 1) {
while (maxWithMargin % groupsSize !== 0) { maxWithMargin--; }
}
// if we have too many vertices, break to multiple calls
if (points.length > maxWithMargin) {
let sliceI = 0;
while (true) {
let start = sliceI * maxWithMargin;
let end = start + maxWithMargin;
if (isStrip && sliceI > 0) { start--; }
let subpoints = points.slice(start, end);
if (subpoints.length === 0) { break; }
let subcolors = (colors && colors.length) ? colors.slice(start, end) : colors;
this._fillShapesBuffer(subpoints, subcolors, blendMode, onReady, isStrip, groupsSize);
sliceI++;
}
return;
}
// basic params
let gl = this._gl;
let positionsBuff = this._dynamicBuffers.positionArray;
let colorsBuff = this._dynamicBuffers.colorsArray;
for (let i = 0; i < points.length; ++i) {
// set positions
positionsBuff[i*3 + 0] = points[i].x;
positionsBuff[i*3 + 1] = points[i].y;
positionsBuff[i*3 + 2] = points[i].z || 0;
// set colors
let color = colors[i] || colors;
colorsBuff[i*4 + 0] = color.r;
colorsBuff[i*4 + 1] = color.g;
colorsBuff[i*4 + 2] = color.b;
colorsBuff[i*4 + 3] = color.a;
}
// set blend mode if needed
this._setBlendMode(blendMode);
// prepare effect and texture
let mesh = new Mesh(this._dynamicBuffers.positionBuffer, null, this._dynamicBuffers.colorsBuffer, this._dynamicBuffers.indexBuffer, points.length);
this._activeEffect.prepareToDrawBatch(mesh, Matrix.identity);
this._setActiveTexture(this.whiteTexture);
// should we slice the arrays to more optimal size?
let shouldSliceArrays = points.length <= 8;
// copy position buffer
this._gl.bindBuffer(this._gl.ARRAY_BUFFER, this._dynamicBuffers.positionBuffer);
this._gl.bufferData(this._gl.ARRAY_BUFFER,
shouldSliceArrays ? this._dynamicBuffers.positionArray.slice(0, points.length * 3) : this._dynamicBuffers.positionArray,
this._gl.DYNAMIC_DRAW);
// copy color buffer
this._gl.bindBuffer(this._gl.ARRAY_BUFFER, this._dynamicBuffers.colorsBuffer);
this._gl.bufferData(this._gl.ARRAY_BUFFER,
shouldSliceArrays ? this._dynamicBuffers.colorsArray.slice(0, points.length * 4) : this._dynamicBuffers.colorsArray,
this._gl.DYNAMIC_DRAW);
// set indices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._dynamicBuffers.linesIndexBuffer);
this._currIndices = null;
// invoke the on-ready callback
onReady(points);
}
/**
* Draw sprites group as a batch.
* @private
* @param {SpritesGroup} group Group to draw.
* @param {Boolean} cullOutOfScreen If true will cull quads that are out of screen.
*/
_drawBatch(group, cullOutOfScreen)
{
// skip if empty
if (group._sprites.length === 0) { return; }
// finish previous drawings
this.presentBufferedData();
// get transform
let transform = group.getTransform();
// draw batch
this.spritesBatch.begin(this._activeEffect, transform);
this.spritesBatch.draw(group._sprites, cullOutOfScreen);
this.spritesBatch.end();
}
/**
* Set the currently active texture.
* @private
* @param {TextureAsset} texture Texture to set.
*/
_setActiveTexture(texture)
{
if (this._activeEffect.setTexture(texture)) {
this._setTextureFilter(texture.filter || this.defaultTextureFilter);
this._setTextureWrapMode(texture.wrapMode || this.defaultTextureWrapMode);
}
}
/**
* Get the blend modes enum.
* * AlphaBlend
* * Opaque
* * Additive
* * Multiply
* * Subtract
* * Screen
* * Overlay
* * Invert
* * DestIn
* * DestOut
*
* 
* @see BlendModes
*/
get BlendModes()
{
return BlendModes;
}
/**
* Get the wrap modes enum.
* * Clamp: when uv position exceed texture boundaries it will be clamped to the nearest border, ie repeat the edge pixels.
* * Repeat: when uv position exceed texture boundaries it will wrap back to the other side.
* * RepeatMirrored: when uv position exceed texture boundaries it will wrap back to the other side but also mirror the texture.
*
* 
* @see TextureWrapModes
*/
get TextureWrapModes()
{
return TextureWrapModes;
}
/**
* Get texture filter modes.
* * Nearest: no filtering, no mipmaps (pixelated).
* * Linear: simple filtering, no mipmaps (smooth).
* * NearestMipmapNearest: no filtering, sharp switching between mipmaps,
* * LinearMipmapNearest: filtering, sharp switching between mipmaps.
* * NearestMipmapLinear: no filtering, smooth transition between mipmaps.
* * LinearMipmapLinear: filtering, smooth transition between mipmaps.
*
* 
* @see TextureFilterModes
*/
get TextureFilterModes()
{
return TextureFilterModes;
}
/**
* Get number of actual WebGL draw calls we performed since the beginning of the frame.
* @returns {Number} Number of WebGL draw calls this frame.
*/
get drawCallsCount()
{
return this._drawCallsCount;
}
/**
* Clear screen to a given color.
* @example
* Shaku.gfx.clear(Shaku.utils.Color.cornflowerblue);
* @param {Color} color Color to clear screen to, or black if not set.
*/
clear(color)
{
this.presentBufferedData();
color = color || Color.black;
this._gl.clearColor(color.r, color.g, color.b, color.a);
this._gl.clear(this._gl.COLOR_BUFFER_BIT | this._gl.DEPTH_BUFFER_BIT);
}
/**
* Set texture mag and min filters.
* @private
* @param {TextureFilterModes} filter Texture filter to set.
*/
_setTextureFilter(filter)
{
if (!TextureFilterModes._values.has(filter)) { throw new Error("Invalid texture filter mode! Please pick a value from 'TextureFilterModes'."); }
let glMode = this._gl[filter];
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, glMode);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, glMode);
}
/**
* Set texture wrap mode on X and Y axis.
* @private
* @param {WrapModes} wrapX Wrap mode on X axis.
* @param {WrapModes} wrapY Wrap mode on Y axis.
*/
_setTextureWrapMode(wrapX, wrapY)
{
if (wrapY === undefined) { wrapY = wrapX; }
if (!TextureWrapModes._values.has(wrapX)) { throw new Error("Invalid texture wrap mode! Please pick a value from 'WrapModes'."); }
if (!TextureWrapModes._values.has(wrapY)) { throw new Error("Invalid texture wrap mode! Please pick a value from 'WrapModes'."); }
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl[wrapX]);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl[wrapY]);
}
/**
* Set blend mode before drawing.
* @private
* @param {BlendModes} blendMode New blend mode to set.
*/
_setBlendMode(blendMode)
{
if (this._lastBlendMode !== blendMode) {
// get gl context and set defaults
var gl = this._gl;
switch (blendMode)
{
case BlendModes.AlphaBlend:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case BlendModes.Opaque:
gl.disable(gl.BLEND);
break;
case BlendModes.Additive:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE);
break;
case BlendModes.Multiply:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFuncSeparate(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case BlendModes.Screen:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case BlendModes.Subtract:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
gl.blendEquationSeparate(gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD);
break;
case BlendModes.Invert:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE_MINUS_DST_COLOR, gl.ZERO);
gl.blendFuncSeparate(gl.ONE_MINUS_DST_COLOR, gl.ZERO, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case BlendModes.Overlay:
gl.enable(gl.BLEND);
if (gl.MAX) {
gl.blendEquation(gl.MAX);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
} else {
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ONE);
}
break;
case BlendModes.Darken:
gl.enable(gl.BLEND);
gl.blendEquation(gl.MIN);
gl.blendFuncSeparate(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
break;
case BlendModes.DestIn:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ZERO, gl.SRC_ALPHA);
break;
case BlendModes.DestOut:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_ALPHA);
// can also use: gl.blendFunc(gl.ONE_MINUS_DST_COLOR, gl.ONE_MINUS_SRC_COLOR);
break;
default:
throw new Error(`Unknown blend mode '${blendMode}'!`);
}
// store last blend mode
this._lastBlendMode = blendMode;
}
}
/**
* Present all currently buffered data.
*/
presentBufferedData()
{
this.__finishDrawingSprites();
}
/**
* Called internally before drawing a sprite to prepare some internal stuff.
* @private
*/
__startDrawingSprites(activeEffect, transform)
{
// check if should break due to effect or transform change
if (this.spritesBatch.drawing) {
if (this.spritesBatch._effect !== activeEffect || this.spritesBatch._transform !== transform) {
this.spritesBatch.end();
}
}
// start sprites batch
if (!this.spritesBatch.drawing) {
this.spritesBatch.begin(activeEffect, transform);
}
}
/**
* Called internally to present sprites batch, if currently drawing sprites.
* @private
*/
__finishDrawingSprites()
{
if (this.spritesBatch.drawing) {
this.spritesBatch.end();
}
}
/**
* @inheritdoc
* @private
*/
startFrame()
{
// reset some states
this._lastBlendMode = null;
this._drawCallsCount = 0;
}
/**
* @inheritdoc
* @private
*/
endFrame()
{
this.presentBufferedData();
}
/**
* @inheritdoc
* @private
*/
destroy()
{
_logger.warn("Cleaning up WebGL is not supported yet!");
}
} |
JavaScript | class Matrix
{
/**
* Create the matrix.
* @param values matrix values array.
* @param cloneValues if true or undefined, will clone values instead of just holding a reference to them.
*/
constructor(values, cloneValues)
{
if (cloneValues || cloneValues === undefined) {
this.values = values.slice(0);
}
else {
this.values = values;
}
}
/**
* Set the matrix values.
*/
set(v11, v12, v13, v14, v21, v22, v23, v24, v31, v32, v33, v34, v41, v42, v43, v44)
{
this.values = new Float32Array([ v11, v12, v13, v14,
v21, v22, v23, v24,
v31, v32, v33, v34,
v41, v42, v43, v44
]);
}
/**
* Clone the matrix.
* @returns {Matrix} Cloned matrix.
*/
clone()
{
let ret = new Matrix(this.values, true);
return ret;
}
/**
* Compare this matrix to another matrix.
* @param {Matrix} other Matrix to compare to.
* @returns {Boolean} If matrices are the same.
*/
equals(other)
{
if (other === this) { return true; }
if (!other) { return false; }
for (let i = 0; i < this.values.length; ++i) {
if (this.values[i] !== other.values[i]) { return false; }
}
return true;
}
/**
* Create an orthographic projection matrix.
* @returns {Matrix} a new matrix with result.
*/
static orthographic(left, right, bottom, top, near, far)
{
return new Matrix([
2 / (right - left), 0, 0, 0,
0, 2 / (top - bottom), 0, 0,
0, 0, 2 / (near - far), 0,
(left + right) / (left - right),
(bottom + top) / (bottom - top),
(near + far) / (near - far),
1,
], false);
}
/**
* Create a perspective projection matrix.
* @returns {Matrix} a new matrix with result.
*/
static perspective(fieldOfViewInRadians, aspectRatio, near, far)
{
var f = 1.0 / Math.tan(fieldOfViewInRadians / 2);
var rangeInv = 1 / (near - far);
return new Matrix([
f / aspectRatio, 0, 0, 0,
0, f, 0, 0,
0, 0, (near + far) * rangeInv, -1,
0, 0, near * far * rangeInv * 2, 0
], false);
}
/**
* Create a translation matrix.
* @returns {Matrix} a new matrix with result.
*/
static translate(x, y, z)
{
return new Matrix([
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x || 0, y || 0, z || 0, 1
], false);
}
/**
* Create a scale matrix.
* @returns {Matrix} a new matrix with result.
*/
static scale(x, y, z)
{
return new Matrix([
x || 1, 0, 0, 0,
0, y || 1, 0, 0,
0, 0, z || 1, 0,
0, 0, 0, 1
], false);
}
/**
* Create a rotation matrix around X axis.
* @returns {Matrix} a new matrix with result.
*/
static rotateX(a)
{
let sin = Math.sin;
let cos = Math.cos;
return new Matrix([
1, 0, 0, 0,
0, cos(a), -sin(a), 0,
0, sin(a), cos(a), 0,
0, 0, 0, 1
], false);
}
/**
* Create a rotation matrix around Y axis.
* @returns {Matrix} a new matrix with result.
*/
static rotateY(a)
{
let sin = Math.sin;
let cos = Math.cos;
return new Matrix([
cos(a), 0, sin(a), 0,
0, 1, 0, 0,
-sin(a), 0, cos(a), 0,
0, 0, 0, 1
], false);
}
/**
* Create a rotation matrix around Z axis.
* @returns {Matrix} a new matrix with result.
*/
static rotateZ(a)
{
let sin = Math.sin;
let cos = Math.cos;
return new Matrix([
cos(a), -sin(a), 0, 0,
sin(a), cos(a), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
], false);
}
/**
* Multiply two matrices.
* @returns {Matrix} a new matrix with result.
*/
static multiply(matrixA, matrixB)
{
// Slice the second matrix up into rows
let row0 = [matrixB.values[ 0], matrixB.values[ 1], matrixB.values[ 2], matrixB.values[ 3]];
let row1 = [matrixB.values[ 4], matrixB.values[ 5], matrixB.values[ 6], matrixB.values[ 7]];
let row2 = [matrixB.values[ 8], matrixB.values[ 9], matrixB.values[10], matrixB.values[11]];
let row3 = [matrixB.values[12], matrixB.values[13], matrixB.values[14], matrixB.values[15]];
// Multiply each row by matrixA
let result0 = multiplyMatrixAndPoint(matrixA.values, row0);
let result1 = multiplyMatrixAndPoint(matrixA.values, row1);
let result2 = multiplyMatrixAndPoint(matrixA.values, row2);
let result3 = multiplyMatrixAndPoint(matrixA.values, row3);
// Turn the result rows back into a single matrix
return new Matrix([
result0[0], result0[1], result0[2], result0[3],
result1[0], result1[1], result1[2], result1[3],
result2[0], result2[1], result2[2], result2[3],
result3[0], result3[1], result3[2], result3[3]
], false);
}
/**
* Multiply an array of matrices.
* @param {Array<Matrix>} matrices Matrices to multiply.
* @returns {Matrix} new matrix with multiply result.
*/
static multiplyMany(matrices)
{
let ret = matrices[0];
for(let i = 1; i < matrices.length; i++) {
ret = Matrix.multiply(ret, matrices[i]);
}
return ret;
}
/**
* Multiply two matrices and put result in first matrix.
* @returns {Matrix} matrixA, after it was modified.
*/
static multiplyIntoFirst(matrixA, matrixB)
{
// Slice the second matrix up into rows
let row0 = [matrixB.values[ 0], matrixB.values[ 1], matrixB.values[ 2], matrixB.values[ 3]];
let row1 = [matrixB.values[ 4], matrixB.values[ 5], matrixB.values[ 6], matrixB.values[ 7]];
let row2 = [matrixB.values[ 8], matrixB.values[ 9], matrixB.values[10], matrixB.values[11]];
let row3 = [matrixB.values[12], matrixB.values[13], matrixB.values[14], matrixB.values[15]];
// Multiply each row by matrixA
let result0 = multiplyMatrixAndPoint(matrixA.values, row0);
let result1 = multiplyMatrixAndPoint(matrixA.values, row1);
let result2 = multiplyMatrixAndPoint(matrixA.values, row2);
let result3 = multiplyMatrixAndPoint(matrixA.values, row3);
// Turn the result rows back into a single matrix
matrixA.set(
result0[0], result0[1], result0[2], result0[3],
result1[0], result1[1], result1[2], result1[3],
result2[0], result2[1], result2[2], result2[3],
result3[0], result3[1], result3[2], result3[3]
);
// return the first matrix after it was modified
return matrixA;
}
/**
* Multiply an array of matrices into the first matrix in the array.
* @param {Array<Matrix>} matrices Matrices to multiply.
* @returns {Matrix} first matrix in array, after it was modified.
*/
static multiplyManyIntoFirst(matrices)
{
let ret = matrices[0];
for(let i = 1; i < matrices.length; i++) {
ret = Matrix.multiplyIntoFirst(ret, matrices[i]);
}
return ret;
}
} |
JavaScript | class Mesh
{
/**
* Create the mesh object.
* @param {WebGLBuffer} positions vertices positions buffer.
* @param {WebGLBuffer} textureCoords vertices texture coords buffer.
* @param {WebGLBuffer} colorss vertices colors buffer.
* @param {WebGLBuffer} indices indices buffer.
* @param {Number} indicesCount how many indices we have.
*/
constructor(positions, textureCoords, colorsBuffer, indices, indicesCount)
{
this.positions = positions;
this.textureCoords = textureCoords;
this.colors = colorsBuffer;
this.indices = indices;
this.indicesCount = indicesCount;
this.__color = new Color(-1, -1, -1, -1);
Object.freeze(this);
}
/**
* Override the colors buffer, if possible.
* @param {WebGl} gl WebGL context.
* @param {Color} color Color to set.
*/
overrideColors(gl, color)
{
if (color.equals(this.__color)) { return; }
this.__color.copy(color);
gl.bindBuffer(gl.ARRAY_BUFFER, this.colors);
const colors = [];
for (let i = 0; i < this.indicesCount; ++i) {
colors.push(color.r);
colors.push(color.g);
colors.push(color.b);
colors.push(color.a);
}
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.DYNAMIC_DRAW);
}
} |
JavaScript | class MeshGenerator
{
/**
* Create the mesh generator.
*/
constructor(gl)
{
this._gl = gl;
}
/**
* Generate and return a textured quad.
* @returns {Mesh} Quad mesh.
*/
quad()
{
const gl = this._gl;
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
let x = 0.5; // <- 0.5 so total size would be 1x1
const positions = [
-x, -x, 0,
x, -x, 0,
-x, x, 0,
x, x, 0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
const textureCoordinates = [
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 1.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gl.STATIC_DRAW);
const colorsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
const colors = [
1,1,1,1,
1,1,1,1,
1,1,1,1,
1,1,1,1,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.DYNAMIC_DRAW);
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
const indices = [
0, 1, 3, 2
];
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
return new Mesh(positionBuffer, textureCoordBuffer, colorsBuffer, indexBuffer, indices.length);
}
} |
JavaScript | class Sprite
{
/**
* Create the texture object.
* @param {TextureAsset} texture Texture asset.
* @param {Rectangle} sourceRect Optional source rect.
*/
constructor(texture, sourceRect)
{
/**
* Texture to use for this sprite.
* @name Sprite#texture
* @type {TextureAsset}
*/
this.texture = texture;
/**
* Sprite position.
* If Vector3 is provided, the z value will be passed to vertices position in shader code.
* @name Sprite#position
* @type {Vector2|Vector3}
*/
this.position = new Vector2(0, 0);
/**
* Sprite size.
* If Vector3 is provided, the z value will be passed to the bottom vertices position in shader code, as position.z + size.z.
* @name Sprite#size
* @type {Vector2|Vector3}
*/
this.size = new Vector2(100, 100);
/**
* Sprite source rectangle in texture.
* Null will take entire texture.
* @name Sprite#sourceRect
* @type {Rectangle}
*/
this.sourceRect = sourceRect || null;
/**
* Sprite blend mode.
* @name Sprite#blendMode
* @type {BlendModes}
*/
this.blendMode = BlendModes.AlphaBlend;
/**
* Sprite rotation in radians.
* @name Sprite#rotation
* @type {Number}
*/
this.rotation = 0;
/**
* Sprite origin point.
* @name Sprite#origin
* @type {Vector2}
*/
this.origin = new Vector2(0.5, 0.5);
/**
* Skew the sprite corners on X and Y axis, around the origin point.
* @name Sprite#skew
* @type {Vector2}
*/
this.skew = new Vector2(0, 0);
/**
* Sprite color.
* If array is set, will assign each color to different vertex, starting from top-left.
* @name Sprite#color
* @type {Color|Array<Color>}
*/
this.color = Color.white;
}
/**
* Clone this sprite.
* @returns {Sprite} cloned sprite.
*/
clone()
{
let ret = new Sprite(this.texture, this.sourceRect);
ret.position = this.position.clone();
ret.size = this.size.clone();
ret.blendMode = this.blendMode;
ret.rotation = this.rotation;
ret.origin = this.origin.clone();
ret.color = this.color.clone();
return ret;
}
/**
* Check if this sprite is flipped around X axis.
* This is just a sugarcoat that returns if size.x < 0.
* @returns {Boolean} If sprite is flipped on X axis.
*/
get flipX()
{
return this.size.x < 0;
}
/**
* Flip sprite around X axis.
* This is just a sugarcoat that set size.x to negative or positive value, without changing its scale.
* @param {Boolean} flip Should we flip the sprite around X axis. If undefined, will take the negative of flipX current value, ie will toggle flipping.
*/
set flipX(flip)
{
if (flip === undefined) flip = !this.flipX;
this.size.x = Math.abs(this.size.x) * (flip ? -1 : 1);
return flip;
}
/**
* Check if this sprite is flipped around y axis.
* This is just a sugarcoat that returns if size.y < 0.
* @returns {Boolean} If sprite is flipped on Y axis.
*/
get flipY()
{
return this.size.y < 0;
}
/**
* Flip sprite around Y axis.
* This is just a sugarcoat that set size.y to negative or positive value, without changing its scale.
* @param {Boolean} flip Should we flip the sprite around Y axis. If undefined, will take the negative of flipY current value, ie will toggle flipping.
*/
set flipY(flip)
{
if (flip === undefined) flip = !this.flipY;
this.size.y = Math.abs(this.size.y) * (flip ? -1 : 1);
return flip;
}
} |
JavaScript | class SpriteBatch
{
/**
* Create the spritebatch.
* @param {Gfx} gfx Gfx manager.
*/
constructor(gfx)
{
this._gfx = gfx;
this._gl = gfx._gl;
this._positions = gfx._dynamicBuffers.positionArray;
this._uvs = gfx._dynamicBuffers.textureArray;
this._colors = gfx._dynamicBuffers.colorsArray;
this._positionsBuff = gfx._dynamicBuffers.positionBuffer;
this._uvsBuff = gfx._dynamicBuffers.textureCoordBuffer;
this._colorsBuff = gfx._dynamicBuffers.colorsBuffer;
this._indexBuff = gfx._dynamicBuffers.indexBuffer;
/**
* If true, will floor vertices positions before pushing them to batch.
*/
this.snapPixels = true;
/**
* If true, will slightly offset texture uv when rotating sprites, to prevent bleeding while using texture atlas.
*/
this.applyAntiBleeding = true;
}
/**
* Create and return a new vertex.
* @param {Vector2} position Vertex position.
* @param {Vector2} textureCoord Vertex texture coord.
* @param {Color} color Vertex color.
* @returns {Vertex} new vertex object.
*/
vertex(position, textureCoord, color)
{
return new Vertex(position, textureCoord, color);
}
/**
* Get if batch is currently drawing.
* @returns {Boolean} True if batch is drawing.
*/
get drawing()
{
return this._drawing;
}
/**
* Start drawing a batch.
* @param {Effect} effect Effect to use.
* @param {Matrix} transform Optional transformations to apply on all sprites.
*/
begin(effect, transform)
{
if (this._drawing) {
_logger.error("Start drawing a batch while already drawing a batch!");
}
if (effect) {
this._gfx.useEffect(effect);
}
this._effect = this._gfx._activeEffect;
this._currBlend = BlendModes.AlphaBlend;
this._currTexture = null;
this._currBatchCount = 0;
this._transform = transform;
this._drawing = true;
}
/**
* Finish drawing batch (and render whatever left in buffers).
*/
end()
{
if (!this._drawing) {
_logger.error("Stop drawing a batch without starting it first!");
}
if (this._currBatchCount) {
this._drawCurrentBatch();
}
this._drawing = false;
}
/**
* Set the currently active texture.
* @param {Texture} texture Texture to set.
*/
setTexture(texture)
{
if (texture !== this._currTexture) {
if (this._currBatchCount) {
this._drawCurrentBatch();
}
this._currTexture = texture;
}
}
/**
* Add sprite to batch.
* Note: changing texture or blend mode may trigger a draw call.
* @param {Sprite|Array<Sprite>} sprites Sprite or multiple sprites to draw.
* @param {Boolean} cullOutOfScreen If true, will cull sprites that are not visible.
*/
draw(sprites, cullOutOfScreen)
{
// if single sprite, turn to array
if (sprites.length === undefined) { sprites = [sprites]; }
// get visible region
let region = cullOutOfScreen ? this._gfx.getRenderingRegion() : null;
// get buffers
let positions = this._positions;
let uvs = this._uvs;
let colors = this._colors;
for (let sprite of sprites) {
// if texture changed, blend mode changed, or we have too many indices - draw current batch
if (this._currBatchCount) {
if ((this._currBatchCount >= this.batchSpritesCount) ||
(sprite.blendMode !== this._currBlend) ||
(sprite.texture !== this._currTexture)) {
this._drawCurrentBatch();
}
}
// set texture and blend (used internally when drawing batch)
this._currTexture = sprite.texture;
this._currBlend = sprite.blendMode;
// calculate vertices positions
let sizeX = sprite.size.x;
let sizeY = sprite.size.y;
let left = -sizeX * sprite.origin.x;
let top = -sizeY * sprite.origin.y;
// calculate corners
let topLeft = new Vector2(left, top);
let topRight = new Vector2(left + sizeX, top);
let bottomLeft = new Vector2(left, top + sizeY);
let bottomRight = new Vector2(left + sizeX, top + sizeY);
// apply skew
if (sprite.skew) {
if (sprite.skew.x) {
topLeft.x += sprite.skew.x * sprite.origin.y;
topRight.x += sprite.skew.x * sprite.origin.y;
bottomLeft.x -= sprite.skew.x * (1 - sprite.origin.y);
bottomRight.x -= sprite.skew.x * (1 - sprite.origin.y);
}
if (sprite.skew.y) {
topLeft.y += sprite.skew.y * sprite.origin.x;
bottomLeft.y += sprite.skew.y * sprite.origin.x;
topRight.y -= sprite.skew.y * (1 - sprite.origin.x);
bottomRight.y -= sprite.skew.y * (1 - sprite.origin.x);
}
}
// apply rotation
if (sprite.rotation) {
let cos = Math.cos(sprite.rotation);
let sin = Math.sin(sprite.rotation);
function rotateVec(vector)
{
let x = (vector.x * cos - vector.y * sin);
let y = (vector.x * sin + vector.y * cos);
vector.set(x, y);
}
rotateVec(topLeft);
rotateVec(topRight);
rotateVec(bottomLeft);
rotateVec(bottomRight);
}
// add sprite position
topLeft.addSelf(sprite.position);
topRight.addSelf(sprite.position);
bottomLeft.addSelf(sprite.position);
bottomRight.addSelf(sprite.position);
// snap pixels
if (this.snapPixels)
{
topLeft.floorSelf();
topRight.floorSelf();
bottomLeft.floorSelf();
bottomRight.floorSelf();
}
// optional z position
let z = sprite.position.z || 0;
let zDepth = sprite.size.z || 0;
// cull out-of-screen sprites
if (cullOutOfScreen)
{
let destRect = Rectangle.fromPoints([topLeft, topRight, bottomLeft, bottomRight]);
if (!region.collideRect(destRect)) {
continue;
}
}
// update positions buffer
let pi = this._currBatchCount * 4 * 3;
positions[pi+0] = topLeft.x; positions[pi+1] = topLeft.y; positions[pi+2] = z;
positions[pi+3] = topRight.x; positions[pi+4] = topRight.y; positions[pi+5] = z;
positions[pi+6] = bottomLeft.x; positions[pi+7] = bottomLeft.y; positions[pi+8] = z + zDepth;
positions[pi+9] = bottomRight.x; positions[pi+10] = bottomRight.y; positions[pi+11] = z + zDepth;
// add uvs
let uvi = this._currBatchCount * 4 * 2;
if (sprite.sourceRect) {
const uvTl = {x: sprite.sourceRect.x / this._currTexture.width, y: sprite.sourceRect.y / this._currTexture.height};
const uvBr = {x: uvTl.x + (sprite.sourceRect.width / this._currTexture.width), y: uvTl.y + (sprite.sourceRect.height / this._currTexture.height)};
if (sprite.rotation && this.applyAntiBleeding) {
let marginX = 0.015 / this._currTexture.width;
let marginY = 0.015 / this._currTexture.height;
uvTl.x += marginX;
uvBr.x -= marginX * 2;
uvTl.y += marginY;
uvBr.y -= marginY * 2;
}
uvs[uvi+0] = uvTl.x; uvs[uvi+1] = uvTl.y;
uvs[uvi+2] = uvBr.x; uvs[uvi+3] = uvTl.y;
uvs[uvi+4] = uvTl.x; uvs[uvi+5] = uvBr.y;
uvs[uvi+6] = uvBr.x; uvs[uvi+7] = uvBr.y;
}
else {
uvs[uvi+0] = 0; uvs[uvi+1] = 0;
uvs[uvi+2] = 1; uvs[uvi+3] = 0;
uvs[uvi+4] = 0; uvs[uvi+5] = 1;
uvs[uvi+6] = 1; uvs[uvi+7] = 1;
}
// add colors
let ci = this._currBatchCount * 4 * 4;
// array of colors
if (sprite.color instanceof Array) {
let lastColor = sprite.color[0];
for (let x = 0; x < 4; ++x) {
let curr = (sprite.color[x] || lastColor);
colors[ci + x*4 + 0] = curr.r;
colors[ci + x*4 + 1] = curr.g;
colors[ci + x*4 + 2] = curr.b;
colors[ci + x*4 + 3] = curr.a;
lastColor = curr;
}
}
// single color
else {
for (let x = 0; x < 4; ++x) {
colors[ci + x*4 + 0] = sprite.color.r;
colors[ci + x*4 + 1] = sprite.color.g;
colors[ci + x*4 + 2] = sprite.color.b;
colors[ci + x*4 + 3] = sprite.color.a;
}
}
// increase sprites count
this._currBatchCount++;
}
}
/**
* Push vertices directly to batch.
* @param {Array<Vertex>} vertices Vertices to push.
*/
pushVertices(vertices)
{
// sanity
if (!vertices || vertices.length !== 4) {
throw new Error("Vertices must be array of 4 values!");
}
// get buffers and offset
let positions = this._positions;
let uvs = this._uvs;
let colors = this._colors;
// push colors
for (let i = 0; i < vertices.length; ++i)
{
let vertex = vertices[i];
let ci = (this._currBatchCount * (4 * 4)) + (i * 4);
colors[ci + 0] = vertex.color.r;
colors[ci + 1] = vertex.color.g;
colors[ci + 2] = vertex.color.b;
colors[ci + 3] = vertex.color.a;
}
// push positions
let topLeft = vertices[0].position;
let topRight = vertices[1].position;
let bottomLeft = vertices[2].position;
let bottomRight = vertices[3].position;
let pi = this._currBatchCount * 4 * 3;
positions[pi+0] = topLeft.x; positions[pi+1] = topLeft.y; positions[pi+2] = topLeft.z || 0;
positions[pi+3] = topRight.x; positions[pi+4] = topRight.y; positions[pi+5] = topRight.z || 0;
positions[pi+6] = bottomLeft.x; positions[pi+7] = bottomLeft.y; positions[pi+8] = bottomLeft.z || 0;
positions[pi+9] = bottomRight.x; positions[pi+10] = bottomRight.y; positions[pi+11] = bottomRight.z || 0;
// set texture coords
let uvi = (this._currBatchCount * (4 * 2));
uvs[uvi++] = vertices[0].textureCoord.x / this._currTexture.width;
uvs[uvi++] = vertices[0].textureCoord.y / this._currTexture.height;
uvs[uvi++] = vertices[1].textureCoord.x / this._currTexture.width;
uvs[uvi++] = vertices[1].textureCoord.y / this._currTexture.height;
uvs[uvi++] = vertices[2].textureCoord.x / this._currTexture.width;
uvs[uvi++] = vertices[2].textureCoord.y / this._currTexture.height;
uvs[uvi++] = vertices[3].textureCoord.x / this._currTexture.width;
uvs[uvi++] = vertices[3].textureCoord.y / this._currTexture.height;
// increase batch count
this._currBatchCount++;
}
/**
* How many sprites we can have in batch, in total.
*/
get batchSpritesCount()
{
return this._gfx.batchSpritesCount;
}
/**
* Draw current batch.
* @private
*/
_drawCurrentBatch()
{
// get some members
let gl = this._gl;
let transform = this._transform;
let positionArray = this._positions;
let textureArray = this._uvs;
let colorsArray = this._colors;
let positionBuffer = this._positionsBuff;
let textureCoordBuffer = this._uvsBuff;
let colorsBuffer = this._colorsBuff;
let indexBuffer = this._indexBuff;
// some sanity checks
if (this._effect !== this._gfx._activeEffect) {
_logger.error("Effect changed while drawing batch!");
}
// set blend mode if needed
this._gfx._setBlendMode(this._currBlend);
// prepare effect and texture
let mesh = new Mesh(positionBuffer, textureCoordBuffer, colorsBuffer, indexBuffer, this._currBatchCount * 6);
this._gfx._activeEffect.prepareToDrawBatch(mesh, transform || Matrix.identity);
this._gfx._setActiveTexture(this._currTexture);
// should we slice the arrays?
let shouldSliceArrays = this._currBatchCount < this.batchSpritesCount / 2;
// copy position buffer
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER,
shouldSliceArrays ? positionArray.slice(0, this._currBatchCount * 4 * 3) : positionArray,
gl.DYNAMIC_DRAW);
// copy texture buffer
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER,
shouldSliceArrays ? textureArray.slice(0, this._currBatchCount * 4 * 2) : textureArray,
gl.DYNAMIC_DRAW);
// copy color buffer
gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
gl.bufferData(gl.ARRAY_BUFFER,
shouldSliceArrays ? colorsArray.slice(0, this._currBatchCount * 4 * 4) : colorsArray,
gl.DYNAMIC_DRAW);
// set indices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
this._currIndices = null;
// draw elements
gl.drawElements(gl.TRIANGLES, this._currBatchCount * 6, gl.UNSIGNED_SHORT, 0);
this._gfx._drawCallsCount++;
// reset current counter
this._currBatchCount = 0;
}
} |
JavaScript | class Vertex
{
/**
* Create the vertex data.
* @param {Vector2|Vector3} position Vertex position.
* @param {Vector2} textureCoord Vertex texture coord (in pixels).
* @param {Color} color Vertex color (undefined will default to white).
*/
constructor(position, textureCoord, color)
{
this.position = position;
this.textureCoord = textureCoord;
this.color = color || Color.white;
}
} |
JavaScript | class SpritesGroup
{
/**
* Create the group object.
*/
constructor()
{
this._sprites = [];
this.rotation = 0;
this.position = new Vector2(0, 0);
this.scale = new Vector2(1, 1);
}
/**
* Iterate all sprites.
* @param {Function} callback Callback to run on all sprites in group.
*/
forEach(callback)
{
this._sprites.forEach(callback);
}
/**
* Set color for all sprites in group.
* @param {Color} color Color to set.
*/
setColor(color)
{
for (let i = 0; i < this._sprites.length; ++i) {
this._sprites[i].color.copy(color);
}
}
/**
* Get group's transformations.
* @returns {Matrix} Transformations matrix, or null if there's nothing to apply.
*/
getTransform()
{
let matrices = [];
if ((this.position.x !== 0) || (this.position.y !== 0))
{
matrices.push(Matrix.translate(this.position.x, this.position.y, 0));
}
if (this.rotation)
{
matrices.push(Matrix.rotateZ(-this.rotation));
}
if ((this.scale.x !== 1) || (this.scale.y !== 1))
{
matrices.push(Matrix.scale(this.scale.x, this.scale.y));
}
if (matrices.length === 0) { return null };
if (matrices.length === 1) { return matrices[0]; }
return Matrix.multiplyMany(matrices);
}
/**
* Adds a sprite to group.
* @param {Sprite} sprite Sprite to add.
* @returns {Sprite} The newly added sprite.
*/
add(sprite)
{
this._sprites.push(sprite);
return sprite;
}
/**
* Remove a sprite from group.
* @param {Sprite} sprite Sprite to remove.
*/
remove(sprite)
{
for (let i = 0; i < this._sprites.length; ++i) {
if (this._sprites[i] === sprite) {
this._sprites.splice(i, 1);
return;
}
}
}
/**
* Shift first sprite element.
* @returns {Sprite} The removed sprite.
*/
shift()
{
return this._sprites.shift();
}
/**
* Sort sprites.
* @param {Function} compare Comparer method.
*/
sort(compare)
{
this._sprites.sort(compare);
}
/**
* Sort by texture and blend mode for maximum efficiency in batching.
* This will change sprites order.
*/
sortForBatching()
{
this._sprites.sort((a,b) => {
let at = a.texture.url + a.blendMode;
let bt = b.texture.url + b.blendMode;
return (at > bt) ? 1 : ((bt > at) ? -1 : 0);
});
}
/**
* Sprites count in group.
* @returns {Number} Number of sprites in group.
*/
get count()
{
return this._sprites.length;
}
} |
JavaScript | class Input extends IManager
{
/**
* Create the manager.
*/
constructor()
{
super();
// callbacks and target we listen to input on
this._callbacks = null;
this._targetElement = window;
// export mouse and keyboard keys
this.MouseButtons = MouseButtons;
this.KeyboardKeys = KeyboardKeys;
// if true, will prevent default events by calling preventDefault()
this.preventDefaults = false;
// by default, when holding wheel button down browsers will turn into special page scroll mode and will not emit mouse move events.
// if this property is set to true, StInput will prevent this behavior, so we could still get mouse delta while mouse wheel is held down.
this.enableMouseDeltaWhileMouseWheelDown = true;
// if true, will disable the context menu (right click)
this.disableContextMenu = true;
// should we reset on focus lost?
this.resetOnFocusLoss = true;
// set base state members
this._resetAll();
}
/**
* @inheritdoc
* @private
**/
setup()
{
return new Promise((resolve, reject) => {
_logger.info("Setup input manager..");
// if target element is a method, invoke it
if (typeof this._targetElement === 'function') {
this._targetElement = this._targetElement();
if (!this._targetElement) {
throw new Error("Input target element was set to be a method, but the returned value was invalid!");
}
}
// get element to attach to
let element = this._targetElement;
// to make sure keyboard input would work if provided with canvas entity
if (element.tabIndex === -1 || element.tabIndex === undefined) {
element.tabIndex = 1000;
}
// focus on target element
window.setTimeout(() => element.focus(), 0);
// set all the events to listen to
var _this = this;
this._callbacks = {
'mousedown': function(event) {_this._onMouseDown(event); if (this.preventDefaults) event.preventDefault(); },
'mouseup': function(event) {_this._onMouseUp(event); if (this.preventDefaults) event.preventDefault(); },
'mousemove': function(event) {_this._onMouseMove(event); if (this.preventDefaults) event.preventDefault(); },
'keydown': function(event) {_this._onKeyDown(event); if (this.preventDefaults) event.preventDefault(); },
'keyup': function(event) {_this._onKeyUp(event); if (this.preventDefaults) event.preventDefault(); },
'blur': function(event) {_this._onBlur(event); if (this.preventDefaults) event.preventDefault(); },
'wheel': function(event) {_this._onMouseWheel(event); },
'touchstart': function(event) {_this._onTouchStart(event); if (this.preventDefaults) event.preventDefault(); },
'touchend': function(event) {_this._onMouseUp(event); if (this.preventDefaults) event.preventDefault(); },
'touchmove': function(event) {_this._onTouchMove(event); if (this.preventDefaults) event.preventDefault(); },
'contextmenu': function(event) { if (_this.disableContextMenu) { event.preventDefault(); } },
};
// reset all data to init initial state
this._resetAll();
// register all callbacks
for (var event in this._callbacks) {
element.addEventListener(event, this._callbacks[event], false);
}
// if we have a specific element, still capture mouse release outside of it
if (element !== window) {
window.addEventListener('mouseup', this._callbacks['mouseup'], false);
window.addEventListener('touchend', this._callbacks['touchend'], false);
}
resolve();
});
}
/**
* @inheritdoc
* @private
**/
startFrame()
{
}
/**
* @inheritdoc
* @private
**/
destroy()
{
// unregister all callbacks
if (this._callbacks)
{
let element = this._targetElement;
for (var event in this._callbacks) {
element.removeEventListener(event, this._callbacks[event]);
}
if (element !== window) {
window.removeEventListener('mouseup', this._callbacks['mouseup'], false);
window.removeEventListener('touchend', this._callbacks['touchend'], false);
}
this._callbacks = null;
}
}
/**
* Set the target element to attach input to. If not called, will just use the entire document.
* Must be called *before* initializing Shaku. This can also be a method to invoke while initializing.
* @example
* // the following will use whatever canvas the gfx manager uses as input element.
* // this means mouse offset will also be relative to this element.
* Shaku.input.setTargetElement(() => Shaku.gfx.canvas);
* @param {Element} element Element to attach input to.
*/
setTargetElement(element)
{
if (this._callbacks) { throw new Error("'setTargetElement() must be called before initializing the input manager!"); }
this._targetElement = element;
}
/**
* Reset all internal data and states.
* @private
*/
_resetAll()
{
// mouse states
this._mousePos = new Vector2();
this._mousePrevPos = new Vector2();
this._mouseState = {};
this._mousePrevState = {};
this._mouseWheel = 0;
// keyboard keys
this._keyboardState = {};
this._keyboardPrevState = {};
// reset touch started state
this._touchStarted = false;
}
/**
* Get mouse position.
* @returns {Vector2} Mouse position.
*/
get mousePosition()
{
return this._mousePos.clone();
}
/**
* Get mouse previous position (before the last endFrame() call).
* @returns {Vector2} Mouse position in previous frame.
*/
get prevMousePosition()
{
return (this._mousePrevPos || this._mousePos).clone();
}
/**
* Get mouse movement since last endFrame() call.
* @returns {Vector2} Mouse change since last frame.
*/
get mouseDelta()
{
// no previous position? return 0,0.
if (!this._mousePrevPos) {
return Vector2.zero;
}
// return mouse delta
return new Vector2(this._mousePos.x - this._mousePrevPos.x, this._mousePos.y - this._mousePrevPos.y);
}
/**
* Get if mouse is currently moving.
* @returns {Boolean} True if mouse moved since last frame, false otherwise.
*/
get mouseMoving()
{
return (this._mousePrevPos && !this._mousePrevPos.equals(this._mousePos));
}
/**
* Get if mouse button was pressed this frame.
* @param {MouseButtons} button Button code (defults to MouseButtons.left).
* @returns {Boolean} True if mouse button is currently down, but was up in previous frame.
*/
mousePressed(button = 0)
{
if (button === undefined) throw new Error("Invalid button code!");
return Boolean(this._mouseState[button] && !this._mousePrevState[button]);
}
/**
* Get if mouse button is currently pressed.
* @param {MouseButtons} button Button code (defults to MouseButtons.left).
* @returns {Boolean} true if mouse button is currently down, false otherwise.
*/
mouseDown(button = 0)
{
if (button === undefined) throw new Error("Invalid button code!");
return Boolean(this._mouseState[button]);
}
/**
* Get if mouse button is currently not down.
* @param {MouseButtons} button Button code (defults to MouseButtons.left).
* @returns {Boolean} true if mouse button is currently up, false otherwise.
*/
mouseUp(button = 0)
{
if (button === undefined) throw new Error("Invalid button code!");
return Boolean(!this.mouseDown(button));
}
/**
* Get if mouse button was released in current frame.
* @param {MouseButtons} button Button code (defults to MouseButtons.left).
* @returns {Boolean} True if mouse was down last frame, but released in current frame.
*/
mouseReleased(button = 0)
{
if (button === undefined) throw new Error("Invalid button code!");
return Boolean(!this._mouseState[button] && this._mousePrevState[button]);
}
/**
* Get if keyboard key is currently pressed down.
* @param {KeyboardKeys} key Keyboard key code.
* @returns {boolean} True if keyboard key is currently down, false otherwise.
*/
keyDown(key)
{
if (key === undefined) throw new Error("Invalid key code!");
return Boolean(this._keyboardState[key]);
}
/**
* Get if keyboard key is currently not down.
* @param {KeyboardKeys} key Keyboard key code.
* @returns {Boolean} True if keyboard key is currently up, false otherwise.
*/
keyUp(key)
{
if (key === undefined) throw new Error("Invalid key code!");
return Boolean(!this.keyDown(key));
}
/**
* Get if a keyboard button was released in current frame.
* @param {KeyboardKeys} button Keyboard key code.
* @returns {Boolean} True if key was down last frame, but released in current frame.
*/
keyReleased(key)
{
if (key === undefined) throw new Error("Invalid key code!");
return Boolean(!this._keyboardState[key] && this._keyboardPrevState[key]);
}
/**
* Get if keyboard key was pressed this frame.
* @param {KeyboardKeys} key Keyboard key code.
* @returns {Boolean} True if key is currently down, but was up in previous frame.
*/
keyPressed(key)
{
if (key === undefined) throw new Error("Invalid key code!");
return Boolean(this._keyboardState[key] && !this._keyboardPrevState[key]);
}
/**
* Get if any of the shift keys are currently down.
* @returns {Boolean} True if there's a shift key pressed down.
*/
get shiftDown()
{
return Boolean(this.keyDown(this.KeyboardKeys.shift));
}
/**
* Get if any of the Ctrl keys are currently down.
* @returns {Boolean} True if there's a Ctrl key pressed down.
*/
get ctrlDown()
{
return Boolean(this.keyDown(this.KeyboardKeys.ctrl));
}
/**
* Get if any of the Alt keys are currently down.
* @returns {Boolean} True if there's an Alt key pressed down.
*/
get altDown()
{
return Boolean(this.keyDown(this.KeyboardKeys.alt));
}
/**
* Get if any keyboard key is currently down.
* @returns {Boolean} True if there's a key pressed down.
*/
get anyKeyDown()
{
for (var key in this._keyboardState) {
if (this._keyboardState[key]) {
return true;
}
}
return false;
}
/**
* Get if any mouse button is down.
* @returns {Boolean} True if any of the mouse buttons are pressed.
*/
get anyMouseButtonDown()
{
for (var key in this._mouseState) {
if (this._mouseState[key]) {
return true;
}
}
return false;
}
/**
* Return if a mouse or keyboard state in a generic way, used internally.
* @private
* @param {string} code Keyboard or mouse code.
* For mouse buttons: mouse_left, mouse_right or mouse_middle.
* For keyboard buttons: use one of the keys of KeyboardKeys (for example 'a', 'alt', 'up_arrow', etc..)
* For numbers (0-9): you can use the number.
* @param {Function} mouseCheck Callback to use to return value if its a mouse button code.
* @param {Function} keyboardCheck Callback to use to return value if its a keyboard key code.
*/
_getValueWithCode(code, mouseCheck, keyboardCheck)
{
// make sure code is string
code = String(code);
// if starts with 'mouse' its for mouse button events
if (code.indexOf('mouse_') === 0) {
// get mouse code name
var codename = code.split('_')[1];
// return if mouse down
return mouseCheck.call(this, this.MouseButtons[codename]);
}
// if its just a number, add the 'n' prefix
if (!isNaN(parseInt(code)) && code.length === 1) {
code = 'n' + code;
}
// if not start with 'mouse', treat it as a keyboard key
return keyboardCheck.call(this, this.KeyboardKeys[code]);
}
/**
* Return if a mouse or keyboard button is currently down.
* @param {string|Array<String>} code Keyboard or mouse code. Can be array of codes to test if any of them is down.
* For mouse buttons: mouse_left, mouse_right or mouse_middle.
* For keyboard buttons: use one of the keys of KeyboardKeys (for example 'a', 'alt', 'up_arrow', etc..)
* For numbers (0-9): you can use the number.
* @returns {Boolean} True if key or mouse button are down.
*/
down(code)
{
if (!(code instanceof Array)) { code = [code]; }
for (let c of code) {
if (Boolean(this._getValueWithCode(c, this.mouseDown, this.keyDown))) {
return true;
}
}
return false;
}
/**
* Return if a mouse or keyboard button was released in this frame.
* @param {string|Array<String>} code Keyboard or mouse code. Can be array of codes to test if any of them is released.
* For mouse buttons: mouse_left, mouse_right or mouse_middle.
* For keyboard buttons: use one of the keys of KeyboardKeys (for example 'a', 'alt', 'up_arrow', etc..)
* For numbers (0-9): you can use the number.
* @returns {Boolean} True if key or mouse button were down in previous frame, and released this frame.
*/
released(code)
{
if (!(code instanceof Array)) { code = [code]; }
for (let c of code) {
if (Boolean(this._getValueWithCode(c, this.mouseReleased, this.keyReleased))) {
return true;
}
}
return false;
}
/**
* Return if a mouse or keyboard button was pressed in this frame.
* @param {string|Array<String>} code Keyboard or mouse code. Can be array of codes to test if any of them is pressed.
* For mouse buttons: mouse_left, mouse_right or mouse_middle.
* For keyboard buttons: use one of the keys of KeyboardKeys (for example 'a', 'alt', 'up_arrow', etc..)
* For numbers (0-9): you can use the number.
* @returns {Boolean} True if key or mouse button where up in previous frame, and pressed this frame.
*/
pressed(code)
{
if (!(code instanceof Array)) { code = [code]; }
for (let c of code) {
if (Boolean(this._getValueWithCode(c, this.mousePressed, this.keyPressed))) {
return true;
}
}
return false;
}
/**
* Get mouse wheel sign.
* @returns {Number} Mouse wheel sign (-1 or 1) for wheel scrolling that happened during this frame.
* Will return 0 if mouse wheel is not currently being used.
*/
get mouseWheelSign()
{
return Math.sign(this._mouseWheel);
}
/**
* Get mouse wheel value.
* @returns {Number} Mouse wheel value.
*/
get mouseWheel()
{
return this._mouseWheel;
}
/**
* @inheritdoc
* @private
**/
endFrame()
{
// set mouse previous position and clear mouse move cache
this._mousePrevPos = this._mousePos.clone();
// set previous keyboard state
this._keyboardPrevState = {};
for (var key in this._keyboardState) {
this._keyboardPrevState[key] = this._keyboardState[key];
}
// set previous mouse state
this._mousePrevState = {};
for (var key in this._mouseState) {
this._mousePrevState[key] = this._mouseState[key];
}
// apply touch start event
if (this._touchStarted)
{
this._mouseState[this.MouseButtons.left] = true;
this._touchStarted = false;
}
// reset mouse wheel
this._mouseWheel = 0;
}
/**
* Get keyboard key code from event.
* @private
*/
_getKeyboardKeyCode(event)
{
event = this._getEvent(event);
return event.keyCode !== undefined ? event.keyCode : event.key.charCodeAt(0);
}
/**
* Called when window loses focus - clear all input states to prevent keys getting stuck.
* @private
*/
_onBlur(event)
{
if (this.resetOnFocusLoss) {
this._resetAll();
}
}
/**
* Handle mouse wheel events.
* @private
* @param {*} event Event data from browser.
*/
_onMouseWheel(event)
{
this._mouseWheel = event.deltaY;
}
/**
* Handle keyboard down event.
* @private
* @param {*} event Event data from browser.
*/
_onKeyDown(event)
{
var keycode = this._getKeyboardKeyCode(event);
this._keyboardState[keycode] = true;
}
/**
* Handle keyboard up event.
* @private
* @param {*} event Event data from browser.
*/
_onKeyUp(event)
{
var keycode = this._getKeyboardKeyCode(event);
this._keyboardState[keycode || 0] = false;
}
/**
* Handle touch start event.
* @private
* @param {*} event Event data from browser.
*/
_onTouchStart(event)
{
// also update mouse position - this is important for touch events on mobile, where touch move only works while touching,
// so we want to update mouse position on the moment touch starts
var touches = event.changedTouches;
if (touches && touches.length)
{
var touch = touches[0];
var x = touch.pageX || touch.offsetX || touch.clientX;
var y = touch.pageY || touch.offsetY || touch.clientY;
if (x !== undefined && y !== undefined) {
this._mousePos.x = x;
this._mousePos.y = y;
this._normalizeMousePos()
}
}
// mark that touch started - will update state next frame
this._touchStarted = true;
}
/**
* Handle mouse down event.
* @private
* @param {*} event Event data from browser.
*/
_onMouseDown(event)
{
// update mouse down state
event = this._getEvent(event);
if (this.enableMouseDeltaWhileMouseWheelDown && (event.button === this.MouseButtons.middle))
{
event.preventDefault();
}
this._mouseState[event.button || 0] = true;
}
/**
* Handle mouse up event.
* @private
* @param {*} event Event data from browser.
*/
_onMouseUp(event)
{
event = this._getEvent(event);
this._mouseState[event.button || 0] = false;
}
/**
* Handle touch move event.
* @private
* @param {*} event Event data from browser.
*/
_onTouchMove(event)
{
event = this._getEvent(event);
this._mousePos.x = event.touches[0].pageX;
this._mousePos.y = event.touches[0].pageY;
this._normalizeMousePos();
}
/**
* Handle mouse move event.
* @private
* @param {*} event Event data from browser.
*/
_onMouseMove(event)
{
// get event in a cross-browser way
event = this._getEvent(event);
// try to get position from event with some fallbacks
var pageX = event.clientX;
if (pageX === undefined) { pageX = event.x; }
if (pageX === undefined) { pageX = event.offsetX; }
if (pageX === undefined) { pageX = event.pageX; }
var pageY = event.clientY;
if (pageY === undefined) { pageY = event.y; }
if (pageY === undefined) { pageY = event.offsetY; }
if (pageY === undefined) { pageY = event.pageY; }
// if pageX and pageY are not supported, use clientX and clientY instead
if (pageX === undefined) {
pageX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
pageY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
// set current mouse position
this._mousePos.x = pageX;
this._mousePos.y = pageY;
this._normalizeMousePos();
}
/**
* Normalize current _mousePos value to be relative to target element.
* @private
*/
_normalizeMousePos()
{
if (this._targetElement && this._targetElement.getBoundingClientRect) {
var rect = this._targetElement.getBoundingClientRect();
this._mousePos.x -= rect.left;
this._mousePos.y -= rect.top;
}
}
/**
* Get event either from event param or from window.event.
* This is for older browsers support.
* @private
*/
_getEvent(event)
{
return event || window.event;
}
} |
JavaScript | class Logger
{
constructor(name)
{
this._nameHeader = '[' + _application + '][' + name + ']';
this._throwErrors = false;
}
/**
* Write a trace level log message.
* @param {String} msg Message to write.
*/
trace(msg)
{
_drivers.trace(this._nameHeader, msg);
}
/**
* Write a debug level log message.
* @param {String} msg Message to write.
*/
debug(msg)
{
_drivers.debug(this._nameHeader, msg);
}
/**
* Write an info level log message.
* @param {String} msg Message to write.
*/
info(msg)
{
_drivers.info(this._nameHeader, msg);
}
/**
* Write a warning level log message.
* @param {String} msg Message to write.
*/
warn(msg)
{
_drivers.warn(this._nameHeader, msg);
if (this._throwErrors) {
throw new Error(msg);
}
}
/**
* Write an error level log message.
* @param {String} msg Message to write.
*/
error(msg)
{
_drivers.error(this._nameHeader, msg);
if (this._throwErrors) {
throw new Error(msg);
}
}
/**
* Set logger to throw an error every time a log message with severity higher than warning is written.
* @param {Boolean} enable Set to true to throw error on warnings.
*/
throwErrorOnWarnings(enable)
{
this._throwErrors = Boolean(enable);
}
} |
JavaScript | class NullDrivers
{
/**
* @private
*/
constructor()
{
}
trace(msg)
{
}
debug(msg)
{
}
info(msg)
{
}
warn(msg)
{
}
error(msg)
{
}
} |
JavaScript | class IManager
{
/**
* Initialize the manager.
* @returns {Promise} Promise to resolve when initialization is done.
*/
setup()
{
throw new Error("Not Implemented!");
}
/**
* Called every update at the begining of the frame.
*/
startFrame()
{
throw new Error("Not Implemented!");
}
/**
* Called every update at the end of the frame.
*/
endFrame()
{
throw new Error("Not Implemented!");
}
/**
* Destroy the manager.
*/
destroy()
{
throw new Error("Not Implemented!");
}
} |
JavaScript | class Sfx extends IManager
{
/**
* Create the manager.
*/
constructor()
{
super();
this._playingSounds = null;
}
/**
* @inheritdoc
* @private
**/
setup()
{
return new Promise((resolve, reject) => {
_logger.info("Setup sfx manager..");
this._playingSounds = new Set();
resolve();
});
}
/**
* @inheritdoc
* @private
**/
startFrame()
{
var playingSounds = Array.from(this._playingSounds);
for (var i = 0; i < playingSounds.length; ++i) {
var sound = playingSounds[i];
if (!sound.isPlaying) {
this._playingSounds.delete(sound);
}
}
}
/**
* @inheritdoc
* @private
**/
endFrame()
{
var playingSounds = Array.from(this._playingSounds);
for (var i = 0; i < playingSounds.length; ++i) {
var sound = playingSounds[i];
if (!sound.isPlaying) {
this._playingSounds.delete(sound);
}
}
}
/**
* @inheritdoc
* @private
**/
destroy()
{
this.stopAll();
this._playingSounds = new Set();
}
/**
* Get the SoundMixer class.
* @see SoundMixer
*/
get SoundMixer()
{
return SoundMixer;
}
/**
* Play a sound once without any special properties and without returning a sound instance.
* Its a more convinient method to play sounds, but less efficient than 'createSound()' if you want to play multiple times.
* @example
* let sound = await Shaku.assets.loadSound("assets/my_sound.ogg");
* Shaku.sfx.play(sound, 0.75);
* @param {SoundAsset} sound Sound asset to play.
* @param {Number} volume Volume to play sound (default to max).
* @param {Number} playbackRate Optional playback rate factor.
* @param {Boolean} preservesPitch Optional preserve pitch when changing rate factor.
*/
play(sound, volume, playbackRate, preservesPitch)
{
var sound = this.createSound(sound);
sound.volume = volume !== undefined ? volume : 1;
if (playbackRate !== undefined) { sound.playbackRate = playbackRate; }
if (preservesPitch !== undefined) { sound.preservesPitch = preservesPitch; }
sound.play();
}
/**
* Stop all playing sounds.
* @example
* Shaku.sfx.stopAll();
*/
stopAll()
{
var playingSounds = Array.from(this._playingSounds);
for (var i = 0; i < playingSounds.length; ++i) {
var sound = playingSounds[i];
sound.stop();
}
this._playingSounds = new Set();
}
/**
* Get currently playing sounds count.
* @returns {Number} Number of sounds currently playing.
*/
get playingSoundsCount()
{
return this._playingSounds.size;
}
/**
* Create and return a sound instance you can use to play multiple times.
* @example
* let sound = await Shaku.assets.loadSound("assets/my_sound.ogg");
* let soundInstance = Shaku.sfx.createSound(sound);
* soundInstance.play();
* @param {SoundAsset} sound Sound asset to play.
* @returns {SoundInstance} Newly created sound instance.
*/
createSound(sound)
{
if (!(sound instanceof SoundAsset)) { throw new Error("Sound type must be an instance of SoundAsset!"); }
var ret = new SoundInstance(this, sound.url);
return ret;
}
/**
* Get master volume.
* This affect all sound effects volumes.
* @returns {Number} Current master volume value.
*/
get masterVolume()
{
return SoundInstance._masterVolume;
}
/**
* Set master volume.
* This affect all sound effects volumes.
* @param {Number} value Master volume to set.
*/
set masterVolume(value)
{
SoundInstance._masterVolume = value;
return value;
}
} |
JavaScript | class SoundInstance
{
/**
* Create a sound instance.
* @param {Sfx} sfxManager Sfx manager instance.
* @param {String} url Sound URL or source.
*/
constructor(sfxManager, url)
{
if (!url) {
_logger.error("Sound type can't be null or invalid!");
throw new Error("Invalid sound type to play in SoundInstance!");
}
this._sfx = sfxManager;
this._audio = new Audio(url);
this._volume = 1;
}
/**
* Play sound.
*/
play()
{
if (this.playing) { return; }
this._audio.play();
this._sfx._playingSounds.add(this);
}
/**
* Get sound effect playback rate.
* @returns {Number} Playback rate.
*/
get playbackRate()
{
return this._audio.playbackRate;
}
/**
* Set playback rate.
* @param {Number} val Playback value to set.
*/
set playbackRate(val)
{
if (val < 0.1) { _logger.error("playbackRate value set is too low, value was capped to 0.1."); }
if (val > 10) { _logger.error("playbackRate value set is too high, value was capped to 10."); }
this._audio.playbackRate = val;
}
/**
* Get if to preserve pitch while changing playback rate.
* @returns {Boolean} Preserve pitch state of the sound instance.
*/
get preservesPitch()
{
return Boolean(this._audio.preservesPitch || this._audio.mozPreservesPitch);
}
/**
* Set if to preserve pitch while changing playback rate.
* @param {Boolean} val New preserve pitch value to set.
*/
set preservesPitch(val)
{
return this._audio.preservesPitch = this._audio.mozPreservesPitch = Boolean(val);
}
/**
* Pause the sound.
*/
pause()
{
this._audio.pause();
}
/**
* Replay sound from start.
*/
replay()
{
this.stop();
this.play();
}
/**
* Stop the sound and go back to start.
*/
stop()
{
this.pause();
this.currentTime = 0;
}
/**
* Get if playing in loop.
* @returns {Boolean} If this sound should play in loop.
*/
get loop()
{
return this._audio.loop;
}
/**
* Set if playing in loop.
* @param {Boolean} value If this sound should play in loop.
*/
set loop(value)
{
this._audio.loop = value;
return this._audio.loop;
}
/**
* Get volume.
* @returns {Number} Sound effect volume.
*/
get volume()
{
return this._volume;
}
/**
* Set volume.
* @param {Number} value Sound effect volume to set.
*/
set volume(value)
{
this._volume = value;
var volume = (value * SoundInstance._masterVolume);
if (volume < 0) { volume = 0; }
if (volume > 1) { volume = 1; }
this._audio.volume = volume;
return this._volume;
}
/**
* Get current time in track.
* @returns {Number} Current time in playing sound.
*/
get currentTime()
{
return this._audio.currentTime;
}
/**
* Set current time in track.
* @param {Number} value Set current playing time in sound track.
*/
set currentTime(value)
{
return this._audio.currentTime = value;
}
/**
* Get track duration.
* @returns {Number} Sound duration in seconds.
*/
get duration()
{
return this._audio.duration;
}
/**
* Get if sound is currently paused.
* @returns {Boolean} True if sound is currently paused.
*/
get paused()
{
return this._audio.paused;
}
/**
* Get if sound is currently playing.
* @returns {Boolean} True if sound is currently playing.
*/
get playing()
{
return !this.paused && !this.finished;
}
/**
* Get if finished playing.
* @returns {Boolean} True if sound reached the end and didn't loop.
*/
get finished()
{
return this._audio.ended;
}
} |
JavaScript | class SoundMixer
{
/**
* Create the sound mixer.
* @param {SoundInstance} sound1 Sound to mix from. Can be null to just fade in.
* @param {SoundInstance} sound2 Sound to mix to. Can be null to just fade out.
* @param {Boolean} allowOverlapping If true (default), will mix while overlapping sounds.
* If false, will first finish first sound before begining next.
*/
constructor(sound1, sound2, allowOverlapping)
{
this._sound1 = sound1;
this._sound2 = sound2;
this.fromSoundVolume = this._sound1 ? this._sound1.volume : 0;
this.toSoundVolume = this._sound2 ? this._sound2.volume : 0;
this.allowOverlapping = allowOverlapping;
this.update(0);
}
/**
* Stop both sounds.
*/
stop()
{
if (this._sound1) { this._sound1.stop(); }
if (this._sound2) { this._sound2.stop(); }
}
/**
* Get first sound.
* @returns {SoundInstance} First sound instance.
*/
get fromSound()
{
return this._sound1;
}
/**
* Get second sound.
* @returns {SoundInstance} Second sound instance.
*/
get toSound()
{
return this._sound2;
}
/**
* Return current progress.
* @returns {Number} Mix progress from 0 to 1.
*/
get progress()
{
return this._progress;
}
/**
* Update the mixer progress with time delta instead of absolute value.
* @param {Number} delta Progress delta, in seconds.
*/
updateDelta(delta)
{
this.update(this._progress + delta);
}
/**
* Update the mixer progress.
* @param {Number} progress Transition progress from sound1 to sound2. Values must be between 0.0 to 1.0.
*/
update(progress)
{
// special case - start
if (progress <= 0) {
if (this._sound1) {
this._sound1.volume = this.fromSoundVolume;
}
if (this._sound2) {
this._sound2.volume = 0;
this._sound2.stop();
}
this._progress = 0;
}
// special case - finish
if (progress >= 1) {
if (this._sound2) {
this._sound2.volume = this.toSoundVolume;
}
if (this._sound1) {
this._sound1.volume = 0;
this._sound1.stop();
}
this._progress = 1;
}
// transition
else
{
this._progress = progress;
if (this._sound1) { this._sound1.play(); }
if (this._sound2) { this._sound2.play(); }
if (this.allowOverlapping) {
if (this._sound1) { this._sound1.volume = this.fromSoundVolume * (1 - progress); }
if (this._sound2) { this._sound2.volume = this.toSoundVolume * progress; }
}
else {
progress *= 2;
if (this._sound1) { this._sound1.volume = Math.max(this.fromSoundVolume * (1 - progress), 0); }
if (this._sound2) { this._sound2.volume = Math.max(this.toSoundVolume * (progress - 1), 0); }
}
}
}
} |
JavaScript | class Shaku
{
/**
* Create the Shaku main object.
*/
constructor()
{
/**
* Different utilities and framework objects, like vectors, rectangles, colors, etc.
*/
this.utils = utils;
/**
* Sound effects and music manager.
*/
this.sfx = sfx;
/**
* Graphics manager.
*/
this.gfx = gfx;
/**
* Input manager.
*/
this.input = input;
/**
* Assets manager.
*/
this.assets = assets;
/**
* Collision detection manager.
*/
this.collision = collision;
/**
* If true, will pause the updates and drawing calls when window is not focused.
* Will also not update elapsed time.
*/
this.pauseWhenNotFocused = false;
/**
* Set to true to completely pause Shaku (will skip updates, drawing, and time counting).
*/
this.paused = false;
/**
* Set to true to pause just the game time.
* This will not pause real-life time. If you need real-life time stop please use the Python package.
*/
this.pauseTime = false;
// are managers currently in 'started' mode?
this._managersStarted = false;
// were we previously paused?
this._wasPaused = false;
}
/**
* Method to select managers to use + initialize them.
* @param {Array<IManager>} managers Array with list of managers to use or null to use all.
* @returns {Promise} promise to resolve when finish initialization.
*/
async init(managers)
{
return new Promise(async (resolve, reject) => {
// sanity & log
if (_usedManagers) { throw new Error("Already initialized!"); }
_logger.info(`Initialize Shaku v${version}.`);
// reset game start time
GameTime.reset();
// setup used managers
_usedManagers = managers || (isBrowser ? [assets, sfx, gfx, input, collision] : [assets, collision]);
// init all managers
for (let i = 0; i < _usedManagers.length; ++i) {
await _usedManagers[i].setup();
}
// set starting time
_prevUpdateTime = new GameTime();
// done!
resolve();
});
}
/**
* Destroy all managers
*/
destroy()
{
// sanity
if (!_usedManagers) { throw new Error("Not initialized!"); }
// destroy all managers
for (let i = 0; i < _usedManagers.length; ++i) {
_usedManagers[i].destroy();
}
}
/**
* Get if the Shaku is currently paused.
*/
get isPaused()
{
return this.paused || (this.pauseWhenNotFocused && !document.hasFocus());
}
/**
* Start frame (update all managers).
*/
startFrame()
{
// if paused, skip
if (this.isPaused) {
this._wasPaused = true;
return;
}
// returning from pause
if (this._wasPaused) {
this._wasPaused = false;
GameTime.resetDelta();
}
// update times
if (this.pauseTime) {
GameTime.resetDelta();
}
else {
GameTime.update();
}
// get frame start time
_startFrameTime = GameTime.rawTimestamp();
// create new gameTime object
this._gameTime = new GameTime();
// update animators
utils.Animator.updateAutos(this._gameTime.delta);
// update managers
for (let i = 0; i < _usedManagers.length; ++i) {
_usedManagers[i].startFrame();
}
this._managersStarted = true;
}
/**
* End frame (update all managers).
*/
endFrame()
{
// update managers
if (this._managersStarted) {
for (let i = 0; i < _usedManagers.length; ++i) {
_usedManagers[i].endFrame();
}
this._managersStarted = false;
}
// if paused, skip
if (this.isPaused) { return; }
// store previous gameTime object
_prevUpdateTime = this._gameTime;
// count fps
_currFpsCounter++;
_countSecond += this._gameTime.delta;
// a second passed:
if (_countSecond >= 1) {
// reset second count and set current fps value
_countSecond = 0;
_currFps = _currFpsCounter;
_currFpsCounter = 0;
// trim the frames avg time, so we won't drag peaks for too long
_totalFrameTimes = this.getAverageFrameTime();
_frameTimeMeasuresCount = 1;
}
// get frame end time and update average frames time
let _endFrameTime = GameTime.rawTimestamp();
_frameTimeMeasuresCount++;
_totalFrameTimes += (_endFrameTime - _startFrameTime);
}
/**
* Make Shaku run in silent mode, without logs.
* You can call this before init.
*/
silent()
{
logger.silent();
}
/**
* Set logger to throw an error every time a log message with severity higher than warning is written.
* You can call this before init.
* @param {Boolean} enable Set to true to throw error on warnings.
*/
throwErrorOnWarnings(enable)
{
if (enable === undefined) { throw Error("Must provide a value!"); }
logger.throwErrorOnWarnings(enable);
}
/**
* Get current frame game time.
* Only valid between startFrame() and endFrame().
* @returns {GameTime} Current frame's gametime.
*/
get gameTime()
{
return this._gameTime;
}
/**
* Get Shaku's version.
* @returns {String} Shaku's version.
*/
get version() { return version; }
/**
* Return current FPS count.
* Note: will return 0 until at least one second have passed.
* @returns {Number} FPS count.
*/
getFpsCount()
{
return _currFps;
}
/**
* Get how long on average it takes to complete a game frame.
* @returns {Number} Average time, in milliseconds, it takes to complete a game frame.
*/
getAverageFrameTime()
{
if (_frameTimeMeasuresCount === 0) { return 0; }
return _totalFrameTimes / _frameTimeMeasuresCount;
}
/**
* Request animation frame with fallbacks.
* @param {Function} callback Method to invoke in next animation frame.
* @returns {Number} Handle for cancellation.
*/
requestAnimationFrame(callback)
{
if (window.requestAnimationFrame) return window.requestAnimationFrame(callback);
else if (window.mozRequestAnimationFrame) return window.mozRequestAnimationFrame(callback);
else if (window.webkitRequestAnimationFrame) return window.webkitRequestAnimationFrame(callback);
else if (window.msRequestAnimationFrame) return window.msRequestAnimationFrame(callback);
else return setTimeout(callback, 1000/60);
}
/**
* Cancel animation frame with fallbacks.
* @param {Number} id Request handle.
*/
cancelAnimationFrame(id) {
if (window.cancelAnimationFrame) return window.cancelAnimationFrame(id);
else if (window.mozCancelAnimationFrame) return window.mozCancelAnimationFrame(id);
else clearTimeout(id);
}
/**
* Set the logger writer class (will replace the default console output).
* @param {*} loggerHandler New logger handler (must implement trace, debug, info, warn, error methods).
*/
setLogger(loggerHandler)
{
logger.setDrivers(loggerHandler);
}
} |
JavaScript | class Animator
{
/**
* Create the animator.
* @param {*} target Any object you want to animate.
*/
constructor(target)
{
this._target = target;
this._fromValues = {};
this._toValues = {};
this._progress = 0;
this._onFinish = null;
this._smoothDamp = false;
this._repeats = false;
this._repeatsWithReverseAnimation = false;
this._isInAutoUpdate = false;
this._originalFrom = null;
this._originalTo = null;
this._originalRepeats = null;
/**
* Speed factor to multiply with delta every time this animator updates.
*/
this.speedFactor = 1;
}
/**
* Update this animator with a given delta time.
* @param {Number} delta Delta time to progress this animator by.
*/
update(delta)
{
// if already done, skip
if (this._progress >= 1) {
return;
}
// apply speed factor and update progress
delta *= this.speedFactor;
this._progress += delta;
// did finish?
if (this._progress >= 1) {
// make sure don't overflow
this._progress = 1;
// trigger finish method
if (this._onFinish) {
this._onFinish();
}
}
// update values
for (let key in this._toValues) {
// get key as parts and to-value
let keyParts = this._toValues[key].keyParts;
let toValue = this._toValues[key].value;
// get from value
let fromValue = this._fromValues[key];
// if from not set, get default
if (fromValue === undefined) {
this._fromValues[key] = fromValue = this._getValueFromTarget(keyParts);
if (fromValue === undefined) {
throw new Error(`Animator issue: missing origin value for key '${key}' and property not found in target object.`);
}
}
// get lerp factor
let a = (this._smoothDamp && this._progress < 1) ? (this._progress * (1 + 1 - this._progress)) : this._progress;
// calculate new value
let newValue = null;
if (typeof fromValue === 'number') {
newValue = lerp(fromValue, toValue, a);
}
else if (fromValue.constructor.lerp) {
newValue = fromValue.constructor.lerp(fromValue, toValue, a);
}
else {
throw new Error(`Animator issue: from-value for key '${key}' is not a number, and its class type don't implement a 'lerp()' method!`);
}
// set new value
this._setValueToTarget(keyParts, newValue);
}
// if repeating, reset progress
if (this._repeats && this._progress >= 1) {
if (typeof this._repeats === 'number') { this._repeats--; }
this._progress = 0;
if (this._repeatsWithReverseAnimation ) {
this.flipFromAndTo();
}
}
}
/**
* Get value from target object.
* @private
* @param {Array<String>} keyParts Key parts broken by dots.
*/
_getValueFromTarget(keyParts)
{
// easy case - get value when key parts is just one component
if (keyParts.length === 1) {
return this._target[keyParts[0]];
}
// get value for path with parts
function index(obj,i) {return obj[i]}
return keyParts.reduce(index, this._target);
}
/**
* Set value in target object.
* @private
* @param {Array<String>} keyParts Key parts broken by dots.
*/
_setValueToTarget(keyParts, value)
{
// easy case - set value when key parts is just one component
if (keyParts.length === 1) {
this._target[keyParts[0]] = value;
return;
}
// set value for path with parts
function index(obj,i) {return obj[i]}
let parent = keyParts.slice(0, keyParts.length - 1).reduce(index, this._target);
parent[keyParts[keyParts.length - 1]] = value;
}
/**
* Make sure a given value is legal for the animator.
* @private
*/
_validateValueType(value)
{
return (typeof value === 'number') || (value && value.constructor && value.constructor.lerp);
}
/**
* Set a method to run when animation ends.
* @param {Function} callback Callback to invoke when done.
* @returns {Animator} this.
*/
then(callback)
{
this._onFinish = callback;
return this;
}
/**
* Set smooth damp.
* If true, lerping will go slower as the animation reach its ending.
* @param {Boolean} enable set smooth damp mode.
* @returns {Animator} this.
*/
smoothDamp(enable)
{
this._smoothDamp = enable;
return this;
}
/**
* Set if the animator should repeat itself.
* @param {Boolean|Number} enable false to disable repeating, true for endless repeats, or a number for limited number of repeats.
* @param {Boolean} reverseAnimation if true, it will reverse animation to repeat it instead of just "jumping" back to starting state.
* @returns {Animator} this.
*/
repeats(enable, reverseAnimation)
{
this._originalRepeats = this._repeats = enable;
this._repeatsWithReverseAnimation = Boolean(reverseAnimation);
return this;
}
/**
* Set 'from' values.
* You don't have to provide 'from' values, when a value is not set the animator will just take whatever was set in target when first update is called.
* @param {*} values Values to set as 'from' values.
* Key = property name in target (can contain dots for nested), value = value to start animation from.
* @returns {Animator} this.
*/
from(values)
{
for (let key in values) {
if (!this._validateValueType(values[key])) {
throw new Error("Illegal value type to use with Animator! All values must be either numbers, or a class instance that has a static lerp() method.");
}
this._fromValues[key] = values[key];
}
this._originalFrom = null;
return this;
}
/**
* Set 'to' values, ie the result when animation ends.
* @param {*} values Values to set as 'to' values.
* Key = property name in target (can contain dots for nested), value = value to start animation from.
* @returns {Animator} this.
*/
to(values)
{
for (let key in values) {
if (!this._validateValueType(values[key])) {
throw new Error("Illegal value type to use with Animator! All values must be either numbers, or a class instance that has a static lerp() method.");
}
this._toValues[key] = {keyParts: key.split('.'), value: values[key]};
}
this._originalTo = null;
return this;
}
/**
* Flip between the 'from' and the 'to' states.
*/
flipFromAndTo()
{
let newFrom = {};
let newTo = {};
if (!this._originalFrom) { this._originalFrom = this._fromValues; }
if (!this._originalTo) { this._originalTo = this._toValues; }
for (let key in this._toValues) {
newFrom[key] = this._toValues[key].value;
newTo[key] = {keyParts: key.split('.'), value: this._fromValues[key]};
}
this._fromValues = newFrom;
this._toValues = newTo;
}
/**
* Make this Animator update automatically with the gameTime delta time.
* Note: this will change the speedFactor property.
* @param {Number} seconds Animator duration time in seconds.
* @returns {Animator} this.
*/
duration(seconds)
{
this.speedFactor = 1 / seconds;
return this;
}
/**
* Reset animator progress.
* @returns {Animator} this.
*/
reset()
{
if (this._originalFrom) { this._fromValues = this._originalFrom; }
if (this._originalTo) { this._toValues = this._originalTo; }
if (this._originalRepeats !== null) { this._repeats = this._originalRepeats; }
this._progress = 0;
return this;
}
/**
* Make this Animator update automatically with the gameTime delta time, until its done.
* @returns {Animator} this.
*/
play()
{
if (this._isInAutoUpdate) {
return;
}
_autoAnimators.push(this);
this._isInAutoUpdate = true;
return this;
}
/**
* Get if this animator finished.
* @returns {Boolean} True if animator finished.
*/
get ended()
{
return this._progress >= 1;
}
/**
* Update all auto animators.
* @private
* @param {Number} delta Delta time in seconds.
*/
static updateAutos(delta)
{
for (let i = _autoAnimators.length - 1; i >= 0; --i) {
_autoAnimators[i].update(delta);
if (_autoAnimators[i].ended) {
_autoAnimators[i]._isInAutoUpdate = false;
_autoAnimators.splice(i, 1);
}
}
}
} |
JavaScript | class Circle
{
/**
* Create the Circle.
* @param {Vector2} center Circle center position.
* @param {Number} radius Circle radius.
*/
constructor(center, radius)
{
this.center = center.clone();
this.radius = radius;
}
/**
* Return a clone of this circle.
* @returns {Circle} Cloned circle.
*/
clone()
{
return new Circle(this.center, this.radius);
}
/**
* Check if this circle contains a Vector2.
* @param {Vector2} p Point to check.
* @returns {Boolean} if point is contained within the circle.
*/
containsVector(p)
{
return this.center.distanceTo(p) <= this.radius;
}
/**
* Check if equal to another circle.
* @param {Circle} other Other circle to compare to.
* @returns {Boolean} True if circles are equal, false otherwise.
*/
equals(other)
{
return (other === this) ||
(other && (other.constructor === this.constructor) && this.center.equals(other.center) && this.radius == other.radius);
}
/**
* Lerp between two circle.
* @param {Circle} p1 First circle.
* @param {Circle} p2 Second circle.
* @param {Number} a Lerp factor (0.0 - 1.0).
* @returns {Circle} result circle.
*/
static lerp(p1, p2, a)
{
let lerpScalar = MathHelper.lerp;
return new Circle(Vector2.lerp(p1.center, p2.center, a), lerpScalar(p1.radius, p2.radius, a));
}
} |
JavaScript | class Color
{
/**
* Create the color.
* @param {Number} r Color red component (value range: 0-1).
* @param {Number} g Color green component (value range: 0-1).
* @param {Number} b Color blue component (value range: 0-1).
* @param {Number} a Color alpha component (value range: 0-1).
*/
constructor(r, g, b, a)
{
this.set(r, g, b, a);
}
/**
* Set the color components.
* @param {Number} r Color red component (value range: 0-1).
* @param {Number} g Color green component (value range: 0-1).
* @param {Number} b Color blue component (value range: 0-1).
* @param {Number} a Color alpha component (value range: 0-1).
* @returns {Color} this.
*/
set(r, g, b, a)
{
this._r = r;
this._g = g;
this._b = b;
this._a = (a === undefined) ? 1 : a;
this._asHex = null;
return this;
}
/**
* Set the color components from byte values (0-255).
* @param {Number} r Color red component (value range: 0-255).
* @param {Number} g Color green component (value range: 0-255).
* @param {Number} b Color blue component (value range: 0-255).
* @param {Number} a Color alpha component (value range: 0-255).
* @returns {Color} this.
*/
setByte(r, g, b, a)
{
this._r = r / 255.0;
this._g = g / 255.0;
this._b = b / 255.0;
this._a = (a === undefined) ? 1 : (a / 255.0);
this._asHex = null;
return this;
}
/**
* Copy all component values from another color.
* @param {Color} other Color to copy values from.
* @returns {Color} this.
*/
copy(other)
{
this.set(other.r, other.g, other.b, other.a);
return this;
}
/**
* Get r component.
* @returns {Number} Red component.
*/
get r()
{
return this._r;
}
/**
* Get g component.
* @returns {Number} Green component.
*/
get g()
{
return this._g;
}
/**
* Get b component.
* @returns {Number} Blue component.
*/
get b()
{
return this._b;
}
/**
* Get a component.
* @returns {Number} Alpha component.
*/
get a()
{
return this._a;
}
/**
* Set r component.
* @returns {Number} Red component after change.
*/
set r(val)
{
this._r = val;
this._asHex = null;
return this._r;
}
/**
* Set g component.
* @returns {Number} Green component after change.
*/
set g(val)
{
this._g = val;
this._asHex = null;
return this._g;
}
/**
* Set b component.
* @returns {Number} Blue component after change.
*/
set b(val)
{
this._b = val;
this._asHex = null;
return this._b;
}
/**
* Set a component.
* @returns {Number} Alpha component after change.
*/
set a(val)
{
this._a = val;
this._asHex = null;
return this._a;
}
/**
* Convert a single component to hex value.
* @param {Number} c Value to convert to hex.
* @returns {String} Component as hex value.
*/
static componentToHex(c)
{
var hex = Math.round(c).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
/**
* Convert this color to hex string (starting with '#').
* @returns {String} Color as hex.
*/
get asHex()
{
if (!this._asHex) {
this._asHex = "#" + Color.componentToHex(this.r * 255) + Color.componentToHex(this.g * 255) + Color.componentToHex(this.b * 255) + Color.componentToHex(this.a * 255);
}
return this._asHex;
}
/**
* Create color from hex value.
* @param {Number} val Number value (hex), as 0xrrggbbaa.
* @returns {Color} New color value.
*/
static fromHex(val)
{
if (typeof val !== 'string' && val[0] != '#') {
throw new PintarJS.Error("Invalid color format!");
}
var parsed = hexToColor(val);
if (!parsed) { throw new Error("Invalid hex value to parse!"); }
return new Color(parsed.r, parsed.g, parsed.b, 1);
}
/**
* Create color from decimal value.
* @param {Number} val Number value (int).
* @param {Number} includeAlpha If true, will include alpha value.
* @returns {Color} New color value.
*/
static fromDecimal(val, includeAlpha)
{
let ret = new Color(1, 1, 1, 1);
if (includeAlpha) { ret.a = (val & 0xff) / 255.0; val = val >> 8; }
ret.b = (val & 0xff) / 255.0; val = val >> 8;
ret.g = (val & 0xff) / 255.0; val = val >> 8;
ret.r = (val & 0xff) / 255.0;
}
/**
* Create color from a dictionary.
* @param {*} data Dictionary with {r,g,b,a}.
* @returns {Color} Newly created color.
*/
static fromDict(data)
{
return new Color(data.r, data.g, data.b, data.a || 1);
}
/**
* Convert to dictionary.
* @returns {*} Dictionary with {r,g,b,a}
*/
toDict()
{
return {r: this.r, g: this.g, b: this.b, a: this.a};
}
/**
* Convert this color to decimal number.
* @returns {Number} Color as decimal RGBA.
*/
get asDecimalRGBA()
{
return ((Math.round(this.r * 255) << (8 * 3)) | (Math.round(this.g * 255) << (8 * 2)) | (Math.round(this.b * 255) << (8 * 1)) | (Math.round(this.a * 255)))>>>0;
}
/**
* Convert this color to decimal number.
* @returns {Number} Color as decimal ARGB.
*/
get asDecimalABGR()
{
return ((Math.round(this.a * 255) << (8 * 3)) | (Math.round(this.b * 255) << (8 * 2)) | (Math.round(this.g * 255) << (8 * 1)) | (Math.round(this.r * 255)))>>>0;
}
/**
* Convert this color to a float array.
*/
get floatArray()
{
return [this.r, this.g, this.b, this.a];
}
/**
* Return a clone of this color.
* @returns {Number} Cloned color.
*/
clone()
{
return new Color(this.r, this.g, this.b, this.a);
}
/**
* Convert to string.
*/
string()
{
return this.r + ',' + this.g + ',' + this.b + ',' + this.a;
}
/**
* Get if this color is pure black (ignoring alpha).
*/
get isBlack()
{
return this.r == 0 && this.g == 0 && this.b == 0;
}
/**
* Return a random color.
* @param {Boolean} includeAlpha If true, will also randomize alpha.
* @returns {Color} Randomized color.
*/
static random(includeAlpha)
{
return new Color(Math.random(), Math.random(), Math.random(), includeAlpha ? Math.random() : 1);
}
/**
* Build and return new color from bytes array.
* @param {Array<Number>} bytes Bytes array to build color from.
* @returns {Color} Newly created color.
*/
static fromBytesArray(bytes)
{
return new Color(bytes[0] / 255, bytes[1] / 255, bytes[2] / 255, bytes[3] !== undefined ? (bytes[3] / 255) : 1);
}
/**
* Get if this color is transparent black.
*/
get isTransparentBlack()
{
return this._r == this._g && this._g == this._b && this._b == this._a && this._a == 0;
}
/**
* Get array with all built-in web color names.
* @returns {Array<String>} Array with color names.
*/
static get webColorNames()
{
return colorKeys;
}
/**
* Check if equal to another color.
* @param {PintarJS.Color} other Other color to compare to.
*/
equals(other)
{
return (this === other) ||
(other && (other.constructor === this.constructor) && this._r == other._r && this._g == other._g && this._b == other._b && this._a == other._a);
}
/**
* Lerp between two colors.
* @param {Color} p1 First color.
* @param {Color} p2 Second color.
* @param {Number} a Lerp factor (0.0 - 1.0).
* @returns {Color} result color.
*/
static lerp(p1, p2, a)
{
let lerpScalar = MathHelper.lerp;
return new Color( lerpScalar(p1.r, p2.r, a),
lerpScalar(p1.g, p2.g, a),
lerpScalar(p1.b, p2.b, a),
lerpScalar(p1.a, p2.a, a)
);
}
} |
JavaScript | class GameTime
{
/**
* create the gametime object with current time.
*/
constructor()
{
/**
* Current timestamp
*/
this.timestamp = _currElapsed;
/**
* Delta time struct.
* Contains: milliseconds, seconds.
*/
this.deltaTime = {
milliseconds: _currDelta,
seconds: _currDelta / 1000.0,
};
/**
* Elapsed time struct.
* Contains: milliseconds, seconds.
*/
this.elapsedTime = {
milliseconds: _currElapsed,
seconds: _currElapsed / 1000.0
};
/**
* Delta time, in seconds, since last frame.
*/
this.delta = this.deltaTime ? this.deltaTime.seconds : null;
/**
* Total time, in seconds, since Shaku was initialized.
*/
this.elapsed = this.elapsedTime.seconds;
// freeze object
Object.freeze(this);
}
/**
* Update game time.
*/
static update()
{
// get current time
let curr = getAccurateTimestampMs();
// calculate delta time
let delta = 0;
if (_prevTime) {
delta = curr - _prevTime;
}
// update previous time
_prevTime = curr;
// update delta and elapsed
_currDelta = delta;
_currElapsed += delta;
}
/**
* Get raw timestamp in milliseconds.
* @returns {Number} raw timestamp in milliseconds.
*/
static rawTimestamp()
{
return getAccurateTimestampMs();
}
/**
* Reset elapsed and delta time.
*/
static reset()
{
_prevTime = null;
_currDelta = 0;
_currElapsed = 0;
}
/**
* Reset current frame's delta time.
*/
static resetDelta()
{
_prevTime = null;
_currDelta = 0;
}
} |
JavaScript | class Line
{
/**
* Create the Line.
* @param {Vector2} from Line start position.
* @param {Vector2} to Line end position.
*/
constructor(from, to)
{
this.from = from.clone();
this.to = to.clone();
}
/**
* Return a clone of this line.
* @returns {Line} Cloned line.
*/
clone()
{
return new Line(this.from, this.to);
}
/**
* Check if this circle contains a Vector2.
* @param {Vector2} p Point to check.
* @param {Number} threshold Distance between point and line to consider as intersecting. Default is 0.5, meaning it will treat point and line as round integers (sort-of).
* @returns {Boolean} if point is contained within the circle.
*/
containsVector(p, threshold)
{
let A = this.from;
let B = this.to;
let distance = Vector2.distance;
if (threshold === undefined) { threshold = 0.5; }
return Math.abs((distance(A, p) + distance(B, p)) - distance(A, B)) <= threshold;
}
/**
* Check if this line collides with another line.
* @param {Line} other Other line to test collision with.
* @returns {Boolean} True if lines collide, false otherwise.
*/
collideLine(other)
{
let p0 = this.from;
let p1 = this.to;
let p2 = other.from;
let p3 = other.to;
if (p0.equals(p2) || p0.equals(p3) || p1.equals(p2) || p1.equals(p3)) {
return true;
}
let s1_x, s1_y, s2_x, s2_y;
s1_x = p1.x - p0.x;
s1_y = p1.y - p0.y;
s2_x = p3.x - p2.x;
s2_y = p3.y - p2.y;
let s, t;
s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
return (s >= 0 && s <= 1 && t >= 0 && t <= 1);
}
/**
* Get the shortest distance between this line segment and a vector.
* @param {Vector2} v Vector to get distance to.
* @returns {Number} Shortest distance between line and vector.
*/
distanceToVector(v)
{
let x1 = this.from.x;
let x2 = this.to.x;
let y1 = this.from.y;
let y2 = this.to.y;
var A = v.x - x1;
var B = v.y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = -1;
if (len_sq != 0) //in case of 0 length line
param = dot / len_sq;
var xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = v.x - xx;
var dy = v.y - yy;
return Math.sqrt(dx * dx + dy * dy);
}
/**
* Check if equal to another circle.
* @param {Circle} other Other circle to compare to.
* @returns {Boolean} True if circles are equal, false otherwise.
*/
equals(other)
{
return (this === other) ||
(other && (other.constructor === this.constructor) && this.from.equals(other.from) && this.to.equals(other.to));
}
/**
* Lerp between two lines.
* @param {Line} l1 First lines.
* @param {Line} l2 Second lines.
* @param {Number} a Lerp factor (0.0 - 1.0).
* @returns {Line} result lines.
*/
static lerp(l1, l2, a)
{
return new Line(Vector2.lerp(l1.from, l2.from, a), Vector2.lerp(l1.to, l2.to, a));
}
} |
JavaScript | class MathHelper
{
/**
* Perform linear interpolation between start and end values.
* @param {Number} start Starting value.
* @param {Number} end Ending value.
* @param {Number} amount How much to interpolate from start to end.
* @returns {Number} interpolated value between start and end.
*/
static lerp(start, end, amount)
{
// to prevent shaking on same values
if (start === end) { return end; }
// do lerping
return ((1-amount) * start) + (amount * end);
}
/**
* Calculate 2d dot product.
* @param {Number} x1 First vector x.
* @param {Number} y1 First vector y.
* @param {Number} x2 Second vector x.
* @param {Number} y2 Second vector y.
* @returns {Number} dot product result.
*/
static dot(x1, y1, x2, y2)
{
return x1 * x2 + y1 * y2;
}
/**
* Convert degrees to radians.
* @param {Number} degrees Degrees value to convert to radians.
* @returns {Number} Value as radians.
*/
static toRadians(degrees)
{
return degrees * _toRadsFactor;
}
/**
* Convert radians to degrees.
* @param {Number} radians Radians value to convert to degrees.
* @returns {Number} Value as degrees.
*/
static toDegrees(radians)
{
return radians * _toDegreesFactor;
}
/**
* Find shortest distance between two radians, with sign (ie distance can be negative).
* @param {Number} a1 First radian.
* @param {Number} a2 Second radian.
* @returns {Number} Shortest distance between radians.
*/
static radiansDistanceSigned(a1, a2)
{
var max = Math.PI * 2;
var da = (a2 - a1) % max;
return 2 * da % max - da;
}
/**
* Find shortest distance between two radians.
* @param {Number} a1 First radian.
* @param {Number} a2 Second radian.
* @returns {Number} Shortest distance between radians.
*/
static radiansDistance(a1, a2)
{
return Math.abs(this.radiansDistanceSigned(a1, a2));
}
/**
* Find shortest distance between two angles in degrees, with sign (ie distance can be negative).
* @param {Number} a1 First angle.
* @param {Number} a2 Second angle.
* @returns {Number} Shortest distance between angles.
*/
static degreesDistanceSigned(a1, a2)
{
let a1r = a1 * _toRadsFactor;
let a2r = a2 * _toRadsFactor;
let ret = this.radiansDistanceSigned(a1r, a2r);
return ret * _toDegreesFactor;
}
/**
* Find shortest distance between two angles in degrees.
* @param {Number} a1 First angle.
* @param {Number} a2 Second angle.
* @returns {Number} Shortest distance between angles.
*/
static degreesDistance(a1, a2)
{
let a1r = a1 * _toRadsFactor;
let a2r = a2 * _toRadsFactor;
let ret = this.radiansDistance(a1r, a2r);
return ret * _toDegreesFactor;
}
/**
* Perform linear interpolation between radian values.
* Unlike the regular lerp method, this method will take wrapping into consideration, and will always lerp via the shortest distance.
* @param {Number} a1 Starting value.
* @param {Number} a2 Ending value.
* @param {Number} alpha How much to interpolate from start to end.
* @returns {Number} interpolated radians between start and end.
*/
static lerpRadians(a1, a2, alpha)
{
// to prevent shaking on same values
if (a1 === a2) { return a2; }
// do lerping
return a1 + this.radiansDistanceSigned(a1, a2) * alpha;
}
/**
* Perform linear interpolation between degrees.
* Unlike the regular lerp method, this method will take wrapping into consideration, and will always lerp via the shortest distance.
* @param {Number} a1 Starting value.
* @param {Number} a2 Ending value.
* @param {Number} alpha How much to interpolate from start to end.
* @returns {Number} interpolated degrees between start and end.
*/
static lerpDegrees(a1, a2, alpha)
{
// to prevent shaking on same values
if (a1 === a2) { return a2; }
// convert to radians
a1 = this.toRadians(a1);
a2 = this.toRadians(a2);
// lerp
var ret = this.lerpRadians(a1, a2, alpha);
// convert back to degrees and return
return this.toDegrees(ret);
}
/**
* Round numbers from 10'th digit.
* This is useful for calculations that should return round or almost round numbers, but have a long tail of 0's and 1 due to floating points accuracy.
* @param {Number} num Number to round.
* @returns {Number} Rounded number.
*/
static round10(num)
{
return Math.round(num * 100000000.0) / 100000000.0;
}
/**
* Wrap degrees value to be between 0 to 360.
* @param {Number} degrees Degrees to wrap.
* @returns {Number} degrees wrapped to be 0-360 values.
*/
static wrapDegrees(degrees)
{
degrees = degrees % 360;
if (degrees < 0) { degrees += 360; }
return degrees;
}
} |
JavaScript | class IGrid
{
/**
* Check if a given tile is blocked from a given neihbor.
* @param {Vector2|Vector3} _from Source tile index.
* @param {Vector2|Vector3} _to Target tile index. Must be a neighbor of _from.
* @returns {Boolean} Can we travel from _from to _to?
*/
isBlocked(_from, _to) { throw new Error("Not Implemented"); }
/**
* Get the price to travel on a given tile.
* Should return 1 for "normal" traveling price, > 1 for expensive tile, and < 1 for a cheap tile to pass on.
* @param {Vector2|Vector3} _index Tile index.
* @returns {Number} Price factor to walk on.
*/
getPrice(_index) { throw new Error("Not Implemented"); }
} |
JavaScript | class Node
{
constructor(position)
{
this.position = position;
this.gCost = 0;
this.hCost = 0;
this.parent = null;
this.price = 1;
}
get fCost()
{
return this.gCost + this.hCost;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.