/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 7);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __assign; });
/* unused harmony export __rest */
/* unused harmony export __decorate */
/* unused harmony export __param */
/* unused harmony export __metadata */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return __generator; });
/* unused harmony export __createBinding */
/* unused harmony export __exportStar */
/* unused harmony export __values */
/* unused harmony export __read */
/* unused harmony export __spread */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return __spreadArrays; });
/* unused harmony export __await */
/* unused harmony export __asyncGenerator */
/* unused harmony export __asyncDelegator */
/* unused harmony export __asyncValues */
/* unused harmony export __makeTemplateObject */
/* unused harmony export __importStar */
/* unused harmony export __importDefault */
/* unused harmony export __classPrivateFieldGet */
/* unused harmony export __classPrivateFieldSet */
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

function __exportStar(m, o) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};

function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}

function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

function __classPrivateFieldGet(receiver, privateMap) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to get private field on non-instance");
    }
    return privateMap.get(receiver);
}

function __classPrivateFieldSet(receiver, privateMap, value) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to set private field on non-instance");
    }
    privateMap.set(receiver, value);
    return value;
}


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export isObject */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isCommonArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isTypedArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return removeFromArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return parametrizeString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return noop; });
var isObject = function (obj) {
    return obj === Object(obj);
};
var isString = function (s) {
    var _a;
    return ((_a = s) === null || _a === void 0 ? void 0 : _a.substr) !== undefined;
};
var isCommonArray = function (a) {
    return !!(a.splice);
};
var isTypedArray = function (a) {
    return !!(a.buffer);
};
var isArray = function (a) {
    return isCommonArray(a) || isTypedArray(a);
};
var isNumber = function (value) {
    return value.toFixed !== undefined;
};
var isEqualArray = function (a, b) {
    for (var i = 0, max = a.length; i < max; i++) {
        if (a[i] !== b[i])
            return false;
    }
    return true;
};
var isEqualObject = function (a, b) {
    throw new Error('not implemented');
};
var isEqual = function (a, b) {
    if (a === null || a === undefined)
        return false;
    if (isArray(a) && isArray(b))
        return isEqualArray(a, b);
    else if (isObject(a) && isObject(b))
        return isEqualObject(a, b);
    return a === b;
};
var removeFromArray = function (arr, predicate) {
    var i = arr.length;
    var cnt = 0;
    while (i--) {
        if (predicate(arr[i])) {
            arr.splice(i, 1);
            cnt++;
        }
    }
    return cnt;
};
var parametrizeString = function (source, args) {
    Object.keys(args).forEach(function (key) {
        source = source.split(key).join('' + args[key]);
    });
    return source;
};
var noop = function (arg) { };


/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = [
    "struct GradientPoint {",
    "    bool pointActive;",
    "    float value;",
    "    float r;",
    "    float g;",
    "    float b;",
    "    float a;",
    "};",
    "#define HALF                            .5",
    "#define ZERO                            .0",
    "#define ONE                             1.",
    "#define PI                              __PI__",
    "#define TWO_PI                          (__PI__*2.)",
    "#define ERROR_COLOR                     vec4(ONE,ZERO,ZERO,ONE)",
    "#define STRETCH_MODE_STRETCH            __STRETCH_MODE_STRETCH__",
    "#define STRETCH_MODE_REPEAT             __STRETCH_MODE_REPEAT__",
    "#define FILL_TYPE_COLOR                 __FILL_TYPE_COLOR__",
    "#define FILL_TYPE_TEXTURE               __FILL_TYPE_TEXTURE__",
    "#define FILL_TYPE_LINEAR_GRADIENT       __FILL_TYPE_LINEAR_GRADIENT__",
    "#define FILL_TYPE_RADIAL_GRADIENT       __FILL_TYPE_RADIAL_GRADIENT__",
    "#define SHAPE_TYPE_ELLIPSE              __SHAPE_TYPE_ELLIPSE__",
    "#define SHAPE_TYPE_RECT                 __SHAPE_TYPE_RECT__",
    "#define MAX_NUM_OF_GRADIENT_POINTS      __MAX_NUM_OF_GRADIENT_POINTS__"
].join('\n');

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = [
    "vec4 getStretchedImage(float tx,float ty){",
    "    vec2 txVec = vec2(tx,ty);",
    "    txVec += fract(u_texOffset);",
    "    txVec = mod(txVec,u_texRect.zw);",
    "    txVec += u_texRect.xy;",
    "    return texture2D(texture, txVec);",
    "}",
    "vec4 getRepeatedImage(float tx,float ty){",
    "    vec2 txVec = vec2(tx,ty)*u_repeatFactor;",
    "    txVec += fract(u_texOffset);",
    "    txVec = mod(txVec,u_texRect.zw);",
    "    txVec += u_texRect.xy;",
    "    return texture2D(texture, txVec);",
    "}",
    "vec4 mixTextureColorWithTint(vec4 textureCol, vec4 tint){",
    "    return mix(textureCol,tint,tint.a)*textureCol.a;",
    "}",
    "vec4 getInterpolatedGradientColor(float position) {",
    "    GradientPoint currentLeftPoint = u_fillGradientPoints[0];",
    "    GradientPoint currentRightPoint = u_fillGradientPoints[MAX_NUM_OF_GRADIENT_POINTS-1];",
    "    for (int i=0;i<MAX_NUM_OF_GRADIENT_POINTS;i++) {",
    "        GradientPoint currentPointFromLtoR = u_fillGradientPoints[i];",
    "        GradientPoint currentPointFromRtoL = u_fillGradientPoints[MAX_NUM_OF_GRADIENT_POINTS-1-i];",
    "        if (!currentLeftPoint.pointActive) currentLeftPoint = currentPointFromLtoR;",
    "        if (!currentRightPoint.pointActive) currentRightPoint = currentPointFromRtoL;",
    "        if (currentPointFromLtoR.pointActive && currentPointFromLtoR.value>currentLeftPoint.value && currentPointFromLtoR.value<position) {",
    "            currentLeftPoint = currentPointFromLtoR;",
    "        }",
    "        if (currentPointFromRtoL.pointActive && currentPointFromRtoL.value<currentRightPoint.value && currentPointFromRtoL.value>=position) {",
    "            currentRightPoint = currentPointFromRtoL;",
    "        }",
    "    }",
    "    return mix(",
    "        vec4(currentLeftPoint.r,currentLeftPoint.g,currentLeftPoint.b,currentLeftPoint.a),",
    "        vec4(currentRightPoint.r,currentRightPoint.g,currentRightPoint.b,currentRightPoint.a),",
    "        (position - currentLeftPoint.value)/(currentRightPoint.value - currentLeftPoint.value+0.00001)",
    "    ) * currentLeftPoint.a;",
    "}",
    "float calcRadiusAtPosition(vec2 pos,vec2 center,vec2 radius) {",
    "    float a = atan(pos.y-center.y,pos.x-center.x);",
    "    float cosA = cos(a);",
    "    float sinA = sin(a);",
    "    return radius.x*radius.y/sqrt(radius.x*radius.x*sinA*sinA+radius.y*radius.y*cosA*cosA);",
    "}",
    "vec4 getFillColor(){",
    "    if (u_fillType==FILL_TYPE_COLOR) return u_fillColor;",
    "    else if (u_fillType==FILL_TYPE_LINEAR_GRADIENT) {",
    "        float r = distance(vec2(HALF, HALF), v_position.xy);",
    "        float angle = atan(v_position.y - HALF,v_position.x - HALF);",
    "        angle+=u_fillGradientAngle;",
    "        float x = r*cos(angle);",
    "        float y = r*sin(angle);",
    "        return getInterpolatedGradientColor(x  + HALF);",
    "    }",
    "    else if (u_fillType==FILL_TYPE_RADIAL_GRADIENT) {",
    "        float r = distance(vec2(u_radialGradientCenterX, u_radialGradientCenterY), v_position.xy);",
    "        // interpolate r to [0..1] interval",
    "        float radiusTopLeft = distance(vec2(u_radialGradientCenterX, u_radialGradientCenterY), vec2(ZERO,ZERO));",
    "        float radiusBottomLeft = distance(vec2(u_radialGradientCenterX, u_radialGradientCenterY), vec2(ZERO,ONE));",
    "        float radiusTopRight = distance(vec2(u_radialGradientCenterX, u_radialGradientCenterY), vec2(ONE,ZERO));",
    "        float radiusBottomRight = distance(vec2(u_radialGradientCenterX, u_radialGradientCenterY), vec2(ONE,ONE));",
    "        float maxRadius = radiusTopLeft;",
    "        if (radiusBottomLeft>maxRadius) maxRadius = radiusBottomLeft;",
    "        if (radiusTopRight>maxRadius) maxRadius = radiusTopRight;",
    "        if (radiusBottomRight>maxRadius) maxRadius = radiusBottomRight;",
    "        return getInterpolatedGradientColor(r/maxRadius);",
    "    }",
    "    else if (u_fillType==FILL_TYPE_TEXTURE) {",
    "        float tx = (v_position.x-u_rectOffsetLeft)/u_width*u_texRect[2];",
    "        float ty = (v_position.y-u_rectOffsetTop)/u_height*u_texRect[3];",
    "        vec4 txVec;",
    "        if (u_stretchMode==STRETCH_MODE_STRETCH) txVec = mixTextureColorWithTint(getStretchedImage(tx,ty),u_color);",
    "        else if (u_stretchMode==STRETCH_MODE_REPEAT) txVec = mixTextureColorWithTint(getRepeatedImage(tx,ty),u_color);",
    "        else txVec = ERROR_COLOR;",
    "        return txVec;",
    "    }",
    "    else return ERROR_COLOR;",
    "}",
    "void _drawElliplse(float dist,float rAtCurrAngle){",
    "    if (dist < rAtCurrAngle) {",
    "        if (dist > rAtCurrAngle - u_lineWidth) gl_FragColor = u_color;",
    "        else gl_FragColor = getFillColor();",
    "    } else discard;",
    "}",
    "void drawEllipse(){",
    "    float dist = distance(vec2(HALF, HALF), v_position.xy);",
    "    float rAtCurrAngle = calcRadiusAtPosition(v_position.xy, vec2(HALF,HALF),vec2(u_rx, u_ry));",
    "    bool isArcNotUsed = u_arcAngleFrom==u_arcAngleTo;",
    "    if (dist > rAtCurrAngle) discard;",
    "    if (isArcNotUsed) {",
    "        _drawElliplse(dist,rAtCurrAngle);",
    "    } else {",
    "        float angle = atan(v_position.y-HALF, v_position.x-HALF);",
    "        float angleFrom = u_arcAngleFrom;",
    "        float angleTo =  u_arcAngleTo;",
    "        if (angleFrom<ZERO) angleFrom = TWO_PI + angleFrom;",
    "        if (angleTo<ZERO) angleTo = TWO_PI + angleTo;",
    "        if (angle<ZERO) angle = TWO_PI + angle;",
    "        bool anticlockwise = u_anticlockwise;",
    "        if (angleFrom>angleTo) {",
    "            anticlockwise=!anticlockwise;",
    "            float tmp = angleFrom;",
    "            angleFrom = angleTo;",
    "            angleTo = tmp;",
    "        }",
    "        bool withinArc = (angleFrom<=angle) && (angle<=angleTo);",
    "        if (withinArc) {",
    "            if (anticlockwise) discard;",
    "            else _drawElliplse(dist,rAtCurrAngle);",
    "        }",
    "        else {",
    "            if (!anticlockwise) discard;",
    "            else _drawElliplse(dist,rAtCurrAngle);",
    "        }",
    "    }",
    "}",
    "void drawRect(){",
    "    float x = v_position.x - HALF;",
    "    float y = v_position.y - HALF;",
    "    float distX = abs(x);",
    "    float distY = abs(y);",
    "    float halfW = u_width  * HALF;",
    "    float halfH = u_height * HALF;",
    "    if (distX < halfW && distY < halfH) {",
    "        if (distX>halfW - u_borderRadius && distY>halfH - u_borderRadius) {",
    "            vec2 borderCenter = vec2(ZERO,ZERO);",
    "            float posX = v_position.x, posY = v_position.y;",
    "            if (posX<HALF && posY<HALF) { // top left",
    "                borderCenter = vec2(HALF - halfW + u_borderRadius,HALF - halfH + u_borderRadius);",
    "            }",
    "            else if (posX>HALF && posY<HALF) { // top right",
    "                borderCenter = vec2(HALF + halfW - u_borderRadius,HALF - halfH + u_borderRadius);",
    "            }",
    "            else if (posX<HALF && posY>HALF) { // bottom left",
    "                borderCenter = vec2(HALF - halfW + u_borderRadius,HALF + halfH - u_borderRadius);",
    "            }",
    "            else {  // bottom right",
    "                borderCenter = vec2(HALF + halfW - u_borderRadius,HALF + halfH - u_borderRadius);",
    "            }",
    "            float distToBorderCenter = distance(v_position.xy,borderCenter);",
    "            if (distToBorderCenter>u_borderRadius) discard;",
    "            else if (distToBorderCenter>u_borderRadius-u_lineWidth) gl_FragColor = u_color;",
    "            else gl_FragColor = getFillColor();",
    "        }",
    "        else if (distX > halfW - u_lineWidth || distY > halfH - u_lineWidth) gl_FragColor = u_color;",
    "        else gl_FragColor = getFillColor();",
    "    }",
    "    else discard;",
    "}",
    "void main(){",
    "    if (u_shapeType==SHAPE_TYPE_ELLIPSE) drawEllipse();",
    "    else if (u_shapeType==SHAPE_TYPE_RECT) drawRect();",
    "    else gl_FragColor = ERROR_COLOR;",
    "    gl_FragColor*=u_alpha;",
    "}"
].join('\n');

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = [
    "precision mediump float;",
    "attribute vec4 a_position;",
    "attribute vec2 a_texCoord;",
    "attribute vec3 a_normal;",
    "uniform mat4 u_modelMatrix;",
    "uniform mat4 u_inverseTransposeModelMatrix;",
    "uniform mat4 u_projectionMatrix;",
    "uniform mat4 u_textureMatrix;",
    "uniform sampler2D u_heightMapTexture;",
    "uniform bool  u_heightMapTextureUsed;",
    "uniform float u_heightMapFactor;",
    "varying vec2 v_texCoord;",
    "varying vec3 v_normal;",
    "varying vec4 v_position;",
    "varying vec3 v_surfaceToLight;",
    "varying vec3 v_surfaceToView;",
    "void main() {",
    "    vec4 position = a_position;",
    "    v_texCoord = (u_textureMatrix * vec4(a_texCoord,1.,1.)).xy;",
    "    v_normal = mat3(u_inverseTransposeModelMatrix) * a_normal;",
    "    if (u_heightMapTextureUsed) {",
    "        vec4 bumpData = texture2D(u_heightMapTexture, v_texCoord);",
    "        position = position + vec4(a_normal,0) * bumpData.r * u_heightMapFactor;",
    "    }",
    "    v_position = u_projectionMatrix * u_modelMatrix * position;",
    "    // compute the vector of the surface to the light",
    "    // and pass it to the fragment shader",
    "    v_surfaceToLight = vec3(600,200,1000) - vec3(u_modelMatrix * position);",
    "    // compute the vector of the surface to the view/camera",
    "    // and pass it to the fragment shader",
    "    v_surfaceToView = normalize(vec3(500,300,1000) - vec3(u_modelMatrix * position));",
    "    gl_Position = v_position;",
    "}"
].join('\n');

/***/ }),
/* 5 */
/***/ (function(module, exports) {

module.exports = [
    "precision mediump float;",
    "varying vec2 v_texCoord;",
    "varying vec3 v_normal;",
    "varying vec4 v_position;",
    "varying vec3 v_surfaceToLight;",
    "varying vec3 v_surfaceToView;",
    "uniform sampler2D u_texture;",
    "uniform sampler2D u_normalsTexture;",
    "uniform samplerCube u_cubeMapTexture;",
    "uniform bool  u_textureUsed;",
    "uniform bool  u_normalsTextureUsed;",
    "uniform bool  u_cubeMapTextureUsed;",
    "uniform float u_alpha;",
    "uniform float u_reflectivity;",
    "uniform bool  u_lightUsed;",
    "uniform vec4  u_color;",
    "uniform float u_color_mix;",
    "uniform mat4  u_modelMatrix;",
    "void main() {",
    "    if (u_textureUsed) gl_FragColor = mix(texture2D(u_texture, v_texCoord),u_color,u_color_mix);",
    "    else gl_FragColor = u_color;",
    "    if (u_lightUsed) {",
    "        vec3 normal = normalize(v_normal);",
    "        vec3 surfaceToLightDirection = normalize(v_surfaceToLight);",
    "        vec3 surfaceToViewDirection = normalize(v_surfaceToView);",
    "        vec3 halfVector = normalize(surfaceToLightDirection + surfaceToViewDirection);",
    "        if (u_normalsTextureUsed) {",
    "            vec4 bumpNormal = texture2D(u_normalsTexture, v_texCoord) * 2. - 1.;",
    "            normal+= bumpNormal.rgb;",
    "            normal = normalize(normal);",
    "        }",
    "        vec3 directionLightPos = vec3(0,0,-100);",
    "        vec3 lightDirection = normalize(directionLightPos);",
    "        float light = max(0.,dot(normal, lightDirection));",
    "        light += max(0.,dot(normal, surfaceToLightDirection));",
    "        float specular = pow(max(dot(normal, halfVector), 0.0), 2.);",
    "        light = clamp(light,.5,1.0);",
    "        //gl_FragColor = vec4(normalize(v_normal)*0.5+0.5,1.0); // to debug normals",
    "        gl_FragColor.rgb *= light;",
    "        gl_FragColor.rgb+=specular;",
    "    }",
    "    if (u_cubeMapTextureUsed) {",
    "        vec3 I = normalize(vec3(v_position));",
    "        vec3 R = reflect(I, normalize(v_normal));",
    "        vec4 reflectionColor = textureCube(u_cubeMapTexture, R);",
    "        gl_FragColor = mix(gl_FragColor,reflectionColor,u_reflectivity);",
    "    }",
    "    gl_FragColor*=u_alpha;",
    "}"
].join('\n');

/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {


        var document = __webpack_require__(9).Document;
        module.exports = document.create({"children":[{"tagName":"info","attributes":{"face":"\"Consolas\"","size":"15","bold":"0","italic":"0","charset":"\"\"","unicode":"0","stretchH":"100","smooth":"1","aa":"1","padding":"1,1,1,1","spacing":"2,2"}},{"tagName":"common","attributes":{"lineHeight":"23","base":"13","scaleW":"512","scaleH":"512","pages":"1","packed":"0"}},{"tagName":"page","attributes":{"id":"0","file":"\"font32.png\""}},{"tagName":"chars","attributes":{"count":"162"}},{"tagName":"char","attributes":{"id":"0","x":"0","y":"0","width":"0","height":"0","xoffset":"-1","yoffset":"11","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"13","x":"0","y":"0","width":"0","height":"0","xoffset":"-1","yoffset":"11","xadvance":"4","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"32","x":"0","y":"0","width":"0","height":"0","xoffset":"-1","yoffset":"11","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"33","x":"296","y":"0","width":"5","height":"13","xoffset":"2","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"34","x":"287","y":"30","width":"8","height":"6","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"35","x":"215","y":"18","width":"10","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"36","x":"84","y":"0","width":"10","height":"16","xoffset":"-1","yoffset":"-1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"37","x":"315","y":"0","width":"12","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"38","x":"327","y":"0","width":"11","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"39","x":"302","y":"30","width":"5","height":"6","xoffset":"2","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"40","x":"0","y":"0","width":"7","height":"18","xoffset":"0","yoffset":"-1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"41","x":"7","y":"0","width":"8","height":"18","xoffset":"0","yoffset":"-1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"42","x":"254","y":"30","width":"9","height":"9","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"43","x":"54","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"44","x":"263","y":"30","width":"6","height":"8","xoffset":"1","yoffset":"9","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"45","x":"323","y":"30","width":"6","height":"4","xoffset":"1","yoffset":"6","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"46","x":"318","y":"30","width":"5","height":"5","xoffset":"2","yoffset":"8","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"47","x":"105","y":"0","width":"10","height":"15","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"48","x":"187","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"49","x":"101","y":"18","width":"9","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"50","x":"110","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"51","x":"119","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"52","x":"129","y":"18","width":"10","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"53","x":"139","y":"18","width":"10","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"54","x":"149","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"55","x":"159","y":"18","width":"8","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"56","x":"167","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"57","x":"177","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"58","x":"49","y":"30","width":"5","height":"10","xoffset":"2","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"59","x":"309","y":"0","width":"6","height":"13","xoffset":"1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"60","x":"198","y":"18","width":"8","height":"12","xoffset":"0","yoffset":"2","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"61","x":"279","y":"30","width":"8","height":"7","xoffset":"0","yoffset":"4","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"62","x":"206","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"2","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"63","x":"301","y":"0","width":"8","height":"13","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"64","x":"72","y":"0","width":"12","height":"16","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"65","x":"358","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"66","x":"369","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"67","x":"379","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"68","x":"389","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"69","x":"400","y":"0","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"70","x":"409","y":"0","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"71","x":"418","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"72","x":"429","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"73","x":"439","y":"0","width":"8","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"74","x":"447","y":"0","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"75","x":"456","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"76","x":"466","y":"0","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"77","x":"475","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"78","x":"486","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"79","x":"496","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"80","x":"0","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"81","x":"94","y":"0","width":"11","height":"15","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"82","x":"10","y":"18","width":"9","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"83","x":"19","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"84","x":"29","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"85","x":"38","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"86","x":"48","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"87","x":"59","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"88","x":"70","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"89","x":"81","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"90","x":"92","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"91","x":"40","y":"0","width":"7","height":"16","xoffset":"1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"93","x":"47","y":"0","width":"7","height":"16","xoffset":"1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"94","x":"269","y":"30","width":"10","height":"7","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"95","x":"329","y":"30","width":"10","height":"4","xoffset":"-1","yoffset":"13","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"96","x":"295","y":"30","width":"7","height":"6","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"97","x":"432","y":"18","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"98","x":"189","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"99","x":"442","y":"18","width":"9","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"100","x":"199","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"101","x":"451","y":"18","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"102","x":"209","y":"0","width":"11","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"103","x":"220","y":"0","width":"11","height":"13","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"104","x":"231","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"105","x":"241","y":"0","width":"8","height":"13","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"106","x":"31","y":"0","width":"9","height":"16","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"107","x":"249","y":"0","width":"10","height":"13","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"108","x":"259","y":"0","width":"8","height":"13","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"109","x":"461","y":"18","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"110","x":"472","y":"18","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"111","x":"482","y":"18","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"112","x":"267","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"113","x":"135","y":"0","width":"10","height":"14","xoffset":"-1","yoffset":"2","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"114","x":"493","y":"18","width":"10","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"115","x":"0","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"116","x":"277","y":"0","width":"9","height":"13","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"117","x":"9","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"118","x":"19","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"119","x":"29","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"120","x":"39","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"121","x":"286","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"122","x":"503","y":"18","width":"8","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"123","x":"54","y":"0","width":"9","height":"16","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"124","x":"15","y":"0","width":"5","height":"18","xoffset":"2","yoffset":"-2","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"125","x":"63","y":"0","width":"9","height":"16","xoffset":"0","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"126","x":"307","y":"30","width":"11","height":"6","xoffset":"-1","yoffset":"5","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1025","x":"115","y":"0","width":"10","height":"15","xoffset":"-1","yoffset":"-2","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1040","x":"358","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1041","x":"225","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1042","x":"369","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1043","x":"235","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1044","x":"155","y":"0","width":"12","height":"14","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1045","x":"400","y":"0","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1046","x":"256","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1047","x":"267","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1048","x":"276","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1049","x":"125","y":"0","width":"10","height":"15","xoffset":"-1","yoffset":"-2","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1050","x":"456","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1051","x":"286","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1052","x":"475","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1053","x":"429","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1054","x":"496","y":"0","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1055","x":"296","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1056","x":"0","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1057","x":"379","y":"0","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1058","x":"29","y":"18","width":"9","height":"12","xoffset":"0","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1059","x":"306","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1060","x":"316","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1061","x":"70","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1062","x":"167","y":"0","width":"11","height":"14","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1063","x":"338","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1064","x":"348","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1065","x":"178","y":"0","width":"11","height":"14","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1066","x":"391","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1067","x":"370","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1068","x":"381","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1069","x":"402","y":"18","width":"10","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1070","x":"412","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1071","x":"423","y":"18","width":"9","height":"12","xoffset":"-1","yoffset":"1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1072","x":"432","y":"18","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1073","x":"145","y":"0","width":"10","height":"14","xoffset":"-1","yoffset":"-1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1074","x":"63","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1075","x":"73","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1076","x":"244","y":"18","width":"12","height":"12","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1077","x":"451","y":"18","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1078","x":"82","y":"30","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1079","x":"93","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1080","x":"102","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1081","x":"348","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1082","x":"111","y":"30","width":"10","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1083","x":"121","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1084","x":"131","y":"30","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1085","x":"142","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1086","x":"482","y":"18","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1087","x":"152","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1088","x":"267","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1089","x":"442","y":"18","width":"9","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1090","x":"162","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1091","x":"286","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1092","x":"20","y":"0","width":"11","height":"17","xoffset":"-1","yoffset":"-1","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1093","x":"39","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1094","x":"327","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1095","x":"171","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1096","x":"181","y":"30","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1097","x":"359","y":"18","width":"11","height":"12","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1098","x":"213","y":"30","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1099","x":"192","y":"30","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1100","x":"203","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1101","x":"224","y":"30","width":"10","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1102","x":"234","y":"30","width":"11","height":"10","xoffset":"-1","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1103","x":"245","y":"30","width":"9","height":"10","xoffset":"0","yoffset":"3","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"char","attributes":{"id":"1105","x":"338","y":"0","width":"10","height":"13","xoffset":"-1","yoffset":"0","xadvance":"12","page":"0","chnl":"0"}},{"tagName":"kernings","attributes":{"count":"0"}},{"attributes":{}}]});
    

/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(11);


/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

if (true) {
    window.__POLYFILLS_INCLUDED__ = true;
}
if (typeof globalThis === 'undefined')
    window.globalThis = window;
var rafPolyfill = function (f) {
    return setTimeout(f, 17);
};
globalThis.requestAnimationFrame =
    globalThis.requestAnimationFrame ||
        globalThis.webkitRequestAnimationFrame ||
        rafPolyfill;
if (!globalThis.cancelAnimationFrame) {
    globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); };
}
if (!Array.prototype.find) {
    Array.prototype.find = function (predicate) {
        if (!this && true) {
            throw new TypeError('Array.prototype.find called on null or undefined');
        }
        if (typeof predicate !== 'function' && true) {
            throw new TypeError('predicate must be a function');
        }
        var list = Object(this);
        var length = list.length >>> 0;
        var thisArg = arguments[1];
        var value;
        for (var i = 0; i < length; i++) {
            value = list[i];
            if (predicate.call(thisArg, value, i, list)) {
                return value;
            }
        }
        return undefined;
    };
}


/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Element", function() { return Element; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Document", function() { return Document; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);

var Element = (function () {
    function Element() {
        this.children = [];
        this.attributes = {};
    }
    Element.fromData = function (data) {
        var el = new Element();
        el.tagName = data.tagName;
        el.attributes = data.attributes;
        if (data.children)
            data.children.forEach(function (c) {
                el.children.push(Element.fromData(c));
            });
        return el;
    };
    Element.visitAll = function (children, onVisited) {
        children.forEach(function (c) {
            onVisited(c);
            Element.visitAll(c.children, onVisited);
        });
    };
    Element.prototype.getElementById = function (id) {
        var el;
        Element.visitAll(this.children, function (current) {
            if (current.attributes.id === id)
                el = current;
        });
        if (el === undefined)
            return undefined;
        else
            return Element.fromData(el);
    };
    Element.prototype.getElementsByTagName = function (tagName) {
        var arr = [];
        Element.visitAll(this.children, function (current) {
            if (current.tagName === tagName)
                arr.push(current);
        });
        return arr;
    };
    Element.prototype.querySelector = function (path) {
        return this.getElementsByTagName(path)[0];
    };
    Element.prototype.querySelectorAll = function (path) {
        return this.getElementsByTagName(path);
    };
    Element.prototype.getAttribute = function (name) {
        return this.attributes[name];
    };
    return Element;
}());

var Document = (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "c"])(Document, _super);
    function Document() {
        return _super.call(this) || this;
    }
    Document.create = function (desc) {
        return Element.fromData(desc);
    };
    return Document;
}(Element));



/***/ }),
/* 10 */,
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXTERNAL MODULE: ./engine/misc/polyfills.ts
var polyfills = __webpack_require__(8);

// CONCATENATED MODULE: ./engine/misc/easing/functions/linear.ts
var EasingLinear = function (t, b, c, d) { return c * t / d + b; };

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// CONCATENATED MODULE: ./engine/debug/debugError.ts

var debugError_DebugError = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(DebugError, _super);
    function DebugError(message) {
        var _this = _super.call(this, message) || this;
        if (Error.captureStackTrace) {
            Error.captureStackTrace(_this, _this.constructor);
        }
        else {
            _this.stack = (new Error()).stack;
        }
        _this.name = 'DebugError';
        _this.errorMessage = message;
        return _this;
    }
    DebugError.prototype.toString = function () {
        return this.errorMessage;
    };
    return DebugError;
}(Error));


// CONCATENATED MODULE: ./engine/animation/tween.ts



var tween_Tween = (function () {
    function Tween(tweenDesc) {
        var _a;
        this._propsToChange = [];
        this._startedTime = 0;
        this._delayWaitTime = 0;
        this._currTime = 0;
        this._completed = false;
        this._delayBeforeStart = 0;
        this._currentLoop = 0;
        this._started = false;
        this._target = tweenDesc.target;
        this._progressFn = tweenDesc.progress;
        this._completeFn = tweenDesc.complete;
        this._startedFn = tweenDesc.start;
        this._easeFn = tweenDesc.ease || EasingLinear;
        this._delayBeforeStart = tweenDesc.delayBeforeStart || 0;
        this._tweenTime = (tweenDesc.time || 1000);
        if ( true && tweenDesc.loop === undefined && tweenDesc.numOfLoops !== undefined) {
            throw new debugError_DebugError("loop property need to be set to true if numOfLoops is specified");
        }
        if ( true && tweenDesc.loop === undefined && tweenDesc.yoyo !== undefined) {
            throw new debugError_DebugError("loop property need to be set to true if yoyo is true");
        }
        this._loop = tweenDesc.loop || false;
        this._numOfLoops = (_a = tweenDesc.numOfLoops) !== null && _a !== void 0 ? _a : Infinity;
        this._yoyo = tweenDesc.yoyo || false;
        this._desc = this.normalizeDesc(tweenDesc);
    }
    Tween.prototype.update = function () {
        if (this._completed)
            return;
        var currTime = game_Game.getInstance().getCurrentTime();
        if (this._currentLoop === 0 && this._delayBeforeStart > 0) {
            this._delayWaitTime = this._delayWaitTime || currTime;
            if (currTime - this._delayWaitTime < this._delayBeforeStart)
                return;
        }
        this._currTime = currTime;
        if (this._startedTime === 0)
            this._startedTime = currTime;
        var curTweenTime = currTime - this._startedTime;
        if (curTweenTime > this._tweenTime) {
            if (this._loop) {
                this._startedTime = currTime;
                if (this._currentLoop === this._numOfLoops - 1) {
                    this.complete();
                    return;
                }
                this._currentLoop++;
                curTweenTime = 0;
            }
            else {
                this.complete();
                return;
            }
        }
        if (this._yoyo && this._currentLoop % 2 !== 0) {
            curTweenTime = this._tweenTime - curTweenTime;
        }
        var l = this._propsToChange.length;
        if (this._startedFn && !this._started)
            this._startedFn(this._target);
        while (l--) {
            var prp = this._propsToChange[l];
            var valFrom = this._desc.from[prp];
            var valTo = this._desc.to[prp];
            var fn = this._easeFn;
            this._target[prp] = fn(curTweenTime, valFrom, valTo - valFrom, this._tweenTime);
        }
        if (this._progressFn)
            this._progressFn(this._target);
        this._started = true;
    };
    Tween.prototype.reset = function () {
        this._startedTime = 0;
        this._completed = false;
    };
    Tween.prototype.complete = function () {
        if (this._completed)
            return;
        var needReversion = this._yoyo && this._currentLoop % 2 !== 0;
        var target = needReversion ? this._desc.from : this._desc.to;
        for (var _i = 0, _a = this._propsToChange; _i < _a.length; _i++) {
            var k = _a[_i];
            this._target[k] = target[k];
        }
        if (this._progressFn)
            this._progressFn(this._target);
        if (this._completeFn)
            this._completeFn(this._target);
        this._completed = true;
    };
    Tween.prototype.isCompleted = function () {
        return this._completed;
    };
    Tween.prototype.getTarget = function () {
        return this._target;
    };
    Tween.prototype.getTweenTime = function () {
        return this._tweenTime;
    };
    Tween.prototype.normalizeDesc = function (tweenDesc) {
        var _this = this;
        var normalized = tweenDesc;
        normalized.from = normalized.from || {};
        normalized.to = normalized.to || {};
        var allPropsMap = {};
        Object.keys(normalized.from).forEach(function (keyFrom) {
            allPropsMap[keyFrom] = true;
        });
        Object.keys(normalized.to).forEach(function (keyTo) {
            allPropsMap[keyTo] = true;
        });
        this._propsToChange = Object.keys(allPropsMap);
        if (true) {
            this._propsToChange.forEach(function (key) {
                if (!(key in _this._target)) {
                    console.error('target', _this._target);
                    throw new debugError_DebugError("Can not create tween animation: property \"" + key + "\" does not belong to target object");
                }
            });
        }
        this._propsToChange.forEach(function (prp) {
            if (normalized.from[prp] === undefined)
                normalized.from[prp] = _this._target[prp];
            if (normalized.to[prp] === undefined)
                normalized.to[prp] = _this._target[prp];
        });
        return normalized;
    };
    return Tween;
}());


// CONCATENATED MODULE: ./engine/misc/objectPool.ts

var objectPool_ObjectPool = (function () {
    function ObjectPool(Class, numberOfInstances) {
        if (numberOfInstances === void 0) { numberOfInstances = 16; }
        this.Class = Class;
        this.numberOfInstances = numberOfInstances;
        this._pool = [];
        if ( true && !Class)
            throw new debugError_DebugError("can not instantiate ObjectPool: class not provided in constructor");
    }
    ObjectPool.prototype.getFreeObject = function (silently) {
        if (silently === void 0) { silently = false; }
        for (var i = 0; i < this.numberOfInstances; i++) {
            var current = this._pool[i];
            if (current === undefined) {
                current = this._pool[i] = new this.Class();
                current.capture();
                return current;
            }
            else if (!current.isCaptured()) {
                current.capture();
                return current;
            }
        }
        if ( true && !silently)
            throw new debugError_DebugError("can not get free object: no free object in pool");
        return undefined;
    };
    ObjectPool.prototype.releaseObject = function (obj) {
        var indexOf = this._pool.indexOf(obj);
        if ( true && indexOf === -1) {
            console.error(obj);
            throw new debugError_DebugError("can not release the object: it does not belong to the pool");
        }
        this._pool[indexOf].release();
    };
    ObjectPool.prototype.releaseAll = function () {
        for (var i = 0; i < this.numberOfInstances; i++) {
            var current = this._pool[i];
            if (current !== undefined) {
                current.release();
            }
        }
    };
    return ObjectPool;
}());


// EXTERNAL MODULE: ./engine/misc/object.ts
var object = __webpack_require__(1);

// CONCATENATED MODULE: ./engine/misc/releaseableEntity.ts
var ReleaseableEntity = (function () {
    function ReleaseableEntity() {
        this._captured = false;
    }
    ReleaseableEntity.prototype.isCaptured = function () {
        return this._captured;
    };
    ReleaseableEntity.prototype.capture = function () {
        this._captured = true;
        return this;
    };
    ReleaseableEntity.prototype.release = function () {
        this._captured = false;
        return this;
    };
    return ReleaseableEntity;
}());


// CONCATENATED MODULE: ./engine/geometry/abstract/observableEntity.ts



var observableEntity_ObservableEntity = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(ObservableEntity, _super);
    function ObservableEntity() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._onChanged = [];
        return _this;
    }
    ObservableEntity.prototype.forceTriggerChange = function () {
        for (var _i = 0, _a = this._onChanged; _i < _a.length; _i++) {
            var fn = _a[_i];
            fn();
        }
    };
    ObservableEntity.prototype.addOnChangeListener = function (f) {
        this._onChanged.push(f);
    };
    ObservableEntity.prototype.removeOnChangeListener = function (f) {
        Object(object["i" /* removeFromArray */])(this._onChanged, function (it) { return it === f; });
    };
    ObservableEntity.prototype.observe = function (onChangedFn) {
        this.addOnChangeListener(onChangedFn);
    };
    ObservableEntity.prototype.triggerObservable = function () {
        for (var _i = 0, _a = this._onChanged; _i < _a.length; _i++) {
            var fn = _a[_i];
            fn();
        }
    };
    return ObservableEntity;
}(ReleaseableEntity));


// CONCATENATED MODULE: ./engine/geometry/point2d.ts




var point2d_Point2d = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Point2d, _super);
    function Point2d(x, y, onChangedFn) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = x; }
        var _this = _super.call(this) || this;
        _this._x = 0;
        _this._y = 0;
        if (onChangedFn)
            _this.addOnChangeListener(onChangedFn);
        _this.setXY(x, y);
        return _this;
    }
    Object.defineProperty(Point2d.prototype, "x", {
        get: function () {
            return this._x;
        },
        set: function (value) {
            this.setX(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Point2d.prototype, "y", {
        get: function () {
            return this._y;
        },
        set: function (value) {
            this.setY(value);
        },
        enumerable: false,
        configurable: true
    });
    Point2d.fromPool = function () {
        return Point2d.pool.getFreeObject();
    };
    Point2d.prototype.setXY = function (x, y) {
        if (y === void 0) { y = x; }
        if ( true && (Number.isNaN(x) || Number.isNaN(y))) {
            console.trace();
            throw new debugError_DebugError("Point2d: wrong numeric arguments " + x + "," + y);
        }
        var changed = this._x !== x || this._y !== y;
        if (changed) {
            this._x = x;
            this._y = y;
            this.triggerObservable();
        }
        return this;
    };
    Point2d.prototype.setX = function (x) {
        this.setXY(x, this._y);
        return this;
    };
    Point2d.prototype.setY = function (y) {
        this.setXY(this._x, y);
        return this;
    };
    Point2d.prototype.set = function (another) {
        this.setXY(another.x, another.y);
        return this;
    };
    Point2d.prototype.add = function (another) {
        this.addXY(another.x, another.y);
        return this;
    };
    Point2d.prototype.substract = function (another) {
        this.addXY(-another.x, -another.y);
        return this;
    };
    Point2d.prototype.multiply = function (n) {
        this.setXY(this._x * n, this._y * n);
        return this;
    };
    Point2d.prototype.addXY = function (x, y) {
        this.setXY(this._x + x, this._y + y);
        return this;
    };
    Point2d.prototype.addX = function (x) {
        this.addXY(x, 0);
        return this;
    };
    Point2d.prototype.addY = function (y) {
        this.addXY(0, y);
        return this;
    };
    Point2d.prototype.negative = function () {
        this.setXY(-this._x, -this._y);
        return this;
    };
    Point2d.prototype.equal = function (x, y) {
        if (y === void 0) { y = x; }
        return this._x === x && this._y === y;
    };
    Point2d.prototype.equalPoint = function (point) {
        return this.equal(point.x, point.y);
    };
    Point2d.prototype.clone = function () {
        return new Point2d(this._x, this._y);
    };
    Point2d.prototype.fromJSON = function (json) {
        this.setXY(json.x, json.y);
    };
    Point2d.prototype.toJSON = function () {
        return { x: this._x, y: this._y };
    };
    Point2d.prototype.toArray = function () {
        if (this._arr === undefined)
            this._arr = [this._x, this._y];
        else {
            this._arr[0] = this._x;
            this._arr[1] = this._y;
        }
        return this._arr;
    };
    Point2d.pool = new objectPool_ObjectPool(Point2d, 4);
    return Point2d;
}(observableEntity_ObservableEntity));


// CONCATENATED MODULE: ./engine/geometry/mat4.ts




var mat4_mat4;
(function (mat4) {
    var Mat16Holder = (function (_super) {
        Object(tslib_es6["c" /* __extends */])(Mat16Holder, _super);
        function Mat16Holder() {
            var _this = _super.call(this) || this;
            _this.mat16 = new Float32Array(16);
            _this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
            return _this;
        }
        Mat16Holder.fromPool = function () {
            return Mat16Holder.m16hPool.getFreeObject();
        };
        Mat16Holder.create = function () {
            return new Mat16Holder();
        };
        Mat16Holder.prototype.set = function (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
            var mat16 = this.mat16;
            mat16[0] = v0;
            mat16[1] = v1;
            mat16[2] = v2;
            mat16[3] = v3;
            mat16[4] = v4;
            mat16[5] = v5;
            mat16[6] = v6;
            mat16[7] = v7;
            mat16[8] = v8;
            mat16[9] = v9;
            mat16[10] = v10;
            mat16[11] = v11;
            mat16[12] = v12;
            mat16[13] = v13;
            mat16[14] = v14;
            mat16[15] = v15;
        };
        Mat16Holder.prototype.fromMat16 = function (mat16) {
            this.set(mat16[0], mat16[1], mat16[2], mat16[3], mat16[4], mat16[5], mat16[6], mat16[7], mat16[8], mat16[9], mat16[10], mat16[11], mat16[12], mat16[13], mat16[14], mat16[15]);
        };
        Mat16Holder.prototype.clone = function () {
            var m = new Mat16Holder();
            for (var i = 0; i < this.mat16.length; i++) {
                m.mat16[i] = this.mat16[i];
            }
            return m;
        };
        Mat16Holder.m16hPool = new objectPool_ObjectPool(Mat16Holder, 256);
        return Mat16Holder;
    }(ReleaseableEntity));
    mat4.Mat16Holder = Mat16Holder;
    mat4.makeIdentity = function (out) {
        out.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    };
    mat4.makeZToWMatrix = function (out, fudgeFactor) {
        out.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, fudgeFactor, 0, 0, 0, 1);
    };
    mat4.make2DProjection = function (out, width, height, depth) {
        out.set(2 / width, 0, 0, 0, 0, -2 / height, 0, 0, 0, 0, 2 / depth, 0, -1, 1, 0, 1);
    };
    mat4.ortho = function (out, left, right, bottom, top, near, far) {
        if (true) {
            if (left === right || bottom === top || near === far) {
                console.error({ left: left, right: right, bottom: bottom, top: top, near: near, far: far });
                throw new debugError_DebugError("Can not create ortho matrix with wrong parameters");
            }
        }
        var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far);
        var outMat16 = out.mat16;
        outMat16[0] = -2 * lr;
        outMat16[1] = 0;
        outMat16[2] = 0;
        outMat16[3] = 0;
        outMat16[4] = 0;
        outMat16[5] = -2 * bt;
        outMat16[6] = 0;
        outMat16[7] = 0;
        outMat16[8] = 0;
        outMat16[9] = 0;
        outMat16[10] = 2 * nf;
        outMat16[11] = 0;
        outMat16[12] = (left + right) * lr;
        outMat16[13] = (top + bottom) * bt;
        outMat16[14] = (far + near) * nf;
        outMat16[15] = 1;
    };
    mat4.perspective = function (out, fovy, aspect, near, far) {
        var f = 1.0 / Math.tan(fovy / 2), nf = 1 / (near - far);
        var outMat16 = out.mat16;
        outMat16[0] = f / aspect;
        outMat16[1] = 0;
        outMat16[2] = 0;
        outMat16[3] = 0;
        outMat16[4] = 0;
        outMat16[5] = f;
        outMat16[6] = 0;
        outMat16[7] = 0;
        outMat16[8] = 0;
        outMat16[9] = 0;
        outMat16[10] = (far + near) * nf;
        outMat16[11] = -1;
        outMat16[12] = 0;
        outMat16[13] = 0;
        outMat16[14] = (2 * far * near) * nf;
        outMat16[15] = 0;
    };
    mat4.makeTranslation = function (out, tx, ty, tz) {
        out.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1);
    };
    mat4.makeXSkew = function (out, angle) {
        out.set(1, 0, 0, 0, Math.tan(angle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    };
    mat4.makeYSkew = function (out, angle) {
        out.set(1, Math.tan(angle), 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    };
    mat4.makeXRotation = function (out, angleInRadians) {
        var c = Math.cos(angleInRadians);
        var s = Math.sin(angleInRadians);
        out.set(1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1);
    };
    mat4.makeYRotation = function (out, angleInRadians) {
        var c = Math.cos(angleInRadians);
        var s = Math.sin(angleInRadians);
        out.set(c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1);
    };
    mat4.makeZRotation = function (out, angleInRadians) {
        var c = Math.cos(angleInRadians);
        var s = Math.sin(angleInRadians);
        out.set(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    };
    mat4.makeRotationReset = function (out) {
        var matrix = out.mat16;
        var d = Math.sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1] + matrix[2] * matrix[2]);
        matrix[0] = d;
        matrix[4] = 0;
        matrix[8] = 0;
        matrix[1] = 0;
        matrix[5] = d;
        matrix[9] = 0;
        matrix[2] = 0;
        matrix[6] = 0;
        matrix[10] = d;
        matrix[3] = 0;
        matrix[7] = 0;
        matrix[11] = 0;
        matrix[15] = 1;
    };
    mat4.makeScale = function (out, sx, sy, sz) {
        out.set(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1);
    };
    mat4.matrixMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12];
        r[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13];
        r[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14];
        r[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15];
        r[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12];
        r[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13];
        r[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14];
        r[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15];
        r[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12];
        r[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13];
        r[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14];
        r[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15];
        r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12];
        r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13];
        r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14];
        r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15];
    };
    mat4.multVecByMatrix = function (out, matrix, vec4Arr) {
        for (var i = 0; i < 4; i++) {
            out.vec4[i] =
                vec4Arr.vec4[0] * matrix.mat16[0 * 4 + i] +
                    vec4Arr.vec4[1] * matrix.mat16[1 * 4 + i] +
                    vec4Arr.vec4[2] * matrix.mat16[2 * 4 + i] +
                    vec4Arr.vec4[3] * matrix.mat16[3 * 4 + i];
        }
    };
    mat4.inverse = function (out, mHolder) {
        var r = out.mat16;
        var m = mHolder.mat16;
        r[0] = m[5] * m[10] * m[15] - m[5] * m[14] * m[11] - m[6] * m[9] * m[15] + m[6] * m[13] * m[11] + m[7] * m[9] * m[14] - m[7] * m[13] * m[10];
        r[1] = -m[1] * m[10] * m[15] + m[1] * m[14] * m[11] + m[2] * m[9] * m[15] - m[2] * m[13] * m[11] - m[3] * m[9] * m[14] + m[3] * m[13] * m[10];
        r[2] = m[1] * m[6] * m[15] - m[1] * m[14] * m[7] - m[2] * m[5] * m[15] + m[2] * m[13] * m[7] + m[3] * m[5] * m[14] - m[3] * m[13] * m[6];
        r[3] = -m[1] * m[6] * m[11] + m[1] * m[10] * m[7] + m[2] * m[5] * m[11] - m[2] * m[9] * m[7] - m[3] * m[5] * m[10] + m[3] * m[9] * m[6];
        r[4] = -m[4] * m[10] * m[15] + m[4] * m[14] * m[11] + m[6] * m[8] * m[15] - m[6] * m[12] * m[11] - m[7] * m[8] * m[14] + m[7] * m[12] * m[10];
        r[5] = m[0] * m[10] * m[15] - m[0] * m[14] * m[11] - m[2] * m[8] * m[15] + m[2] * m[12] * m[11] + m[3] * m[8] * m[14] - m[3] * m[12] * m[10];
        r[6] = -m[0] * m[6] * m[15] + m[0] * m[14] * m[7] + m[2] * m[4] * m[15] - m[2] * m[12] * m[7] - m[3] * m[4] * m[14] + m[3] * m[12] * m[6];
        r[7] = m[0] * m[6] * m[11] - m[0] * m[10] * m[7] - m[2] * m[4] * m[11] + m[2] * m[8] * m[7] + m[3] * m[4] * m[10] - m[3] * m[8] * m[6];
        r[8] = m[4] * m[9] * m[15] - m[4] * m[13] * m[11] - m[5] * m[8] * m[15] + m[5] * m[12] * m[11] + m[7] * m[8] * m[13] - m[7] * m[12] * m[9];
        r[9] = -m[0] * m[9] * m[15] + m[0] * m[13] * m[11] + m[1] * m[8] * m[15] - m[1] * m[12] * m[11] - m[3] * m[8] * m[13] + m[3] * m[12] * m[9];
        r[10] = m[0] * m[5] * m[15] - m[0] * m[13] * m[7] - m[1] * m[4] * m[15] + m[1] * m[12] * m[7] + m[3] * m[4] * m[13] - m[3] * m[12] * m[5];
        r[11] = -m[0] * m[5] * m[11] + m[0] * m[9] * m[7] + m[1] * m[4] * m[11] - m[1] * m[8] * m[7] - m[3] * m[4] * m[9] + m[3] * m[8] * m[5];
        r[12] = -m[4] * m[9] * m[14] + m[4] * m[13] * m[10] + m[5] * m[8] * m[14] - m[5] * m[12] * m[10] - m[6] * m[8] * m[13] + m[6] * m[12] * m[9];
        r[13] = m[0] * m[9] * m[14] - m[0] * m[13] * m[10] - m[1] * m[8] * m[14] + m[1] * m[12] * m[10] + m[2] * m[8] * m[13] - m[2] * m[12] * m[9];
        r[14] = -m[0] * m[5] * m[14] + m[0] * m[13] * m[6] + m[1] * m[4] * m[14] - m[1] * m[12] * m[6] - m[2] * m[4] * m[13] + m[2] * m[12] * m[5];
        r[15] = m[0] * m[5] * m[10] - m[0] * m[9] * m[6] - m[1] * m[4] * m[10] + m[1] * m[8] * m[6] + m[2] * m[4] * m[9] - m[2] * m[8] * m[5];
        var det = m[0] * r[0] + m[1] * r[4] + m[2] * r[8] + m[3] * r[12];
        if ( true && det === 0) {
            console.error(m);
            throw new debugError_DebugError("can not invert matrix with zero determinant");
        }
        for (var i = 0; i < 16; i++)
            r[i] /= det;
    };
    mat4.transpose = function (out, mHolder) {
        var m = mHolder.mat16;
        out.set(m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14], m[3], m[7], m[11], m[15]);
    };
    var m16h = Mat16Holder.create();
    mat4.makeIdentity(m16h);
    mat4.IDENTITY = m16h.mat16;
    mat4.IDENTITY_HOLDER = new Mat16Holder();
    mat4.IDENTITY_HOLDER.set.apply(mat4.IDENTITY_HOLDER, mat4.IDENTITY);
})(mat4_mat4 || (mat4_mat4 = {}));

// CONCATENATED MODULE: ./engine/geometry/vec4.ts



var vec4_vec4;
(function (vec4) {
    var Vec4Holder = (function (_super) {
        Object(tslib_es6["c" /* __extends */])(Vec4Holder, _super);
        function Vec4Holder() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.vec4 = new Float32Array(4);
            return _this;
        }
        Vec4Holder.fromPool = function () {
            return Vec4Holder.pool.getFreeObject();
        };
        Vec4Holder.prototype.set = function (x, y, z, w) {
            var v = this.vec4;
            v[0] = x;
            v[1] = y;
            v[2] = z;
            v[3] = w;
        };
        Object.defineProperty(Vec4Holder.prototype, "x", {
            get: function () {
                return this.vec4[0];
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Vec4Holder.prototype, "y", {
            get: function () {
                return this.vec4[1];
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Vec4Holder.prototype, "z", {
            get: function () {
                return this.vec4[2];
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Vec4Holder.prototype, "w", {
            get: function () {
                return this.vec4[3];
            },
            enumerable: false,
            configurable: true
        });
        Vec4Holder.pool = new objectPool_ObjectPool(Vec4Holder, 32);
        return Vec4Holder;
    }(ReleaseableEntity));
    vec4.Vec4Holder = Vec4Holder;
})(vec4_vec4 || (vec4_vec4 = {}));

// CONCATENATED MODULE: ./engine/misc/mathEx.ts



var mathEx_MathEx;
(function (MathEx) {
    var Mat16Holder = mat4_mat4.Mat16Holder;
    var Vec4Holder = vec4_vec4.Vec4Holder;
    MathEx.isPointInRect = function (point, rect, angle) {
        return point.x > rect.x &&
            point.x < (rect.x + rect.width) &&
            point.y > rect.y &&
            point.y < (rect.y + rect.height);
    };
    MathEx.clamp = function (val, min, max) {
        if (val < min)
            val = min;
        if (val > max)
            val = max;
        return val;
    };
    MathEx.overlapTest = function (a, b) {
        return (a.x < b.x + b.width) &&
            (a.x + a.width > b.x) &&
            (a.y < b.y + b.height) &&
            (a.y + a.height > b.y);
    };
    MathEx.radToDeg = function (rad) {
        return rad * 180 / Math.PI;
    };
    MathEx.degToRad = function (deg) {
        return deg * Math.PI / 180;
    };
    MathEx.rectToPolar = function (point, center) {
        var radius = Math.sqrt(point.x * point.x + center.y * center.y);
        var angle = Math.atan2(center.y - point.y, center.x - point.x);
        return { radius: radius, angle: angle };
    };
    MathEx.polarToRect = function (radius, angle, center) {
        var x = radius * Math.cos(angle);
        var y = radius * Math.sin(angle);
        return new point2d_Point2d(center.x - x, center.y - y);
    };
    MathEx.getDistanceSquared = function (p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
    };
    MathEx.closeTo = function (a, b, epsilon) {
        if (epsilon === void 0) { epsilon = 0.01; }
        return Math.abs(a - b) <= epsilon;
    };
    MathEx.getDistance = function (p1, p2) {
        return Math.sqrt(MathEx.getDistanceSquared(p1, p2));
    };
    MathEx.getAngle = function (p1, p2) {
        var dx = p1.x - p2.x;
        var dy = p1.y - p2.y;
        return Math.atan2(dy, dx);
    };
    MathEx.random = function (min, max) {
        if (min > max) {
            var tmp = min;
            min = max;
            max = tmp;
        }
        return Math.random() * (max - min) + min;
    };
    MathEx.randomInt = function (min, max) {
        return ~~MathEx.random(min, max);
    };
    MathEx.randomByte = function (min, max) {
        return MathEx.randomInt(min, max);
    };
    MathEx.unProject = function (winPoint, width, height, viewProjectionMatrix) {
        var x = 2.0 * winPoint.x / width - 1;
        var y = 2.0 * winPoint.y / height - 1;
        var viewProjectionInverse = Mat16Holder.fromPool();
        mat4_mat4.inverse(viewProjectionInverse, viewProjectionMatrix);
        var point3D = Vec4Holder.fromPool();
        point3D.set(x, y, 0, 1);
        var res = Vec4Holder.fromPool();
        mat4_mat4.multVecByMatrix(res, viewProjectionInverse, point3D);
        var resultX = (res.x / 2 + 0.5) * width;
        var resultY = (res.y / 2 + 0.5) * height;
        var result = point2d_Point2d.fromPool();
        result.setXY(resultX, resultY);
        point3D.release();
        res.release();
        viewProjectionInverse.release();
        return result;
    };
})(mathEx_MathEx || (mathEx_MathEx = {}));

// CONCATENATED MODULE: ./engine/geometry/rect.ts




var rect_Rect = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Rect, _super);
    function Rect(x, y, width, height, onChangedFn) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (width === void 0) { width = 0; }
        if (height === void 0) { height = 0; }
        var _this = _super.call(this) || this;
        _this._x = 0;
        _this._y = 0;
        _this._width = 0;
        _this._height = 0;
        _this._arr = [0, 0, 0, 0];
        if (onChangedFn)
            _this.addOnChangeListener(onChangedFn);
        _this.setXYWH(x, y, width, height);
        return _this;
    }
    Rect.fromPool = function () {
        return Rect.rectPool.getFreeObject();
    };
    Rect.prototype.setXYWH = function (x, y, width, height) {
        if ( true &&
            (Number.isNaN(x) ||
                Number.isNaN(y) ||
                Number.isNaN(width) ||
                Number.isNaN(height)))
            throw new debugError_DebugError("Rect: wrong numeric arguments " + x + "," + y + "," + width + "," + height);
        var oldX = this._x;
        var oldY = this._y;
        var oldW = this._width;
        var oldH = this._height;
        var changed = oldX !== x || oldY !== y || oldW !== width || oldH !== height;
        if (changed) {
            this._x = x;
            this._y = y;
            this._width = width;
            this._height = height;
            this._right = this._x + this._width;
            this._bottom = this._y + this._height;
            this.triggerObservable();
        }
        return this;
    };
    Object.defineProperty(Rect.prototype, "x", {
        get: function () {
            return this._x;
        },
        set: function (x) {
            this.setXY(x, this.y);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rect.prototype, "y", {
        get: function () {
            return this._y;
        },
        set: function (y) {
            this.setXY(this.x, y);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rect.prototype, "width", {
        get: function () {
            return this._width;
        },
        set: function (width) {
            this.setWH(width, this.height);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rect.prototype, "height", {
        get: function () {
            return this._height;
        },
        set: function (height) {
            this.setWH(this.width, height);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rect.prototype, "right", {
        get: function () {
            return this._right;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rect.prototype, "bottom", {
        get: function () {
            return this._bottom;
        },
        enumerable: false,
        configurable: true
    });
    Rect.prototype.setXY = function (x, y) {
        this.setXYWH(x, y, this._width, this._height);
        return this;
    };
    Rect.prototype.setWH = function (width, height) {
        this.setXYWH(this._x, this._y, width, height);
        return this;
    };
    Rect.prototype.set = function (another) {
        this.setXYWH(another.x, another.y, another.width, another.height);
        return this;
    };
    Rect.prototype.setSize = function (s) {
        this.setWH(s.width, s.height);
        return this;
    };
    Rect.prototype.setPoint = function (p) {
        this.setXY(p.x, p.y);
        return this;
    };
    Rect.prototype.setPointAndSize = function (p, size) {
        this.setPoint(p);
        this.setSize(size);
        return this;
    };
    Rect.prototype.addXY = function (x, y) {
        this.setXY(this._x + x, this._y + y);
        return this;
    };
    Rect.prototype.addWH = function (width, height) {
        this.setWH(this._width + width, this._height + height);
        return this;
    };
    Rect.prototype.addPoint = function (another) {
        this.addXY(another.x, another.y);
        return this;
    };
    Rect.prototype.isZeroSize = function () {
        return this._width === 0 || this._height === 0;
    };
    Rect.prototype.clone = function () {
        return new Rect(this._x, this._y, this._width, this._height);
    };
    Rect.prototype.toJSON = function () {
        return {
            x: this._x,
            y: this._y,
            width: this._width,
            height: this._height
        };
    };
    Rect.prototype.toArray = function () {
        this._arr[0] = this._x;
        this._arr[1] = this._y;
        this._arr[2] = this._width;
        this._arr[3] = this._height;
        return this._arr;
    };
    Rect.prototype.fromJSON = function (jsonObj) {
        this.setXYWH(jsonObj.x, jsonObj.y, jsonObj.width, jsonObj.height);
    };
    Rect.rectPool = new objectPool_ObjectPool(Rect);
    return Rect;
}(observableEntity_ObservableEntity));


// CONCATENATED MODULE: ./engine/delegates/parentChildDelegate.ts

var parentChildDelegate_ParentChildDelegate = (function () {
    function ParentChildDelegate(model) {
        this.model = model;
    }
    ParentChildDelegate.prototype.appendChild = function (c) {
        if (true) {
            if (!c)
                throw new debugError_DebugError("illegal argument");
            if (c === this.model)
                throw new debugError_DebugError("parent and child objects are the same");
            if (this.model.children.find(function (it) { return it === c; })) {
                console.error(c);
                throw new debugError_DebugError("this children is already added");
            }
        }
        c.parent = this.model;
        this.model.children.push(c);
        if (this.afterChildAppended !== undefined)
            this.afterChildAppended(c);
    };
    ParentChildDelegate.prototype.appendChildAt = function (c, index) {
        if (true) {
            if (!c)
                throw new debugError_DebugError("illegal argument");
            if (index > this.model.children.length - 1)
                throw new debugError_DebugError("can not insert element: index is out of range (" + index + "," + (this.model.children.length - 1) + ")");
        }
        c.parent = this.model;
        this.model.children.splice(index, 0, c);
        if (this.afterChildAppended !== undefined)
            this.afterChildAppended(c);
    };
    ParentChildDelegate.prototype.appendChildAfter = function (modelAfter, newChild) {
        if (true) {
            if (!modelAfter || !newChild)
                throw new debugError_DebugError("illegal argument");
        }
        var afterIndex = this.model.children.indexOf(modelAfter);
        if (true) {
            if (afterIndex === -1)
                throw new debugError_DebugError("can not insert element: object is detached");
        }
        if (afterIndex === this.model.children.length - 1)
            this.appendChild(newChild);
        else
            this.appendChildAt(newChild, afterIndex + 1);
    };
    ParentChildDelegate.prototype.appendChildBefore = function (modelBefore, newChild) {
        if (true) {
            if (!modelBefore || !newChild)
                throw new debugError_DebugError("illegal argument");
        }
        var beforeIndex = this.model.children.indexOf(modelBefore);
        if (true) {
            if (beforeIndex === -1)
                throw new debugError_DebugError("can not insert element: object is detached");
        }
        if (beforeIndex === 0)
            this.prependChild(newChild);
        else
            this.appendChildAt(newChild, beforeIndex - 1);
    };
    ParentChildDelegate.prototype.prependChild = function (c) {
        if (true) {
            if (!c)
                throw new debugError_DebugError("illegal argument");
        }
        c.parent = this.model;
        this.model.children.unshift(c);
        if (this.afterChildAppended !== undefined)
            this.afterChildAppended(c);
    };
    ParentChildDelegate.prototype.removeChildAt = function (i) {
        var c = this.model.children[i];
        if ( true && !c)
            throw new debugError_DebugError("can not remove children with index " + i);
        if ( true && c.parent === undefined)
            throw new debugError_DebugError("can not remove children with index " + i + ": it is already detached");
        c.parent.children.splice(i, 1);
        c.parent = undefined;
        if (this.afterChildRemoved !== undefined)
            this.afterChildRemoved(c);
    };
    ParentChildDelegate.prototype.removeChild = function (child) {
        if (true) {
            if (!child)
                throw new debugError_DebugError("illegal argument");
        }
        var parent = child.getParent();
        var i = parent.children.indexOf(child);
        if ( true && i === -1)
            throw new debugError_DebugError("can not remove child: it doesn't belong to parent");
        parent.children.splice(i, 1);
        child.parent = undefined;
        if (this.afterChildRemoved !== undefined)
            this.afterChildRemoved(child);
    };
    ParentChildDelegate.prototype.removeSelf = function () {
        var parent = this.model.getParent();
        if ( true && parent === undefined)
            throw new debugError_DebugError("can not remove child: it is already detached");
        var i = parent.children.indexOf(this.model);
        if ( true && i === -1)
            throw new debugError_DebugError("can not remove child: it doesn't belong to parent");
        parent.children.splice(i, 1);
        this.model.parent = undefined;
        if (this.afterChildRemoved !== undefined)
            this.afterChildRemoved(this.model);
    };
    ParentChildDelegate.prototype.removeChildren = function () {
        for (var i = this.model.children.length - 1; i >= 0; i--) {
            this.removeChildAt(i);
        }
    };
    ParentChildDelegate.prototype.replaceChild = function (c, newChild) {
        if (true) {
            if (!c || !newChild)
                throw new debugError_DebugError("illegal argument");
        }
        var indexOf = this.model.children.indexOf(c);
        if ( true && indexOf === -1)
            throw new debugError_DebugError("can not replace child: destination node doesn't belong to element");
        this.model.children[indexOf] = newChild;
        c.parent = undefined;
        newChild.parent = this.model;
        if (this.afterChildRemoved !== undefined)
            this.afterChildRemoved(c);
        if (this.afterChildAppended !== undefined)
            this.afterChildAppended(newChild);
    };
    ParentChildDelegate.prototype.moveToFront = function () {
        var parent = this.model.getParent();
        if ( true && !parent)
            throw new debugError_DebugError("can not move to front: object is detached");
        var parentArray = parent.children;
        var index = parentArray.indexOf(this.model);
        if ( true && index === -1)
            throw new debugError_DebugError("can not move to front: object is not belong to current scene");
        parentArray.splice(index, 1);
        parentArray.push(this.model);
    };
    ParentChildDelegate.prototype.moveToBack = function () {
        var parent = this.model.getParent();
        if ( true && !parent)
            throw new debugError_DebugError("can not move to back: object is detached");
        var parentArray = parent.children;
        var index = parentArray.indexOf(this.model);
        if ( true && index === -1)
            throw new debugError_DebugError("can not move to front: object is not belong to current scene");
        parentArray.splice(index, 1);
        parentArray.unshift(this.model);
    };
    ParentChildDelegate.prototype.findChildById = function (id) {
        if (true) {
            if (!id)
                throw new debugError_DebugError("illegal argument");
        }
        if (id === this.model.id)
            return this.model;
        for (var _i = 0, _a = this.model.children; _i < _a.length; _i++) {
            var c = _a[_i];
            var possibleObject = c.findChildById(id);
            if (possibleObject)
                return possibleObject;
        }
        return undefined;
    };
    return ParentChildDelegate;
}());


// CONCATENATED MODULE: ./engine/scene/layer.ts

var LayerTransformType;
(function (LayerTransformType) {
    LayerTransformType[LayerTransformType["TRANSFORM"] = 0] = "TRANSFORM";
    LayerTransformType[LayerTransformType["STICK_TO_CAMERA"] = 1] = "STICK_TO_CAMERA";
})(LayerTransformType || (LayerTransformType = {}));
var layer_Layer = (function () {
    function Layer(game) {
        var _this = this;
        this.game = game;
        this.type = 'Layer';
        this.transformType = LayerTransformType.TRANSFORM;
        this.children = [];
        this._parentChildDelegate = new parentChildDelegate_ParentChildDelegate(this);
        this._parentChildDelegate.afterChildAppended = function (c) {
            var m = c;
            m.setLayer(_this);
            m.setScene(_this._scene);
            c.parent = undefined;
            m.revalidate();
        };
    }
    Layer.prototype.appendChild = function (newChild) {
        this._parentChildDelegate.appendChild(newChild);
    };
    Layer.prototype.appendChildAt = function (newChild, index) {
        this._parentChildDelegate.appendChildAt(newChild, index);
    };
    Layer.prototype.appendChildAfter = function (modelAfter, newChild) {
        this._parentChildDelegate.appendChildAfter(modelAfter, newChild);
    };
    Layer.prototype.appendChildBefore = function (modelBefore, newChild) {
        this._parentChildDelegate.appendChildBefore(modelBefore, newChild);
    };
    Layer.prototype.prependChild = function (newChild) {
        this._parentChildDelegate.prependChild(newChild);
    };
    Layer.prototype.removeChildAt = function (i) {
        this._parentChildDelegate.removeChildAt(i);
    };
    Layer.prototype.removeChild = function (c) {
        this._parentChildDelegate.removeChild(c);
    };
    Layer.prototype.replaceChild = function (c, newChild) {
        this._parentChildDelegate.replaceChild(c, newChild);
    };
    Layer.prototype.removeSelf = function () {
        this._parentChildDelegate.removeSelf();
    };
    Layer.prototype.removeChildren = function () {
        this._parentChildDelegate.removeChildren();
    };
    Layer.prototype.moveToFront = function () {
        this._parentChildDelegate.moveToFront();
    };
    Layer.prototype.moveToBack = function () {
        this._parentChildDelegate.moveToBack();
    };
    Layer.prototype.findChildById = function (id) {
        return this._parentChildDelegate.findChildById(id);
    };
    Layer.prototype.getParent = function () {
        return this._scene;
    };
    Layer.prototype.getParentNode = function () {
        return this.parent;
    };
    Layer.prototype.getChildAt = function (index) {
        return this.children[index];
    };
    Layer.prototype.getChildren = function () {
        return this.children;
    };
    Layer.prototype.setScene = function (scene) {
        this._scene = scene;
    };
    Layer.prototype.update = function () {
        var all = this.children;
        for (var _i = 0, all_1 = all; _i < all_1.length; _i++) {
            var obj = all_1[_i];
            obj.update();
        }
    };
    Layer.prototype.render = function () {
        for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
            var obj = _a[_i];
            obj.render();
        }
    };
    return Layer;
}());


// CONCATENATED MODULE: ./engine/renderer/camera.ts





var camera_Mat16Holder = mat4_mat4.Mat16Holder;

var DIRECTION_CORRECTION;
(function (DIRECTION_CORRECTION) {
    DIRECTION_CORRECTION[DIRECTION_CORRECTION["RIGHT"] = 0] = "RIGHT";
    DIRECTION_CORRECTION[DIRECTION_CORRECTION["LEFT"] = 1] = "LEFT";
    DIRECTION_CORRECTION[DIRECTION_CORRECTION["UP"] = 2] = "UP";
    DIRECTION_CORRECTION[DIRECTION_CORRECTION["DOWN"] = 3] = "DOWN";
})(DIRECTION_CORRECTION || (DIRECTION_CORRECTION = {}));
var camera_Camera = (function () {
    function Camera(game) {
        var _this = this;
        this.game = game;
        this.pos = new point2d_Point2d(0, 0);
        this.posZ = 0;
        this.scale = new point2d_Point2d(1, 1);
        this.worldTransformDirty = true;
        this.worldTransformMatrix = new camera_Mat16Holder();
        this._rect = new rect_Rect();
        this._cameraPosCorrection = {
            current: new point2d_Point2d(),
            max: new point2d_Point2d()
        };
        var observer = function () { return _this.worldTransformDirty = true; };
        this.pos.observe(observer);
        this.scale.observe(observer);
        this._rect.observe(observer);
    }
    Camera.prototype.revalidate = function () {
        this._rect.setSize(this.game.size);
        this.worldTransformDirty = true;
    };
    Camera.prototype.followTo = function (gameObject) {
        if (gameObject === undefined) {
            this._objFollowTo = undefined;
            return;
        }
        this._objFollowTo = gameObject;
        this._objFollowToPrevPos = new point2d_Point2d();
        this._objFollowToPrevPos.set(this._objFollowTo.pos);
        this.revalidate();
    };
    Camera.prototype.update = function () {
        var gameObject = this._objFollowTo;
        if (gameObject !== undefined) {
            if ((gameObject.pos.x - this._objFollowToPrevPos.x) > 0)
                this._directionCorrection = DIRECTION_CORRECTION.RIGHT;
            else if ((gameObject.pos.x - this._objFollowToPrevPos.x) < 0)
                this._directionCorrection = DIRECTION_CORRECTION.LEFT;
            if ((gameObject.pos.y - this._objFollowToPrevPos.y) > 0)
                this._directionCorrection = DIRECTION_CORRECTION.DOWN;
            else if ((gameObject.pos.y - this._objFollowToPrevPos.y) < 0)
                this._directionCorrection = DIRECTION_CORRECTION.UP;
            this._objFollowToPrevPos.set(gameObject.pos);
            var _a = this.getRect(), width = _a.width, height = _a.height;
            if (this._directionCorrection === DIRECTION_CORRECTION.RIGHT)
                this._cameraPosCorrection.max.x = width / 3;
            else if (this._directionCorrection === DIRECTION_CORRECTION.LEFT)
                this._cameraPosCorrection.max.x = -width / 3;
            else if (this._directionCorrection === DIRECTION_CORRECTION.DOWN)
                this._cameraPosCorrection.max.y = height / 3;
            else if (this._directionCorrection === DIRECTION_CORRECTION.UP)
                this._cameraPosCorrection.max.y = -height / 3;
            var currCorrection = this._cameraPosCorrection.max.
                substract(this._cameraPosCorrection.current).
                multiply(0.05);
            this._cameraPosCorrection.current.add(currCorrection);
            var newPos = point2d_Point2d.fromPool();
            var pointToFollow = point2d_Point2d.fromPool();
            var scene = this.game.getCurrScene();
            var w = this.game.size.width;
            var h = this.game.size.height;
            var wDiv2 = w / 2;
            var hDiv2 = h / 2;
            pointToFollow.set(gameObject.pos);
            pointToFollow.addXY(-wDiv2, -hDiv2);
            newPos.x = this.pos.x + (pointToFollow.x + this._cameraPosCorrection.current.x - this.pos.x) * Camera.FOLLOW_FACTOR.x;
            newPos.y = this.pos.y + (pointToFollow.y + this._cameraPosCorrection.current.y - this.pos.y) * Camera.FOLLOW_FACTOR.y;
            if (newPos.x < 0) {
                newPos.x = 0;
            }
            if (newPos.y < 0) {
                newPos.y = 0;
            }
            if (newPos.x > scene.size.width - w) {
                newPos.x = scene.size.width - w;
            }
            if (newPos.y > scene.size.height - h) {
                newPos.y = scene.size.height - h;
            }
            this.pos.set(newPos);
            newPos.release();
            pointToFollow.release();
        }
        if (this._cameraShakeTween !== undefined)
            this._cameraShakeTween.update();
    };
    Camera.prototype.shake = function (amplitude, time) {
        var _this = this;
        var tweenTarget = { time: 0, point: new point2d_Point2d(0, 0) };
        this._cameraShakeTween = new tween_Tween({
            target: tweenTarget,
            time: time,
            to: { time: time },
            progress: function () {
                var r1 = mathEx_MathEx.random(-amplitude / 2, amplitude / 2);
                var r2 = mathEx_MathEx.random(-amplitude / 2, amplitude / 2);
                tweenTarget.point.setXY(r1, r2);
            },
            complete: function () { return _this._cameraShakeTween = undefined; }
        });
    };
    Camera.prototype.translate = function () {
        var renderer = this.game.getRenderer();
        renderer.transformTranslate(-this.pos.x, -this.pos.y, 0);
    };
    Camera.prototype.transform = function () {
        var renderer = this.game.getRenderer();
        if (!this.scale.equal(1)) {
            renderer.transformTranslate(this.game.size.width / 2, this.game.size.height / 2, 0);
            renderer.transformScale(this.scale.x, this.scale.y);
            renderer.transformTranslate(-this.game.size.width / 2, -this.game.size.height / 2);
        }
        if (this._cameraShakeTween !== undefined)
            renderer.transformTranslate(this._cameraShakeTween.getTarget().point.x, this._cameraShakeTween.getTarget().point.y);
    };
    Camera.prototype.screenToWorld = function (p, transformType) {
        var mScale = camera_Mat16Holder.fromPool();
        var scaleX = transformType === LayerTransformType.TRANSFORM ? this.scale.x : 1;
        var scaleY = transformType === LayerTransformType.TRANSFORM ? this.scale.y : 1;
        var posX = transformType === LayerTransformType.TRANSFORM ? this.pos.x : 0;
        var posY = transformType === LayerTransformType.TRANSFORM ? this.pos.y : 0;
        mat4_mat4.makeScale(mScale, scaleX, scaleY, 1);
        var point2d = mathEx_MathEx.unProject(p, this.game.size.width, this.game.size.height, mScale);
        point2d.addXY(posX / scaleX, posY / scaleY);
        mScale.release();
        return point2d;
    };
    Camera.prototype.getRect = function () {
        this._rect.setXY(this.pos.x, this.pos.y);
        return this._rect;
    };
    Camera.FOLLOW_FACTOR = new point2d_Point2d(0.1, 0.1);
    return Camera;
}());


// CONCATENATED MODULE: ./engine/renderer/common/color.ts



var color_Color = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Color, _super);
    function Color(r, g, b, a) {
        if (r === void 0) { r = 0; }
        if (g === void 0) { g = r; }
        if (b === void 0) { b = g; }
        if (a === void 0) { a = 255; }
        var _this = _super.call(this) || this;
        _this.type = 'Color';
        _this._friezed = false;
        _this.setRGBA(r, g, b, a);
        return _this;
    }
    Color.RGB = function (r, g, b) {
        if (g === void 0) { g = r; }
        if (b === void 0) { b = r; }
        return Color.RGBA(r, g, b, 255);
    };
    Color.HSLA = function (h, s, l, a) {
        var c = new Color();
        c.setHSLA(h, s, l, a);
        return c;
    };
    Color.HSL = function (h, s, l) {
        return Color.HSLA(h, s, l, 255);
    };
    Color.HSV = function (h, s, v) {
        var c = new Color();
        c.setHSV(h, s, v);
        return c;
    };
    Color.RGBA = function (r, g, b, a) {
        if (g === void 0) { g = r; }
        if (b === void 0) { b = g; }
        if (a === void 0) { a = 255; }
        return new Color(r, g, b, a);
    };
    Color.from = function (col) {
        return new Color(col.r, col.g, col.b, col.a);
    };
    Color.fromRGBNumeric = function (col) {
        var r = (col & 16711680) >> (4 * 4);
        var g = (col & 65280) >> (4 * 2);
        var b = (col & 255);
        return new Color(r, g, b);
    };
    Color.fromCssLiteral = function (literal) {
        var _c, _d;
        var r = 0, g = 0, b = 0, a = 0;
        if (literal.substr(0, 1) === "#") {
            var numericPart = literal.substr(1);
            if (numericPart.length === 3) {
                r = ~~(parseInt(numericPart.substr(0, 1), 16) * 0xFF / 0xF);
                g = ~~(parseInt(numericPart.substr(1, 1), 16) * 0xFF / 0xF);
                b = ~~(parseInt(numericPart.substr(2, 1), 16) * 0xFF / 0xF);
                a = 255;
            }
            else if (numericPart.length === 6) {
                r = ~~(parseInt(numericPart.substr(0, 2), 16));
                g = ~~(parseInt(numericPart.substr(2, 2), 16));
                b = ~~(parseInt(numericPart.substr(4, 2), 16));
                a = 255;
            }
            else if (numericPart.length === 8) {
                r = ~~(parseInt(numericPart.substr(0, 2), 16));
                g = ~~(parseInt(numericPart.substr(2, 2), 16));
                b = ~~(parseInt(numericPart.substr(4, 2), 16));
                a = ~~(parseInt(numericPart.substr(6, 2), 16));
            }
            else {
                if (true)
                    throw new debugError_DebugError("unsupported or wrong color literal: " + literal);
            }
        }
        else {
            if (literal.indexOf('rgb') === 0) {
                _c = literal.split("(")[1].split(")")[0].split(",").map(function (x) { return +x; }), r = _c[0], g = _c[1], b = _c[2], a = _c[3];
                if (a === undefined)
                    a = 255;
                else
                    a = ~~(a * 255);
            }
            else if (literal.indexOf('hsl') === 0) {
                var h = void 0, s = void 0, l = void 0, alfa = void 0;
                _d = literal.split("(")[1].split(")")[0].split(",").map(function (x) { return parseInt(x); }), h = _d[0], s = _d[1], l = _d[2], alfa = _d[3];
                if (alfa === undefined)
                    alfa = 255;
                else
                    alfa = ~~(alfa * 255);
                return Color.HSLA(h, s, l, alfa);
            }
            else {
                if (true)
                    throw new debugError_DebugError("unsupported or wrong color literal: " + literal);
            }
        }
        return Color.RGBA(r, g, b, a);
    };
    Color.prototype.setRGBA = function (r, g, b, a) {
        if (a === void 0) { a = 255; }
        this.checkFriezed();
        var changed = this._r !== r || this._g !== g || this._b !== b || this._a !== a;
        if (!changed)
            return;
        this._r = r;
        this._g = g;
        this._b = b;
        this._a = a;
        this.triggerObservable();
        this.normalizeToZeroOne();
    };
    Color.prototype.setRGB = function (r, g, b) {
        if (g === void 0) { g = r; }
        if (b === void 0) { b = g; }
        this.setRGBA(r, g, b, 255);
    };
    Color.prototype.setHSLA = function (h, s, l, a) {
        h = (h % 360) / 360;
        s /= 100;
        l /= 100;
        var r, g, b;
        if (s === 0) {
            r = g = b = l;
        }
        else {
            var hue2rgb = function (pCol, qCol, t) {
                if (t < 0)
                    t += 1;
                if (t > 1)
                    t -= 1;
                if (t < 1 / 6)
                    return pCol + (qCol - pCol) * 6 * t;
                if (t < 1 / 2)
                    return qCol;
                if (t < 2 / 3)
                    return pCol + (qCol - pCol) * (2 / 3 - t) * 6;
                return pCol;
            };
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }
        var rResult = Math.round(r * 255);
        var gResult = Math.round(g * 255);
        var bResult = Math.round(b * 255);
        this.setRGBA(rResult, gResult, bResult, a);
    };
    Color.prototype.setHSV = function (h, s, v) {
        h /= 100;
        s /= 100;
        v /= 100;
        var r = 0, g = 0, b = 0;
        var i = Math.floor(h * 6);
        var f = h * 6 - i;
        var p = v * (1 - s);
        var q = v * (1 - f * s);
        var t = v * (1 - (1 - f) * s);
        switch (i % 6) {
            case 0: {
                r = v;
                g = t;
                b = p;
                break;
            }
            case 1: {
                r = q;
                g = v;
                b = p;
                break;
            }
            case 2: {
                r = p;
                g = v;
                b = t;
                break;
            }
            case 3: {
                r = p;
                g = q;
                b = v;
                break;
            }
            case 4: {
                r = t;
                g = p;
                b = v;
                break;
            }
            case 5: {
                r = v;
                g = p;
                b = q;
                break;
            }
        }
        this.setRGB(~~(r * 255), ~~(b * 255), ~~(b * 255));
    };
    Color.prototype.setHSL = function (h, s, l) {
        this.setHSLA(h, s, l, 255);
    };
    Object.defineProperty(Color.prototype, "r", {
        get: function () {
            return this._r;
        },
        set: function (value) {
            this.setRGBA(value, this._g, this._b, this._a);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Color.prototype, "g", {
        get: function () {
            return this._g;
        },
        set: function (value) {
            this.setRGBA(this._r, value, this._b, this._a);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Color.prototype, "b", {
        get: function () {
            return this._b;
        },
        set: function (value) {
            this.setRGBA(this._r, this._g, value, this._a);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Color.prototype, "a", {
        get: function () {
            return this._a;
        },
        set: function (value) {
            this.setRGBA(this._r, this._g, this._b, value);
        },
        enumerable: false,
        configurable: true
    });
    Color.prototype.set = function (another) {
        this.setRGBA(another.r, another.g, another.b, another.a);
    };
    Color.prototype.clone = function () {
        return new Color(this._r, this._g, this._b, this._a);
    };
    Color.prototype.freeze = function () {
        this._friezed = true;
        return this;
    };
    Color.prototype.asGL = function () {
        if (!this._arr)
            this._arr = [0, 0, 0, 0];
        this._arr[0] = this.rNorm;
        this._arr[1] = this.gNorm;
        this._arr[2] = this.bNorm;
        this._arr[3] = this.aNorm;
        return this._arr;
    };
    Color.prototype.asCSS = function () {
        return "rgba(" + this._r + "," + this._g + "," + this._b + "," + this._a / 255 + ")";
    };
    Color.prototype.asRGBNumeric = function () {
        return (this._r << 16) | (this._g << 8) | this._b;
    };
    Color.prototype.toJSON = function () {
        return { r: this._r, g: this._g, b: this._b, a: this._a };
    };
    Color.prototype.fromJSON = function (json) {
        this.setRGBA(json.r, json.g, json.b, json.a);
    };
    Color.prototype.checkFriezed = function () {
        if (this._friezed) {
            if (true) {
                console.error(this);
                throw new debugError_DebugError("the color is friezed and can no be changed");
            }
            else
                {}
        }
    };
    Color.prototype.normalizeToZeroOne = function () {
        this.rNorm = this._r / 0xff;
        this.gNorm = this._g / 0xff;
        this.bNorm = this._b / 0xff;
        this.aNorm = this._a / 0xff;
    };
    Color.WHITE = Color.RGB(255, 255, 255).freeze();
    Color.GREY = Color.RGB(127, 127, 127).freeze();
    Color.BLACK = Color.RGB(0, 0, 0).freeze();
    Color.NONE = Color.RGBA(0, 0, 0, 0).freeze();
    return Color;
}(observableEntity_ObservableEntity));


// CONCATENATED MODULE: ./engine/resources/resourceLink.ts
var ResourceLinkState;
(function (ResourceLinkState) {
    ResourceLinkState["CREATED"] = "CREATED";
    ResourceLinkState["PENDING"] = "PENDING";
    ResourceLinkState["COMPLETED"] = "COMPLETED";
    ResourceLinkState["PENDING_ERROR"] = "PENDING_ERROR";
})(ResourceLinkState || (ResourceLinkState = {}));
var ResourceLink = (function () {
    function ResourceLink(url) {
        this.url = url;
        this.state = ResourceLinkState.CREATED;
    }
    ResourceLink.create = function (target) {
        var url = 'url' + Math.random() + '_' + Math.random();
        var link = new ResourceLink(url);
        link.setTarget(target);
        return link;
    };
    ResourceLink.prototype.getUrl = function () {
        return this.url;
    };
    ResourceLink.prototype.setTarget = function (t) {
        this._target = t;
        this.state = ResourceLinkState.COMPLETED;
    };
    ResourceLink.prototype.getTarget = function () {
        return this._target;
    };
    return ResourceLink;
}());


// CONCATENATED MODULE: ./engine/resources/incrementer.ts
var incrementer_val = 0;
var Incrementer = (function () {
    function Incrementer() {
    }
    Incrementer.getValue = function () {
        return incrementer_val++;
    };
    return Incrementer;
}());


// CONCATENATED MODULE: ./engine/resources/queue.ts


var queue_TaskRef = (function () {
    function TaskRef() {
        this.id = Incrementer.getValue();
    }
    return TaskRef;
}());

var queue_Queue = (function () {
    function Queue() {
        this._tasksResolved = 0;
        this._tasks = [];
        this._tasksProgressById = {};
        this._completed = false;
        this._nextTaskIndex = 0;
        this._currProgress = 0;
    }
    Queue.prototype.progressTask = function (taskRef, progress) {
        if (progress === 1)
            return;
        var taskId = taskRef.id;
        this._tasksProgressById[taskId] = progress;
        if (this.onProgress)
            this.onProgress(this.calcProgress());
    };
    Queue.prototype.resolveTask = function (taskRef) {
        var taskId = taskRef.id;
        if (true) {
            if (this._tasksProgressById[taskId] === undefined)
                throw new debugError_DebugError("can not resolve task: no task with id " + taskId);
            if (this._tasksProgressById[taskId] === 1)
                throw new debugError_DebugError("task with id " + taskId + " resolved already");
        }
        this._tasksResolved++;
        this._tasksProgressById[taskId] = 1;
        if (this._tasks.length === this._tasksResolved) {
            if (this.onProgress)
                this.onProgress(1);
            this._completed = true;
            if (this.onResolved)
                this.onResolved();
        }
        else {
            if (this.onProgress)
                this.onProgress(this.calcProgress());
            this._tasks[this._nextTaskIndex++]();
        }
    };
    Queue.prototype.addTask = function (taskFn) {
        var taskRef = new queue_TaskRef();
        this._tasks.push(taskFn);
        this._tasksProgressById[taskRef.id] = 0;
        return taskRef;
    };
    Queue.prototype.isCompleted = function () {
        return this._completed;
    };
    Queue.prototype.calcProgress = function () {
        var _this = this;
        var sum = 0;
        Object.keys(this._tasksProgressById).forEach(function (taskId) {
            sum += _this._tasksProgressById[taskId] || 0;
        });
        var progress = sum / this._tasks.length;
        if (progress > this._currProgress)
            this._currProgress = progress;
        return this._currProgress;
    };
    Queue.prototype.completeForced = function () {
        this._completed = true;
        if (this.onResolved !== undefined)
            this.onResolved();
    };
    Queue.prototype.start = function () {
        if (this.size() === 0) {
            this._completed = true;
            if (this.onResolved)
                this.onResolved();
        }
        else {
            this._tasks[this._nextTaskIndex++]();
        }
    };
    Queue.prototype.size = function () {
        return this._tasks.length;
    };
    return Queue;
}());


// CONCATENATED MODULE: ./engine/resources/urlLoader.ts

var addUrlParameter = function (url, param, value) {
    if (url.indexOf('?') > -1)
        url += '&';
    else
        url += '?';
    return "" + url + param + "=" + value;
};
var loadBase64 = function (urlRequest) {
    return Promise.resolve(urlRequest.url);
};
var loadViaXmlHttp = function (urlRequest, onProgress) {
    if (!urlRequest.method)
        urlRequest.method = 'GET';
    var xhr = new XMLHttpRequest();
    xhr.open(urlRequest.method, addUrlParameter(urlRequest.url, 'modified', 1603311205338), true);
    xhr.responseType = urlRequest.responseType;
    if (xhr.responseType === 'blob') {
        xhr.setRequestHeader('Accept-Ranges', 'bytes');
        xhr.setRequestHeader('Content-Range', 'bytes');
    }
    if (urlRequest.headers) {
        for (var _i = 0, _a = urlRequest.headers; _i < _a.length; _i++) {
            var header = _a[_i];
            xhr.setRequestHeader(header.name, header.value);
        }
    }
    return new Promise(function (resolve, reject) {
        xhr.onload = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(xhr.response);
                }
                else {
                    var message =  true ? "can not load resource with url '" + urlRequest.url + "', status " + xhr.status : undefined;
                    reject(message);
                }
            }
        };
        if (onProgress) {
            xhr.onprogress = function (e) {
                onProgress(e.loaded / e.total);
            };
        }
        xhr.onerror = function (e) {
            console.error(e);
            var rejectError =  true ? "can not load resource with url " + urlRequest.url : undefined;
            reject(rejectError);
        };
        xhr.ontimeout = function (e) {
            console.error(e);
            var rejectError =  true ? "can not load resource with url " + urlRequest.url : undefined;
            reject(rejectError);
        };
        xhr.send();
    });
};
var urlLoader_UrlLoader = (function () {
    function UrlLoader(urlRequest) {
        this.urlRequest = urlRequest;
    }
    UrlLoader.prototype.getUrl = function () {
        return this.urlRequest.url;
    };
    UrlLoader.prototype.load = function () {
        return Object(tslib_es6["b" /* __awaiter */])(this, void 0, Promise, function () {
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                if (this.getUrl().indexOf('data:') === 0)
                    return [2, loadBase64(this.urlRequest)];
                else
                    return [2, loadViaXmlHttp(this.urlRequest, this.onProgress)];
                return [2];
            });
        });
    };
    return UrlLoader;
}());


// CONCATENATED MODULE: ./engine/resources/resourceUtil.ts


var resourceUtil_ResourceUtil;
(function (ResourceUtil) {
    var _this = this;
    var loadArrayBuffer = function (req, q, taskRef) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, Promise, function () {
        var iReq, loader;
        return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (req.substr !== undefined) {
                        iReq = { url: req, responseType: 'arraybuffer', method: 'GET' };
                    }
                    else
                        iReq = req;
                    loader = new urlLoader_UrlLoader(iReq);
                    loader.onProgress = function (n) { return q.progressTask(taskRef, n); };
                    return [4, loader.load()];
                case 1: return [2, _a.sent()];
            }
        });
    }); };
    var createBitmapFromBlob = function (imgBlob) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, Promise, function () {
        return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
            return [2, globalThis.createImageBitmap(imgBlob)];
        });
    }); };
    var createHTMLImageFromUrl = function (imgUrl) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, Promise, function () {
        var url;
        return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
            url = imgUrl.url ? imgUrl.url : imgUrl;
            return [2, new Promise(function (resolve, reject) {
                    var img = new window.Image();
                    img.src = url;
                    img.onload = function () {
                        resolve(img);
                    };
                    img.onerror = function (e) {
                        console.error(e);
                        var msg =  true ? "can not create image. Bad url data: " + url : undefined;
                        reject(msg);
                    };
                })];
        });
    }); };
    ResourceUtil.createImageFromData = function (imageData, q, taskRef) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, Promise, function () {
        var isBase64, arrayBuffer, arrayBufferView, imgBlob;
        return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    isBase64 = imageData.substr !== undefined && imageData.indexOf('data:image/') === 0;
                    if (!isBase64) return [3, 2];
                    return [4, createHTMLImageFromUrl(imageData)];
                case 1: return [2, _a.sent()];
                case 2:
                    if (!(globalThis.createImageBitmap === undefined)) return [3, 4];
                    return [4, createHTMLImageFromUrl(imageData)];
                case 3: return [2, _a.sent()];
                case 4: return [4, loadArrayBuffer(imageData, q, taskRef)];
                case 5:
                    arrayBuffer = _a.sent();
                    arrayBufferView = new Uint8Array(arrayBuffer);
                    imgBlob = new Blob([arrayBufferView]);
                    return [4, createBitmapFromBlob(imgBlob)];
                case 6: return [2, _a.sent()];
            }
        });
    }); };
})(resourceUtil_ResourceUtil || (resourceUtil_ResourceUtil = {}));

// CONCATENATED MODULE: ./engine/renderable/impl/general/font.ts



var getCtx = function (cnv) {
    return cnv.getContext('2d');
};
var font_FontFactory;
(function (FontFactory) {
    var SYMBOL_PADDING = 4;
    var getFontHeight = function (strFont) {
        var parent = document.createElement("span");
        parent.appendChild(document.createTextNode("height"));
        document.body.appendChild(parent);
        parent.style.cssText = "font: " + strFont + "; white-space: nowrap; display: inline-block;line-height:1em;";
        var height = parent.offsetHeight;
        document.body.removeChild(parent);
        return height;
    };
    FontFactory.getFontContext = function (standartChars, extraChars, strFont, width) {
        var cnv = document.createElement('canvas');
        var ctx = getCtx(cnv);
        ctx.font = strFont;
        var lineHeight = getFontHeight(strFont);
        var rowHeight = lineHeight + 2 * SYMBOL_PADDING;
        var symbols = {};
        var currX = 0, currY = 0, cnvHeight = rowHeight;
        var putCharOnContext = function (char) {
            var context2D = cnv.getContext('2d');
            var textWidth = context2D.measureText(char).width + 2 * SYMBOL_PADDING;
            if (textWidth === 0)
                return;
            if (currX + textWidth > width) {
                currX = 0;
                currY += rowHeight;
                cnvHeight += rowHeight;
            }
            symbols[char] = {
                x: ~~currX,
                y: ~~currY,
                width: ~~textWidth,
                height: rowHeight,
                destOffsetX: 0,
                destOffsetY: 0,
            };
            currX += textWidth;
        };
        standartChars.forEach(function (c) { return putCharOnContext(c); });
        extraChars.forEach(function (c) { return putCharOnContext(c); });
        return {
            symbols: symbols,
            width: width,
            height: cnvHeight,
            padding: [SYMBOL_PADDING, SYMBOL_PADDING, SYMBOL_PADDING, SYMBOL_PADDING],
            spacing: [0, 0],
            lineHeight: lineHeight,
        };
    };
    FontFactory.getFontImageBase64 = function (fontContext, strFont) {
        var cnv = document.createElement('canvas');
        cnv.width = fontContext.width;
        cnv.height = fontContext.height;
        var ctx = getCtx(cnv);
        ctx.font = strFont;
        ctx.textBaseline = 'top';
        ctx.imageSmoothingEnabled = false;
        ctx.mozImageSmoothingEnabled = false;
        ctx.webkitImageSmoothingEnabled = false;
        ctx.msImageSmoothingEnabled = false;
        ctx.oImageSmoothingEnabled = false;
        ctx.fillStyle = 'rgba(0,0,0,0)';
        ctx.fillRect(0, 0, cnv.width, cnv.height);
        ctx.fillStyle = '#fff';
        var symbols = fontContext.symbols;
        Object.keys(symbols).forEach(function (symbol) {
            var rect = symbols[symbol];
            ctx.fillText(symbol, rect.x + SYMBOL_PADDING, rect.y + SYMBOL_PADDING);
        });
        return cnv.toDataURL();
    };
    var querySelector = function (doc, path) {
        var res = doc.querySelector(path);
        if ( true && res === undefined) {
            console.error(doc);
            throw new debugError_DebugError("can not receive node " + path + " from document");
        }
        return res;
    };
    FontFactory.createFontFromAtlas = function (game, resourceLink, doc) {
        var _a = querySelector(doc, 'info').getAttribute('padding').split(',').map(function (it) { return +it; }), up = _a[0], right = _a[1], down = _a[2], left = _a[3];
        var _b = querySelector(doc, 'info').getAttribute('spacing').split(',').map(function (it) { return +it; }), spacingHorizontal = _b[0], spacingVertical = _b[1];
        var lineHeight = +(querySelector(doc, 'common').getAttribute('lineHeight'));
        var context = {
            width: resourceLink.getTarget().size.width,
            height: resourceLink.getTarget().size.height,
            lineHeight: lineHeight,
            padding: [up, right, down, left],
            spacing: [spacingHorizontal, spacingVertical],
            symbols: {}
        };
        var fontFamily = querySelector(doc, 'info').getAttribute('face');
        var fontSize = +querySelector(doc, 'info').getAttribute('size');
        var all = doc.querySelectorAll('char');
        for (var i = 0; i < all.length; i++) {
            var el = all[i];
            var id = +(el.getAttribute('id'));
            var width = +(el.getAttribute('width')) || ~~(lineHeight / 3) || 16;
            var height = +(el.getAttribute('height')) || 0.0001;
            var x = +(el.getAttribute('x'));
            var y = +(el.getAttribute('y'));
            var xOffset = +(el.getAttribute('xoffset')) || 0;
            var yOffset = +(el.getAttribute('yoffset')) || 0;
            var char = String.fromCharCode(id);
            context.symbols[char] = {
                x: x,
                y: y,
                width: width,
                height: height,
                destOffsetX: xOffset,
                destOffsetY: yOffset
            };
        }
        return new font_Font(game, { fontFamily: fontFamily, fontSize: fontSize, resourceLink: resourceLink, context: context });
    };
})(font_FontFactory || (font_FontFactory = {}));
var DEFAULT_FONT_PARAMS = {
    fontFamily: 'monospace',
    fontSize: 12,
    extraChars: [],
};
var LAT_CHARS = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
var STANDART_SYMBOLS = '1234567890 ' +
    '"!`?\'.,;:()[]{}<>|/@\\^$-%+=#_&~*';
var CYR_CHARS = 'АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНн' +
    'ОоПпРрСсТтУуФфХхЦцЧчШшЩщ' +
    'ЫыЬьЪъЭэЮюЯя';
var font_Font = (function () {
    function Font(game, params) {
        if (params === void 0) { params = {}; }
        var _a, _b, _c, _d;
        this.game = game;
        this.type = 'Font';
        this.fontFamily = 'Monospace';
        this.fontFamily = (_a = params.fontFamily) !== null && _a !== void 0 ? _a : DEFAULT_FONT_PARAMS.fontFamily;
        this.fontSize = (_b = params.fontSize) !== null && _b !== void 0 ? _b : DEFAULT_FONT_PARAMS.fontSize;
        this.chars = (_c = params.chars) !== null && _c !== void 0 ? _c : (LAT_CHARS + STANDART_SYMBOLS + CYR_CHARS).split('');
        this.extraChars = (_d = params.extraChars) !== null && _d !== void 0 ? _d : DEFAULT_FONT_PARAMS.extraChars;
        if (params.context === undefined)
            params.context = this.createContext();
        this.fontContext = params.context;
        if (params.resourceLink === undefined) {
            var base64 = this.createBitmap();
            params.resourceLink = this.game.getCurrScene().resourceLoader.loadTexture(base64);
        }
        this.setResourceLink(params.resourceLink);
    }
    Font.createSystemFont = function (game) {
        return Object(tslib_es6["b" /* __awaiter */])(this, void 0, Promise, function () {
            var f, resourceLoader, link, resolveFn, p;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                if (Font._systemFontInstance)
                    return [2, Font._systemFontInstance];
                f = new Font(game);
                f.createContext();
                resourceLoader = new resourceLoader_ResourceLoader(game);
                link = resourceLoader.loadTexture(f.createBitmap());
                f.setResourceLink(link);
                resourceLoader.onCompleted(function () {
                    resolveFn(f);
                    Font._systemFontInstance = f;
                });
                p = new Promise(function (resolve) {
                    resolveFn = resolve;
                });
                resourceLoader.startLoading();
                return [2, p];
            });
        });
    };
    Font.prototype.asCss = function () {
        return this.fontSize + "px " + this.fontFamily;
    };
    Font.prototype.setResourceLink = function (link) {
        this._resourceLink = link;
    };
    Font.prototype.getResourceLink = function () {
        return this._resourceLink;
    };
    Font.prototype.createContext = function () {
        var WIDTH = 512;
        return font_FontFactory.getFontContext(this.chars, this.extraChars, this.asCss(), WIDTH);
    };
    Font.prototype.createBitmap = function () {
        return font_FontFactory.getFontImageBase64(this.fontContext, this.asCss());
    };
    return Font;
}());


// CONCATENATED MODULE: ./engine/resources/resourceLoader.ts







var createImageFromData = resourceUtil_ResourceUtil.createImageFromData;
var createFontFromAtlas = font_FontFactory.createFontFromAtlas;
var resourceCache;
(function (resourceCache) {
    resourceCache.cache = {};
    resourceCache.clear = function () {
        var keys = Object.keys(resourceCache.cache);
        keys.forEach(function (k) { return delete resourceCache.cache[k]; });
    };
})(resourceCache || (resourceCache = {}));
var resourceLoader_ResourceLoader = (function () {
    function ResourceLoader(game) {
        this.game = game;
        this.completed = false;
        this.q = new queue_Queue();
        this.game = game;
    }
    ResourceLoader.createUrlLoader = function (req, responseType) {
        if (responseType === void 0) { responseType = 'text'; }
        var iReq;
        if (req.substr !== undefined) {
            iReq = { url: req, responseType: responseType, method: 'GET' };
        }
        else
            iReq = req;
        return new urlLoader_UrlLoader(iReq);
    };
    ResourceLoader.prototype.loadTexture = function (req) {
        var _this = this;
        var _a, _b;
        this.validateState();
        var link = new ResourceLink(req);
        if (resourceCache.cache[(_a = req.url) !== null && _a !== void 0 ? _a : req] !== undefined) {
            link.setTarget(resourceCache.cache[(_b = req.url) !== null && _b !== void 0 ? _b : req]);
            return link;
        }
        var taskRef = this.q.addTask(function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            var img, texture, e_1;
            var _a;
            return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        link.state = ResourceLinkState.PENDING;
                        return [4, createImageFromData(req, this.q, taskRef)];
                    case 1:
                        img = _b.sent();
                        texture = this.game.getRenderer().createTexture(img);
                        link.setTarget(texture);
                        resourceCache.cache[(_a = req.url) !== null && _a !== void 0 ? _a : req] = texture;
                        this.q.resolveTask(taskRef);
                        return [3, 3];
                    case 2:
                        e_1 = _b.sent();
                        link.state = ResourceLinkState.PENDING_ERROR;
                        console.error(e_1);
                        throw e_1;
                    case 3: return [2];
                }
            });
        }); });
        return link;
    };
    ResourceLoader.prototype.loadCubeTexture = function (leftSide, rightSide, topSide, bottomSide, frontSide, backSide) {
        var _this = this;
        this.validateState();
        var link = new ResourceLink('');
        var taskRef = this.q.addTask(function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            var imgLeft, imgRight, imgTop, imgBottom, imgFront, imgBack, texture, e_2;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        link.state = ResourceLinkState.PENDING;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 8, , 9]);
                        return [4, createImageFromData(leftSide, this.q, taskRef)];
                    case 2:
                        imgLeft = _a.sent();
                        return [4, createImageFromData(rightSide, this.q, taskRefsAdditionals[0])];
                    case 3:
                        imgRight = _a.sent();
                        this.q.resolveTask(taskRefsAdditionals[0]);
                        return [4, createImageFromData(topSide, this.q, taskRefsAdditionals[1])];
                    case 4:
                        imgTop = _a.sent();
                        this.q.resolveTask(taskRefsAdditionals[1]);
                        return [4, createImageFromData(bottomSide, this.q, taskRefsAdditionals[2])];
                    case 5:
                        imgBottom = _a.sent();
                        this.q.resolveTask(taskRefsAdditionals[2]);
                        return [4, createImageFromData(frontSide, this.q, taskRefsAdditionals[3])];
                    case 6:
                        imgFront = _a.sent();
                        this.q.resolveTask(taskRefsAdditionals[3]);
                        return [4, createImageFromData(backSide, this.q, taskRefsAdditionals[4])];
                    case 7:
                        imgBack = _a.sent();
                        this.q.resolveTask(taskRefsAdditionals[4]);
                        texture = this.game.getRenderer().createCubeTexture(imgLeft, imgRight, imgTop, imgBottom, imgFront, imgBack);
                        link.setTarget(texture);
                        this.q.resolveTask(taskRef);
                        return [3, 9];
                    case 8:
                        e_2 = _a.sent();
                        link.state = ResourceLinkState.PENDING_ERROR;
                        throw e_2;
                    case 9: return [2];
                }
            });
        }); });
        var taskRefsAdditionals = new Array(5);
        for (var i = 0; i < taskRefsAdditionals.length; i++) {
            taskRefsAdditionals[i] = (this.q.addTask(function () { }));
        }
        return link;
    };
    ResourceLoader.prototype.loadText = function (req) {
        return this._loadAndProcessText(req, function (t) { return t; });
    };
    ResourceLoader.prototype.loadJSON = function (req) {
        var postPrecessFn = function (t) { return JSON.parse(t); };
        return this._loadAndProcessText(req, postPrecessFn);
    };
    ResourceLoader.prototype.loadSound = function (req) {
        var _this = this;
        this.validateState();
        var loader = ResourceLoader.createUrlLoader(req, 'arraybuffer');
        var link = new ResourceLink(loader.getUrl());
        var taskRef = this.q.addTask(function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            var buff, e_3;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 3, , 4]);
                        link.state = ResourceLinkState.PENDING;
                        return [4, loader.load()];
                    case 1:
                        buff = _a.sent();
                        return [4, this.game.getAudioPlayer().loadSound(buff, link)];
                    case 2:
                        _a.sent();
                        this.q.resolveTask(taskRef);
                        link.setTarget(undefined);
                        return [3, 4];
                    case 3:
                        e_3 = _a.sent();
                        console.error(e_3);
                        throw e_3;
                    case 4: return [2];
                }
            });
        }); });
        loader.onProgress = function (n) { return _this.q.progressTask(taskRef, n); };
        return link;
    };
    ResourceLoader.prototype.loadBinary = function (req) {
        var _this = this;
        this.validateState();
        var loader = ResourceLoader.createUrlLoader(req, 'arraybuffer');
        var link = new ResourceLink(loader.getUrl());
        loader.onProgress = function (n) { return _this.q.progressTask(taskRef, n); };
        var taskRef = this.q.addTask(function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            var buff, e_4;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        link.state = ResourceLinkState.PENDING;
                        return [4, loader.load()];
                    case 1:
                        buff = _a.sent();
                        link.setTarget(buff);
                        this.q.resolveTask(taskRef);
                        return [3, 3];
                    case 2:
                        e_4 = _a.sent();
                        console.error(e_4);
                        throw e_4;
                    case 3: return [2];
                }
            });
        }); });
        return link;
    };
    ResourceLoader.prototype.loadFont = function (params) {
        this.validateState();
        return new font_Font(this.game, params);
    };
    ResourceLoader.prototype.loadFontFromAtlas = function (atlasUrl, doc) {
        var _this = this;
        this.validateState();
        var resourceLink = this.loadTexture(atlasUrl);
        var result = ResourceLink.create(undefined);
        this.addNextTask(function () {
            result.setTarget(createFontFromAtlas(_this.game, resourceLink, doc));
        });
        return result;
    };
    ResourceLoader.prototype.addNextTask = function (task) {
        var _this = this;
        this.validateState();
        var taskRef = this.q.addTask(function () {
            task();
            _this.q.resolveTask(taskRef);
        });
    };
    ResourceLoader.prototype.clearCache = function () {
        resourceCache.clear();
    };
    ResourceLoader.prototype.startLoading = function () {
        this.q.start();
    };
    ResourceLoader.prototype.isCompleted = function () {
        return this.q.isCompleted();
    };
    ResourceLoader.prototype.getProgress = function () {
        return this.q.calcProgress();
    };
    ResourceLoader.prototype.onProgress = function (fn) {
        this.q.onProgress = fn;
    };
    ResourceLoader.prototype.onCompleted = function (fn) {
        var _this = this;
        this.q.onResolved = function () {
            fn();
            _this.completed = true;
        };
    };
    ResourceLoader.prototype._loadAndProcessText = function (req, postProcess) {
        var _this = this;
        this.validateState();
        var url = req.url ? req.url : req;
        var link = new ResourceLink(url);
        var loader = ResourceLoader.createUrlLoader(req);
        loader.onProgress = function (n) { return _this.q.progressTask(taskRef, n); };
        var taskRef = this.q.addTask(function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            var text, data, e_5;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4, loader.load()];
                    case 1:
                        text = _a.sent();
                        data = postProcess(text);
                        link.setTarget(data);
                        this.q.resolveTask(taskRef);
                        return [3, 3];
                    case 2:
                        e_5 = _a.sent();
                        console.error(e_5);
                        throw e_5;
                    case 3: return [2];
                }
            });
        }); });
        return link;
    };
    ResourceLoader.prototype.validateState = function () {
        if (this.completed) {
            if (true)
                throw new debugError_DebugError("resourceLoader is already completed, use another one");
            else
                {}
        }
    };
    return ResourceLoader;
}());


// CONCATENATED MODULE: ./engine/delegates/tweenableDelegate.ts

var tweenableDelegate_TweenableDelegate = (function () {
    function TweenableDelegate() {
        this._tweens = [];
        this._tweenMovies = [];
    }
    TweenableDelegate.prototype.tween = function (desc) {
        var t = new tween_Tween(desc);
        if (!this._tweens)
            this._tweens = [];
        this._tweens.push(t);
        return t;
    };
    TweenableDelegate.prototype.addTween = function (t) {
        if (!this._tweens)
            this._tweens = [];
        this._tweens.push(t);
    };
    TweenableDelegate.prototype.addTweenMovie = function (tm) {
        if (!this._tweenMovies)
            this._tweenMovies = [];
        this._tweenMovies.push(tm);
    };
    TweenableDelegate.prototype.update = function () {
        for (var i = 0, l = this._tweens.length; i < l; i++) {
            var t = this._tweens[i];
            t.update();
            if (t.isCompleted()) {
                this._tweens.splice(i, 1);
                l--;
            }
        }
        for (var i = 0, l = this._tweenMovies.length; i < l; i++) {
            var t = this._tweenMovies[i];
            t.update();
            if (t.isCompleted()) {
                this._tweenMovies.splice(i, 1);
                l--;
            }
        }
    };
    return TweenableDelegate;
}());


// CONCATENATED MODULE: ./engine/misc/timer.ts


var timer_Timer = (function () {
    function Timer(parent, callback, interval, once) {
        this.parent = parent;
        this.once = once;
        this._lastTime = 0;
        this._interval = interval;
        this._callback = callback;
    }
    Timer.prototype.onUpdate = function () {
        var time = game_Game.getInstance().getCurrentTime();
        if (!this._lastTime)
            this._lastTime = time;
        var delta = time - this._lastTime;
        if (delta !== 0 && delta > this._interval) {
            this._lastTime = time;
            this._callback();
            if (this.once)
                this.kill();
        }
    };
    Timer.prototype.kill = function () {
        var _this = this;
        Object(object["i" /* removeFromArray */])(this.parent.getTimers(), function (it) { return it === _this; });
    };
    return Timer;
}());


// CONCATENATED MODULE: ./engine/delegates/timerDelegate.ts

var timerDelegate_TimerDelegate = (function () {
    function TimerDelegate() {
    }
    TimerDelegate.prototype.setInterval = function (callback, interval) {
        return this._addTimer(callback, interval, false);
    };
    TimerDelegate.prototype.setTimeout = function (callback, interval) {
        return this._addTimer(callback, interval, true);
    };
    TimerDelegate.prototype.getTimers = function () {
        return this._timers;
    };
    TimerDelegate.prototype.update = function () {
        if (!this._timers)
            return;
        for (var _i = 0, _a = this._timers; _i < _a.length; _i++) {
            var t = _a[_i];
            t.onUpdate();
        }
    };
    TimerDelegate.prototype._addTimer = function (callback, interval, once) {
        var t = new timer_Timer(this, callback, interval, once);
        if (!this._timers)
            this._timers = [];
        this._timers.push(t);
        return t;
    };
    return TimerDelegate;
}());


// CONCATENATED MODULE: ./engine/control/mouse/mouseEvents.ts
var MOUSE_EVENTS;
(function (MOUSE_EVENTS) {
    MOUSE_EVENTS["click"] = "click";
    MOUSE_EVENTS["mousePressed"] = "mousePressed";
    MOUSE_EVENTS["mouseDown"] = "mouseDown";
    MOUSE_EVENTS["mouseMove"] = "mouseMove";
    MOUSE_EVENTS["mouseLeave"] = "mouseLeave";
    MOUSE_EVENTS["mouseEnter"] = "mouseEnter";
    MOUSE_EVENTS["mouseUp"] = "mouseUp";
    MOUSE_EVENTS["doubleClick"] = "doubleClick";
    MOUSE_EVENTS["scroll"] = "scroll";
    MOUSE_EVENTS["dragStart"] = "dragStart";
    MOUSE_EVENTS["dragMove"] = "dragMove";
    MOUSE_EVENTS["dragStop"] = "dragStop";
})(MOUSE_EVENTS || (MOUSE_EVENTS = {}));

// CONCATENATED MODULE: ./engine/misc/eventEmitter.ts

var eventEmitter_EventEmitter = (function () {
    function EventEmitter() {
        this._events = {};
    }
    EventEmitter.prototype.on = function (eventNameOrList, callBack) {
        var _this = this;
        if (typeof eventNameOrList === 'string') {
            this._on(eventNameOrList, callBack);
        }
        else if (eventNameOrList.splice !== undefined) {
            eventNameOrList.forEach(function (eventName) {
                _this._on(eventName, callBack);
            });
        }
    };
    EventEmitter.prototype.off = function (eventName, callback) {
        if (callback === undefined) {
            if (this._events[eventName] !== undefined)
                this._events[eventName].length = 0;
        }
        else {
            var es = this._events[eventName];
            if (!es)
                return;
            var index = es.indexOf(callback);
            if ( true && index === -1) {
                console.error(callback);
                throw new debugError_DebugError("can not remove event listener " + eventName + ", it does not belong to this eventEmitter");
            }
            es.splice(index, 1);
        }
    };
    EventEmitter.prototype.trigger = function (eventName, data) {
        var evnts = this._events[eventName];
        if (!evnts)
            return;
        for (var i = 0; i < evnts.length; i++) {
            evnts[i](data);
        }
    };
    EventEmitter.prototype._on = function (name, callBack) {
        this._events[name] = this._events[name] || [];
        this._events[name].push(callBack);
    };
    return EventEmitter;
}());


// CONCATENATED MODULE: ./engine/control/abstract/abstractKeypad.ts



var KEY_STATE;
(function (KEY_STATE) {
    KEY_STATE[KEY_STATE["KEY_JUST_PRESSED"] = 2] = "KEY_JUST_PRESSED";
    KEY_STATE[KEY_STATE["KEY_PRESSED"] = 1] = "KEY_PRESSED";
    KEY_STATE[KEY_STATE["KEY_JUST_RELEASED"] = 0] = "KEY_JUST_RELEASED";
    KEY_STATE[KEY_STATE["KEY_RELEASED"] = -1] = "KEY_RELEASED";
})(KEY_STATE || (KEY_STATE = {}));
var abstractKeypad_KeyPadEvent = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(KeyPadEvent, _super);
    function KeyPadEvent() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return KeyPadEvent;
}(observableEntity_ObservableEntity));

var abstractKeypad_AbstractKeypad = (function () {
    function AbstractKeypad(game) {
        this.buffer = [];
        this.game = game;
    }
    AbstractKeypad.prototype.press = function (event) {
        event.keyState = KEY_STATE.KEY_PRESSED;
        this.buffer.push(event);
        this.notify(this.keyPressed, event);
    };
    AbstractKeypad.prototype.release = function (event) {
        event.keyState = KEY_STATE.KEY_JUST_RELEASED;
        this.notify(this.keyReleased, event);
    };
    AbstractKeypad.prototype.update = function () {
        for (var _i = 0, _a = this.buffer; _i < _a.length; _i++) {
            var event = _a[_i];
            if (!event.isCaptured())
                continue;
            var keyVal = event.keyState;
            switch (keyVal) {
                case KEY_STATE.KEY_RELEASED:
                    this.buffer.splice(this.buffer.indexOf(event), 1);
                    event.release();
                    break;
                case KEY_STATE.KEY_JUST_RELEASED:
                    event.keyState = KEY_STATE.KEY_RELEASED;
                    break;
                case KEY_STATE.KEY_JUST_PRESSED:
                    event.keyState = KEY_STATE.KEY_PRESSED;
                    break;
                case KEY_STATE.KEY_PRESSED:
                    this.notify(this.keyHold, event);
                    break;
                default:
                    if (true)
                        throw new debugError_DebugError("unknown button state: " + keyVal);
                    break;
            }
        }
    };
    AbstractKeypad.prototype.notify = function (eventName, e) {
        this.game.getCurrScene().trigger(eventName, e);
    };
    return AbstractKeypad;
}());


// CONCATENATED MODULE: ./engine/control/gamepad/gamePadEvents.ts



var GAME_PAD_EVENTS;
(function (GAME_PAD_EVENTS) {
    GAME_PAD_EVENTS["buttonPressed"] = "buttonPressed";
    GAME_PAD_EVENTS["buttonReleased"] = "buttonReleased";
    GAME_PAD_EVENTS["buttonHold"] = "buttonHold";
})(GAME_PAD_EVENTS || (GAME_PAD_EVENTS = {}));
var gamePadEvents_GamePadEvent = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(GamePadEvent, _super);
    function GamePadEvent() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    GamePadEvent.fromPool = function () {
        return GamePadEvent.pool.getFreeObject(true);
    };
    GamePadEvent.pool = new objectPool_ObjectPool(GamePadEvent);
    return GamePadEvent;
}(abstractKeypad_KeyPadEvent));


// CONCATENATED MODULE: ./engine/control/keyboard/keyboardEvents.ts



var KEYBOARD_EVENTS;
(function (KEYBOARD_EVENTS) {
    KEYBOARD_EVENTS["keyPressed"] = "keyPressed";
    KEYBOARD_EVENTS["keyReleased"] = "keyReleased";
    KEYBOARD_EVENTS["keyHold"] = "keyHold";
})(KEYBOARD_EVENTS || (KEYBOARD_EVENTS = {}));
var keyboardEvents_KeyBoardEvent = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(KeyBoardEvent, _super);
    function KeyBoardEvent() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    KeyBoardEvent.fromPool = function () {
        return KeyBoardEvent._pool.getFreeObject();
    };
    KeyBoardEvent._pool = new objectPool_ObjectPool(KeyBoardEvent);
    return KeyBoardEvent;
}(abstractKeypad_KeyPadEvent));


// CONCATENATED MODULE: ./engine/delegates/eventEmitterDelegate.ts






var getControlErrorMessage = function (controlName, controlClassName) {
    if (false)
        {}
    return "can not listen " + controlName + " events: " + controlName + " control is not added;\ninvoke \"game.addControl(" + controlClassName + ");\"";
};
var eventEmitterDelegate_EventEmitterDelegate = (function () {
    function EventEmitterDelegate() {
    }
    EventEmitterDelegate.prototype.on = function (eventName, callBack) {
        if ( true && eventName in MOUSE_EVENTS) {
            if (!game_Game.getInstance().hasControl('MouseControl'))
                throw new debugError_DebugError(getControlErrorMessage('mouse', 'MouseControl'));
        }
        if ( true && eventName in GAME_PAD_EVENTS) {
            if (!game_Game.getInstance().hasControl('GamePadControl'))
                throw new debugError_DebugError(getControlErrorMessage('gamepad', 'GamePadControl'));
        }
        if ( true && eventName in KEYBOARD_EVENTS) {
            if (!game_Game.getInstance().hasControl('KeyboardControl'))
                throw new debugError_DebugError(getControlErrorMessage('keyboard', 'KeyboardControl'));
        }
        if (this._emitter === undefined)
            this._emitter = new eventEmitter_EventEmitter();
        this._emitter.on(eventName, callBack);
        return callBack;
    };
    EventEmitterDelegate.prototype.once = function (eventName, callBack) {
        var _this = this;
        var cb = this.on(eventName, function (_args) {
            _this.off(eventName, cb);
            callBack(_args);
        });
    };
    EventEmitterDelegate.prototype.off = function (eventName, callBack) {
        if (this._emitter !== undefined)
            this._emitter.off(eventName, callBack);
    };
    EventEmitterDelegate.prototype.trigger = function (eventName, data) {
        if (this._emitter !== undefined)
            this._emitter.trigger(eventName, data);
    };
    return EventEmitterDelegate;
}());


// CONCATENATED MODULE: ./engine/geometry/size.ts





var size_Size = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Size, _super);
    function Size(width, height, onChangedFn) {
        if (width === void 0) { width = 0; }
        if (height === void 0) { height = 0; }
        var _this = _super.call(this) || this;
        _this._arr = [0, 0];
        if (onChangedFn)
            _this.addOnChangeListener(onChangedFn);
        _this.setWH(width, height);
        return _this;
    }
    Object.defineProperty(Size.prototype, "width", {
        get: function () {
            return this._width;
        },
        set: function (val) {
            if ( true && Number.isNaN(val)) {
                console.trace();
                throw new debugError_DebugError("Size: wrong numeric argument  " + val);
            }
            var changed = this._width !== val;
            if (changed) {
                this._width = val;
                this.triggerObservable();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Size.prototype, "height", {
        get: function () {
            return this._height;
        },
        set: function (val) {
            var changed = this._height !== val;
            if (changed) {
                this._height = val;
                this.triggerObservable();
            }
        },
        enumerable: false,
        configurable: true
    });
    Size.fromPool = function () {
        return Size.rectPool.getFreeObject();
    };
    Size.prototype.setW = function (width) {
        this.setWH(width, this._height);
        return this;
    };
    Size.prototype.setH = function (height) {
        this.setWH(this._width, height);
        return this;
    };
    Size.prototype.setWH = function (width, height) {
        if (height === void 0) { height = width; }
        var changed = this._width !== width || this._height !== height;
        if (changed) {
            this._width = width;
            this._height = height;
            this.triggerObservable();
        }
        return this;
    };
    Size.prototype.addWH = function (width, height) {
        if (height === void 0) { height = width; }
        this.setWH(this.width + width, this.height + height);
        return this;
    };
    Size.prototype.set = function (another) {
        this.setWH(another.width, another.height);
        return this;
    };
    Size.prototype.equal = function (wOrAnother, h) {
        var wToCheck, hToCheck;
        if (Object(object["d" /* isNumber */])(wOrAnother)) {
            wToCheck = wOrAnother;
            hToCheck = h !== null && h !== void 0 ? h : wOrAnother;
        }
        else {
            wToCheck = wOrAnother.width;
            hToCheck = h !== null && h !== void 0 ? h : wOrAnother.height;
        }
        return this._width === wToCheck && this._height === hToCheck;
    };
    Size.prototype.clone = function () {
        return new Size(this.width, this.height);
    };
    Size.prototype.isZero = function () {
        return this.equal(0, 0);
    };
    Size.prototype.toArray = function () {
        this._arr[0] = this._width;
        this._arr[1] = this._height;
        return this._arr;
    };
    Size.prototype.toJSON = function () {
        return {
            width: this.width,
            height: this.height
        };
    };
    Size.rectPool = new objectPool_ObjectPool(Size);
    return Size;
}(observableEntity_ObservableEntity));


// CONCATENATED MODULE: ./engine/core/baseModel.ts



var baseModel_BaseModel = (function () {
    function BaseModel(game) {
        this.game = game;
        this.size = new size_Size();
        this.pos = new point2d_Point2d(0, 0);
        this.posZ = 0;
        if ( true && !game)
            throw new debugError_DebugError("can not create model '" + this.type + "': game instance not passed to model constructor");
    }
    return BaseModel;
}());


// CONCATENATED MODULE: ./engine/renderable/abstract/transformableModel.ts





var transformableModel_Mat16Holder = mat4_mat4.Mat16Holder;

var transformableModel_AnglePoint3d = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(AnglePoint3d, _super);
    function AnglePoint3d(m, zProperty) {
        var _this = _super.call(this) || this;
        _this.m = m;
        _this.zProperty = zProperty;
        _this._x = 0;
        _this._y = 0;
        _this._z = 0;
        return _this;
    }
    Object.defineProperty(AnglePoint3d.prototype, "z", {
        get: function () {
            return this._z;
        },
        set: function (val) {
            if (val !== this.m[this.zProperty]) {
                this.m[this.zProperty] = val;
                this.triggerObservable();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AnglePoint3d.prototype, "x", {
        get: function () {
            return this._x;
        },
        set: function (value) {
            if (this._x !== value) {
                this._x = value;
                this.triggerObservable();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AnglePoint3d.prototype, "y", {
        get: function () {
            return this._y;
        },
        set: function (value) {
            if (this._y !== value) {
                this._y = value;
                this.triggerObservable();
            }
        },
        enumerable: false,
        configurable: true
    });
    AnglePoint3d.prototype._setZSilently = function (val) {
        this._z = val;
    };
    AnglePoint3d.prototype.clone = function (m) {
        var a = new AnglePoint3d(m, this.zProperty);
        a._x = this._x;
        a._y = this._y;
        a.z = this.z;
        return a;
    };
    return AnglePoint3d;
}(observableEntity_ObservableEntity));
var transformableModel_ModelPoint2d = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(ModelPoint2d, _super);
    function ModelPoint2d(model) {
        var _this = _super.call(this) || this;
        _this.model = model;
        return _this;
    }
    ModelPoint2d.prototype.setToCenter = function () {
        this.model.revalidate();
        if ( true && !(this.model.size.width && this.model.size.height))
            throw new debugError_DebugError("can not set anchor to center: width or height of transformable object is not set");
        this.setXY(this.model.size.width / 2, this.model.size.height / 2);
    };
    return ModelPoint2d;
}(point2d_Point2d));
var transformableModel_TransformableModel = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(TransformableModel, _super);
    function TransformableModel(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.worldTransformMatrix = new transformableModel_Mat16Holder();
        _this.worldTransformDirty = true;
        _this.children = [];
        _this.scale = new point2d_Point2d(1, 1);
        _this.skew = new point2d_Point2d(0, 0);
        _this.anchorPoint = new transformableModel_ModelPoint2d(_this);
        _this.transformPoint = new transformableModel_ModelPoint2d(_this);
        _this.angle3d = new transformableModel_AnglePoint3d(_this, 'angle');
        _this.billBoard = false;
        _this._angleVelocity3d = new transformableModel_AnglePoint3d(_this, 'angleVelocity');
        _this._angle = 0;
        var observer = function () { return _this.worldTransformDirty = true; };
        _this.pos.observe(observer);
        _this.size.observe(observer);
        _this.scale.observe(observer);
        _this.transformPoint.observe(observer);
        _this.anchorPoint.observe(observer);
        _this.angle3d.observe(observer);
        return _this;
    }
    Object.defineProperty(TransformableModel.prototype, "angle", {
        get: function () {
            return this._angle;
        },
        set: function (val) {
            if (this._angle !== val)
                this.worldTransformDirty = true;
            this._angle = val;
            this.angle3d._setZSilently(val);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TransformableModel.prototype, "angleVelocity", {
        get: function () {
            return this._angleVelocity3d.z;
        },
        set: function (val) {
            this._angleVelocity3d._setZSilently(val);
        },
        enumerable: false,
        configurable: true
    });
    TransformableModel.prototype.translate = function () {
        var renderer = this.game.getRenderer();
        renderer.transformTranslate(this.pos.x, this.pos.y, this.posZ);
    };
    TransformableModel.prototype.transform = function () {
        var renderer = this.game.getRenderer();
        renderer.transformTranslate(-this.anchorPoint.x, -this.anchorPoint.y);
        renderer.transformTranslate(this.transformPoint.x, this.transformPoint.y);
        renderer.transformRotateZ(this.angle3d.z);
        renderer.transformRotateX(this.angle3d.x);
        renderer.transformRotateY(this.angle3d.y);
        var _a = this.scale.toArray(), x = _a[0], y = _a[1], z = _a[2];
        renderer.transformScale(x, y, z);
        renderer.transformSkewX(this.skew.x);
        renderer.transformSkewY(this.skew.y);
        renderer.transformTranslate(-this.transformPoint.x, -this.transformPoint.y);
        if (this.billBoard)
            renderer.transformRotationReset();
    };
    TransformableModel.prototype.setProps = function (props) {
        if (props.pos !== undefined)
            this.pos.set(props.pos);
        if (props.size !== undefined)
            this.size.set(props.size);
        if (props.scale !== undefined)
            this.scale.set(props.scale);
    };
    TransformableModel.prototype.setClonedProperties = function (cloned) {
        cloned.angle = this.angle;
        cloned.angleVelocity = this.angleVelocity;
        cloned.pos.set(this.pos);
        cloned.scale.set(this.scale);
        cloned.anchorPoint.set(this.anchorPoint);
        cloned.skew.set(this.skew);
        cloned.transformPoint.set(this.transformPoint);
        var angle3dCloned = this.angle3d.clone(this);
        cloned.angle3d.x = angle3dCloned.x;
        cloned.angle3d.y = angle3dCloned.y;
        cloned.angle3d.z = angle3dCloned.z;
    };
    return TransformableModel;
}(baseModel_BaseModel));


// CONCATENATED MODULE: ./engine/renderable/abstract/renderableModel.ts










var BLEND_MODE;
(function (BLEND_MODE) {
    BLEND_MODE[BLEND_MODE["NORMAL"] = 0] = "NORMAL";
    BLEND_MODE[BLEND_MODE["NORMAL_SEPARATE"] = 1] = "NORMAL_SEPARATE";
    BLEND_MODE[BLEND_MODE["ADDITIVE"] = 2] = "ADDITIVE";
    BLEND_MODE[BLEND_MODE["SUBSTRACTIVE"] = 3] = "SUBSTRACTIVE";
    BLEND_MODE[BLEND_MODE["REVERSE_SUBSTRACTIVE"] = 4] = "REVERSE_SUBSTRACTIVE";
})(BLEND_MODE || (BLEND_MODE = {}));
var renderableModel_RenderableModel = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(RenderableModel, _super);
    function RenderableModel(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.alpha = 1;
        _this.visible = true;
        _this.blendMode = BLEND_MODE.NORMAL;
        _this.depthTest = false;
        _this.filters = [];
        _this.forceDrawChildrenOnNewSurface = false;
        _this.children = [];
        _this.velocity = new point2d_Point2d(0, 0);
        _this.passMouseEventsThrough = false;
        _this._destRect = new rect_Rect();
        _this._behaviours = [];
        _this._propertyAnimations = [];
        _this._tweenDelegate = new tweenableDelegate_TweenableDelegate();
        _this._timerDelegate = new timerDelegate_TimerDelegate();
        _this._eventEmitterDelegate = new eventEmitterDelegate_EventEmitterDelegate();
        _this._parentChildDelegate = new parentChildDelegate_ParentChildDelegate(_this);
        _this.id = "object_" + Incrementer.getValue();
        _this._parentChildDelegate.afterChildAppended = function (child) {
            child.setLayer(_this._layer);
            child.setScene(_this.game.getCurrScene());
            child.revalidate();
        };
        _this._parentChildDelegate.afterChildRemoved = function (child) {
            child.setLayer(undefined);
            child.setScene(undefined);
        };
        return _this;
    }
    RenderableModel.prototype.revalidate = function () {
        for (var _i = 0, _a = this._behaviours; _i < _a.length; _i++) {
            var b = _a[_i];
            b.revalidate();
        }
    };
    RenderableModel.prototype.getLayer = function () {
        return this._layer;
    };
    RenderableModel.prototype.setLayer = function (value) {
        this._layer = value;
    };
    RenderableModel.prototype.getScene = function () {
        return this._scene;
    };
    RenderableModel.prototype.setScene = function (value) {
        this._scene = value;
    };
    RenderableModel.prototype.getDestRect = function () {
        this._destRect.setPoint(this.pos);
        this._destRect.setSize(this.size);
        return this._destRect;
    };
    RenderableModel.prototype.addBehaviour = function (b) {
        this._behaviours.push(b);
        b.manage(this);
    };
    RenderableModel.prototype.addPropertyAnimation = function (animation) {
        animation.target = this;
        this._propertyAnimations.push(animation);
    };
    RenderableModel.prototype.setPosAndSize = function (x, y, w, h) {
        this.pos.setXY(x, y);
        this.size.setWH(w, h);
    };
    RenderableModel.prototype.setRigidBody = function (rigidBody) {
        this._rigidBody = rigidBody;
        rigidBody.updateBounds(this);
    };
    RenderableModel.prototype.getRigidBody = function () {
        return this._rigidBody;
    };
    RenderableModel.prototype.destroy = function () {
        for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
            var c = _a[_i];
            c.destroy();
        }
        if ( true && !this.getParent())
            throw new debugError_DebugError("can not kill object: gameObject is detached");
        var parentArray = this.getParent().children;
        var index = parentArray.indexOf(this);
        if ( true && index === -1) {
            console.error(this);
            throw new debugError_DebugError('can not kill: object is not belong to current scene');
        }
        parentArray.splice(index, 1);
        for (var _b = 0, _c = this._behaviours; _b < _c.length; _b++) {
            var b = _c[_b];
            b.destroy();
        }
        this.game.getRenderer().killObject(this);
    };
    RenderableModel.prototype.render = function () {
        if (!this.visible)
            return;
        if (this.alpha === 0)
            return;
        var renderer = this.game.getRenderer();
        if (renderer.getAlphaBlend() === 0)
            return;
        renderer.saveAlphaBlend();
        renderer.transformSave();
        if (this.game.camera.worldTransformDirty || this.worldTransformDirty) {
            this.translate();
            this.transform();
            this.worldTransformMatrix.fromMat16(renderer.transformGet());
        }
        else {
            renderer.transformSet.apply(renderer, this.worldTransformMatrix.mat16);
        }
        renderer.setAlphaBlend(this.alpha);
        var statePointer = renderer.beforeItemStackDraw(this.filters, this.forceDrawChildrenOnNewSurface);
        this.draw();
        if (this.children.length > 0) {
            renderer.transformSave();
            renderer.saveAlphaBlend();
            for (var i = 0, max = this.children.length; i < max; i++) {
                var c = this.children[i];
                c.worldTransformDirty = this.worldTransformDirty || c.worldTransformDirty;
                c.render();
            }
            renderer.transformRestore();
            renderer.restoreAlphaBlend();
        }
        renderer.afterItemStackDraw(statePointer);
        renderer.transformRestore();
        renderer.restoreAlphaBlend();
        this.worldTransformDirty = false;
        if ( true && this._rigidBody !== undefined)
            this._rigidBody.debugRender();
    };
    RenderableModel.prototype.update = function () {
        var delta = this.game.getDeltaTime();
        this._tweenDelegate.update();
        this._timerDelegate.update();
        for (var _i = 0, _a = this._behaviours; _i < _a.length; _i++) {
            var bh = _a[_i];
            bh.update();
        }
        for (var _b = 0, _c = this._propertyAnimations; _b < _c.length; _b++) {
            var pa = _c[_b];
            pa.update();
        }
        if (this._rigidBody !== undefined) {
            this._rigidBody.nextTick();
        }
        else {
            if (this.velocity.x)
                this.pos.x += this.velocity.x * delta / 1000;
            if (this.velocity.y)
                this.pos.y += this.velocity.y * delta / 1000;
        }
        if (this._angleVelocity3d.x)
            this.angle3d.x += this._angleVelocity3d.x * delta / 1000;
        if (this._angleVelocity3d.y)
            this.angle3d.y += this._angleVelocity3d.y * delta / 1000;
        if (this._angleVelocity3d.z)
            this.angle3d.z += this._angleVelocity3d.z * delta / 1000;
        for (var _d = 0, _e = this.children; _d < _e.length; _d++) {
            var c = _e[_d];
            c.update();
        }
    };
    RenderableModel.prototype.addTween = function (t) {
        this._tweenDelegate.addTween(t);
    };
    RenderableModel.prototype.addTweenMovie = function (tm) {
        this._tweenDelegate.addTweenMovie(tm);
    };
    RenderableModel.prototype.tween = function (desc) {
        return this._tweenDelegate.tween(desc);
    };
    RenderableModel.prototype.setTimeout = function (callback, interval) {
        return this._timerDelegate.setTimeout(callback, interval);
    };
    RenderableModel.prototype.setInterval = function (callback, interval) {
        return this._timerDelegate.setInterval(callback, interval);
    };
    RenderableModel.prototype.off = function (eventName, callBack) {
        this._eventEmitterDelegate.off(eventName, callBack);
    };
    RenderableModel.prototype.on = function (eventName, callBack) {
        return this._eventEmitterDelegate.on(eventName, callBack);
    };
    RenderableModel.prototype.once = function (eventName, callBack) {
        this._eventEmitterDelegate.once(eventName, callBack);
    };
    RenderableModel.prototype.trigger = function (eventName, data) {
        this._eventEmitterDelegate.trigger(eventName, data);
    };
    RenderableModel.prototype.appendChild = function (newChild) {
        this._parentChildDelegate.appendChild(newChild);
    };
    RenderableModel.prototype.appendChildAt = function (newChild, index) {
        this._parentChildDelegate.appendChildAt(newChild, index);
    };
    RenderableModel.prototype.appendChildAfter = function (modelAfter, newChild) {
        this._parentChildDelegate.appendChildAfter(modelAfter, newChild);
    };
    RenderableModel.prototype.appendChildBefore = function (modelBefore, newChild) {
        this._parentChildDelegate.appendChildBefore(modelBefore, newChild);
    };
    RenderableModel.prototype.prependChild = function (newChild) {
        this._parentChildDelegate.prependChild(newChild);
    };
    RenderableModel.prototype.removeChild = function (c) {
        this._parentChildDelegate.removeChild(c);
    };
    RenderableModel.prototype.getParentNode = function () {
        return undefined;
    };
    RenderableModel.prototype.removeChildAt = function (i) {
        this._parentChildDelegate.removeChildAt(i);
    };
    RenderableModel.prototype.removeChildren = function () {
        this._parentChildDelegate.removeChildren();
    };
    RenderableModel.prototype.removeSelf = function () {
        this._parentChildDelegate.removeSelf();
    };
    RenderableModel.prototype.moveToFront = function () {
        this._parentChildDelegate.moveToFront();
    };
    RenderableModel.prototype.moveToBack = function () {
        this._parentChildDelegate.moveToBack();
    };
    RenderableModel.prototype.findChildById = function (id) {
        return this._parentChildDelegate.findChildById(id);
    };
    RenderableModel.prototype.replaceChild = function (c, newChild) {
        this._parentChildDelegate.replaceChild(c, newChild);
    };
    RenderableModel.prototype.getParent = function () {
        return this.parent || this._layer;
    };
    RenderableModel.prototype.getChildAt = function (index) {
        return this.children[index];
    };
    RenderableModel.prototype.getChildren = function () {
        return this.children;
    };
    RenderableModel.prototype.renderToTexture = function (target, clearColor) {
        this.game.getRenderer().getHelper().renderModelToTexture(this, target, clearColor);
    };
    RenderableModel.prototype.isDetached = function () {
        return this._scene === undefined;
    };
    RenderableModel.prototype.setClonedProperties = function (cloned) {
        cloned.size.set(cloned.size);
        cloned.alpha = this.alpha;
        cloned.blendMode = this.blendMode;
        cloned.visible = this.visible;
        cloned.filters = Object(tslib_es6["e" /* __spreadArrays */])(this.filters);
        cloned.forceDrawChildrenOnNewSurface = this.forceDrawChildrenOnNewSurface;
        if (this.getRigidBody() !== undefined)
            cloned.setRigidBody(this.getRigidBody().clone());
        this.children.forEach(function (c) {
            if ( true && !('clone' in c)) {
                console.error(c);
                throw new debugError_DebugError("can not clone object: cloneable interface is not implemented");
            }
            var clonedChildren = c.clone();
            if ( true && !(clonedChildren instanceof RenderableModel)) {
                console.error(c);
                throw new debugError_DebugError("can not clone object: \"clone\"  method must return Cloneable object");
            }
            cloned.appendChild(clonedChildren);
        });
        cloned.game = this.game;
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    return RenderableModel;
}(transformableModel_TransformableModel));


// CONCATENATED MODULE: ./engine/renderable/abstract/renderableModelWithResourceLink.ts



var renderableModelWithResourceLink_RenderableModelWithResourceLink = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(RenderableModelWithResourceLink, _super);
    function RenderableModelWithResourceLink() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    RenderableModelWithResourceLink.prototype.setResourceLink = function (link) {
        if (true) {
            if (!link) {
                throw new debugError_DebugError("can not set resource link: link passed is " + link);
            }
        }
        this._resourceLink = link;
    };
    RenderableModelWithResourceLink.prototype.getResourceLink = function () {
        return this._resourceLink;
    };
    return RenderableModelWithResourceLink;
}(renderableModel_RenderableModel));


// CONCATENATED MODULE: ./engine/renderable/impl/general/image.ts







var STRETCH_MODE;
(function (STRETCH_MODE) {
    STRETCH_MODE[STRETCH_MODE["STRETCH"] = 0] = "STRETCH";
    STRETCH_MODE[STRETCH_MODE["REPEAT"] = 1] = "REPEAT";
})(STRETCH_MODE || (STRETCH_MODE = {}));
var image_Image = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Image, _super);
    function Image(game) {
        var _this = _super.call(this, game) || this;
        _this.type = 'Image';
        _this.borderRadius = 0;
        _this.offset = new point2d_Point2d();
        _this.stretchMode = STRETCH_MODE.STRETCH;
        _this.color = color_Color.NONE.clone();
        _this.lineWidth = 0;
        _this._pixelPerfect = false;
        _this._srcRect = new rect_Rect();
        return _this;
    }
    Image.prototype.revalidate = function () {
        if ( true && !this.getResourceLink()) {
            console.error(this);
            throw new debugError_DebugError("can not render Image: resourceLink is not specified");
        }
        if ( true && this.getResourceLink().state !== ResourceLinkState.COMPLETED) {
            console.error(this);
            throw new debugError_DebugError("can not render Image: wrong resource link state: " + this.getResourceLink().state);
        }
        if ( true && !this.getResourceLink().getTarget()) {
            console.error(this);
            throw new debugError_DebugError("can not render Image: can not find texture by resource link");
        }
        var tex = this.getResourceLink().getTarget();
        if (this.size.isZero()) {
            this.size.width = tex.size.width;
            this.size.height = tex.size.height;
        }
        if (this._srcRect.isZeroSize()) {
            this._srcRect.setWH(tex.size.width, tex.size.height);
        }
    };
    Image.prototype.draw = function () {
        this.game.getRenderer().drawImage(this);
    };
    Image.prototype.clone = function () {
        var cloned = new Image(this.game);
        this.setClonedProperties(cloned);
        return cloned;
    };
    Image.prototype.setProps = function (props) {
        this.setResourceLink(props.resourceLink);
        _super.prototype.setProps.call(this, props);
        if (props.borderRadius !== undefined)
            this.borderRadius = props.borderRadius;
        if (props.color !== undefined)
            this.color.setRGBA(props.color.r, props.color.g, props.color.b, props.color.a);
        if (props.lineWidth !== undefined)
            this.lineWidth = props.lineWidth;
    };
    Image.prototype.getSrcRect = function () {
        return this._srcRect;
    };
    Image.prototype.setResourceLink = function (link) {
        _super.prototype.setResourceLink.call(this, link);
        var oldLink = this.getResourceLink();
        var canBeRevalidated = (oldLink === undefined || oldLink !== link) &&
            link.getTarget() !== undefined;
        if (canBeRevalidated)
            this.revalidate();
    };
    Image.prototype.setPixelPerfect = function (val) {
        this._pixelPerfect = val;
    };
    Image.prototype.isPixelPerfect = function () {
        return this._pixelPerfect;
    };
    Image.prototype.setClonedProperties = function (cloned) {
        cloned._srcRect.set(this._srcRect);
        cloned.size.set(this.size);
        cloned.borderRadius = this.borderRadius;
        cloned.offset.set(this.offset);
        cloned.stretchMode = this.stretchMode;
        cloned.color = this.color.clone();
        cloned.lineWidth = this.lineWidth;
        cloned._pixelPerfect = this._pixelPerfect;
        cloned.setResourceLink(this.getResourceLink());
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    return Image;
}(renderableModelWithResourceLink_RenderableModelWithResourceLink));


// CONCATENATED MODULE: ./engine/renderable/abstract/shape.ts





var shape_Shape = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Shape, _super);
    function Shape(game) {
        var _this = _super.call(this, game) || this;
        _this.color = color_Color.BLACK.clone();
        _this._lineWidth = 0;
        _this.fillColor = color_Color.GREY.clone();
        return _this;
    }
    Object.defineProperty(Shape.prototype, "lineWidth", {
        get: function () {
            return this._lineWidth;
        },
        set: function (value) {
            this._lineWidth = value;
        },
        enumerable: false,
        configurable: true
    });
    Shape.prototype.cacheAsBitmap = function () {
        var sizeInt = new size_Size().setWH(~~this.size.width, ~~this.size.height);
        var renderTarget = this.game.getRenderer().getHelper().
            createRenderTarget(this.game, sizeInt);
        var image = new image_Image(this.game);
        image.size.set(sizeInt);
        this.renderToTexture(renderTarget, color_Color.NONE);
        image.setResourceLink(renderTarget.getResourceLink());
        renderTarget.destroy();
        return image;
    };
    Shape.prototype.setProps = function (props) {
        _super.prototype.setProps.call(this, props);
        if (props.color !== undefined)
            this.color.setRGBA(props.color.r, props.color.g, props.color.b, props.color.a);
        if (props.fillColor !== undefined)
            this.fillColor.setRGBA(props.fillColor.r, props.fillColor.g, props.fillColor.b, props.fillColor.a);
        if (props.lineWidth !== undefined)
            this._lineWidth = props.lineWidth;
    };
    Shape.prototype.setClonedProperties = function (cloned) {
        cloned.color.set(this.color);
        cloned._lineWidth = this._lineWidth;
        cloned.fillColor = this.fillColor.clone();
        if (this.fillGradient !== undefined)
            cloned.fillGradient = this.fillGradient.clone();
        cloned.filters = Object(tslib_es6["e" /* __spreadArrays */])(this.filters);
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    return Shape;
}(renderableModel_RenderableModel));


// CONCATENATED MODULE: ./engine/renderable/impl/geometry/rectangle.ts


var rectangle_Rectangle = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Rectangle, _super);
    function Rectangle(game) {
        var _this = _super.call(this, game) || this;
        _this.type = 'Rectangle';
        _this.borderRadius = 0;
        _this.size.setWH(16);
        _this.lineWidth = 1;
        return _this;
    }
    Rectangle.prototype.draw = function () {
        this.game.getRenderer().drawRectangle(this);
    };
    Rectangle.prototype.clone = function () {
        var cloned = new Rectangle(this.game);
        this.setClonedProperties(cloned);
        return cloned;
    };
    Rectangle.prototype.setProps = function (props) {
        _super.prototype.setProps.call(this, props);
        if (props.borderRadius !== undefined)
            this.borderRadius = props.borderRadius;
    };
    Rectangle.prototype.setClonedProperties = function (cloned) {
        cloned.borderRadius = this.borderRadius;
        cloned.size.set(this.size);
        cloned.lineWidth = this.lineWidth;
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    return Rectangle;
}(shape_Shape));


// CONCATENATED MODULE: ./engine/scene/sceneLifeCicleState.ts
var SceneLifeCycleState;
(function (SceneLifeCycleState) {
    SceneLifeCycleState[SceneLifeCycleState["CREATED"] = 0] = "CREATED";
    SceneLifeCycleState[SceneLifeCycleState["PRELOADING"] = 1] = "PRELOADING";
    SceneLifeCycleState[SceneLifeCycleState["COMPLETED"] = 2] = "COMPLETED";
    SceneLifeCycleState[SceneLifeCycleState["INACTIVATED"] = 3] = "INACTIVATED";
})(SceneLifeCycleState || (SceneLifeCycleState = {}));

// CONCATENATED MODULE: ./engine/scene/scene.ts












var IDENTITY_HOLDER = mat4_mat4.IDENTITY_HOLDER;
var SCENE_EVENTS;
(function (SCENE_EVENTS) {
    SCENE_EVENTS["PRELOADING"] = "preloading";
    SCENE_EVENTS["PROGRESS"] = "progress";
    SCENE_EVENTS["COMPLETED"] = "completed";
    SCENE_EVENTS["CONTINUE"] = "continue";
    SCENE_EVENTS["INACTIVATED"] = "inactivated";
})(SCENE_EVENTS || (SCENE_EVENTS = {}));
var scene_Scene = (function () {
    function Scene(game) {
        this.game = game;
        this.type = "Scene";
        this.backgroundColor = color_Color.WHITE.clone();
        this.pos = new point2d_Point2d();
        this.filters = [];
        this.alpha = 1;
        this.size = new size_Size();
        this.lifeCycleState = SceneLifeCycleState.CREATED;
        this._layers = [];
        this._propertyAnimations = [];
        this._tweenDelegate = new tweenableDelegate_TweenableDelegate();
        this._timerDelegate = new timerDelegate_TimerDelegate();
        this._eventEmitterDelegate = new eventEmitterDelegate_EventEmitterDelegate();
        this.resourceLoader = new resourceLoader_ResourceLoader(game);
        this.size.set(this.game.size);
    }
    Scene.isLayerGuard = function (modelOrLayer) {
        return modelOrLayer.type === 'Layer';
    };
    Scene.prototype.revalidate = function () {
        if (this.size.isZero())
            this.size.set(this.game.size);
    };
    Scene.prototype.getLayers = function () {
        return this._layers;
    };
    Scene.prototype.getDefaultLayer = function () {
        if (!this._layers.length)
            this.appendChild(new layer_Layer(this.game));
        return this._layers[this._layers.length - 1];
    };
    Scene.prototype.getLayerById = function (id) {
        for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            if (layer.id === id)
                return layer;
        }
        return undefined;
    };
    Scene.prototype.getLayerAtIndex = function (index) {
        return this._layers[index];
    };
    Scene.prototype.removeChild = function (modelOrLayer) {
        if (Scene.isLayerGuard(modelOrLayer)) {
            var i = this._layers.indexOf(modelOrLayer);
            if ( true && i === -1)
                throw new debugError_DebugError("can not remove layer: is doesn't belong to target scene");
            this._layers.splice(i, 1);
        }
        else {
            this.getDefaultLayer().removeChild(modelOrLayer);
        }
    };
    Scene.prototype.appendChild = function (modelOrLayer) {
        if (Scene.isLayerGuard(modelOrLayer)) {
            modelOrLayer.setScene(this);
            this._layers.push(modelOrLayer);
        }
        else {
            this.getDefaultLayer().appendChild(modelOrLayer);
        }
    };
    Scene.prototype.prependChild = function (modelOrLayer) {
        if (Scene.isLayerGuard(modelOrLayer)) {
            modelOrLayer.setScene(this);
            this._layers.unshift(modelOrLayer);
        }
        else {
            this.getDefaultLayer().prependChild(modelOrLayer);
        }
    };
    Scene.prototype.fitSizeToChildren = function () {
        var maxRight = this.game.size.width;
        var maxBottom = this.game.size.height;
        this._layers.forEach(function (l) {
            l.children.forEach(function (c) {
                var right = c.pos.x + c.size.width;
                var bottom = c.pos.y + c.size.height;
                if (right > maxRight)
                    maxRight = right;
                if (bottom > maxBottom)
                    maxBottom = bottom;
            });
        });
        this.size.setWH(maxRight, maxBottom);
    };
    Scene.prototype.update = function () {
        if (!this.resourceLoader.isCompleted()) {
            if (this.preloadingGameObject !== undefined) {
                this.preloadingGameObject.update();
            }
        }
        else {
            this.updateFrame();
        }
    };
    Scene.prototype.renderToTexture = function (target) {
        this.game.getRenderer().getHelper().renderSceneToTexture(this, target);
    };
    Scene.prototype.addPropertyAnimation = function (animation) {
        this._propertyAnimations.push(animation);
    };
    Scene.prototype.addTween = function (t) {
        this._tweenDelegate.addTween(t);
    };
    Scene.prototype.addTweenMovie = function (tm) {
        this._tweenDelegate.addTweenMovie(tm);
    };
    Scene.prototype.tween = function (desc) {
        return this._tweenDelegate.tween(desc);
    };
    Scene.prototype.setTimeout = function (callback, interval) {
        return this._timerDelegate.setTimeout(callback, interval);
    };
    Scene.prototype.setInterval = function (callback, interval) {
        return this._timerDelegate.setInterval(callback, interval);
    };
    Scene.prototype.off = function (eventName, callBack) {
        this._eventEmitterDelegate.off(eventName, callBack);
    };
    Scene.prototype.on = function (eventName, callBack) {
        return this._eventEmitterDelegate.on(eventName, callBack);
    };
    Scene.prototype.once = function (eventName, callBack) {
        this._eventEmitterDelegate.once(eventName, callBack);
    };
    Scene.prototype.trigger = function (eventName, data) {
        this._eventEmitterDelegate.trigger(eventName, data);
    };
    Scene.prototype.findChildById = function (id) {
        for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
            var l = _a[_i];
            var possibleObject = l.findChildById(id);
            if (possibleObject)
                return possibleObject;
        }
        return undefined;
    };
    Scene.prototype.onPreloading = function () {
        var rect = new rectangle_Rectangle(this.game);
        rect.fillColor.setRGB(10, 100, 100);
        rect.size.height = 10;
        this.preloadingGameObject = rect;
    };
    Scene.prototype.onProgress = function (val) {
        if (this.preloadingGameObject !== undefined)
            this.preloadingGameObject.size.width = val * this.game.size.width;
    };
    Scene.prototype.onReady = function () { };
    Scene.prototype.onContinue = function () { };
    Scene.prototype.render = function () {
        var _a, _b;
        var renderer = this.game.getRenderer();
        renderer.transformSave();
        renderer.saveAlphaBlend();
        renderer.clearColor.set(this.backgroundColor);
        var statePointer = renderer.beforeFrameDraw(this.filters);
        if (this.game.camera.worldTransformDirty) {
            this.game.camera.translate();
            this.game.camera.transform();
            (_a = this.game.camera.worldTransformMatrix).set.apply(_a, this.game.getRenderer().transformGet());
        }
        else {
            (_b = this.game.getRenderer()).transformSet.apply(_b, this.game.camera.worldTransformMatrix.mat16);
        }
        renderer.setAlphaBlend(this.alpha);
        if (!this.resourceLoader.isCompleted()) {
            if (this.preloadingGameObject !== undefined) {
                this.preloadingGameObject.render();
            }
        }
        else {
            for (var _i = 0, _c = this._layers; _i < _c.length; _i++) {
                var l = _c[_i];
                if (l.transformType === LayerTransformType.STICK_TO_CAMERA) {
                    renderer.transformSave();
                    renderer.transformSet.apply(renderer, IDENTITY_HOLDER.mat16);
                }
                l.render();
                if (l.transformType === LayerTransformType.STICK_TO_CAMERA) {
                    renderer.transformRestore();
                }
            }
        }
        renderer.restoreAlphaBlend();
        renderer.transformSave();
        this.onRender();
        renderer.transformRestore();
        renderer.afterFrameDraw(statePointer);
        renderer.transformRestore();
    };
    Scene.prototype.onInactivated = function () { };
    Scene.prototype.onUpdate = function () { };
    Scene.prototype.onRender = function () { };
    Scene.prototype.updateFrame = function () {
        this.game.camera.update();
        this._tweenDelegate.update();
        this._timerDelegate.update();
        for (var _i = 0, _a = this._propertyAnimations; _i < _a.length; _i++) {
            var a = _a[_i];
            a.update();
        }
        for (var _b = 0, _c = this._layers; _b < _c.length; _b++) {
            var l = _c[_b];
            l.update();
        }
        if (this.game.hasPhysicsSystem())
            this.game.getPhysicsSystem().nextTick(this);
        this.onUpdate();
    };
    return Scene;
}());


// CONCATENATED MODULE: ./engine/misc/collection/stack.ts

var stack_Stack = (function () {
    function Stack() {
        this._array = new Array(16);
        this._stackPointer = 0;
    }
    Stack.prototype.push = function (obj) {
        this._array[this._stackPointer++] = obj;
    };
    Stack.prototype.pop = function () {
        if ( true && this._stackPointer === 0)
            throw new debugError_DebugError("empty stack");
        this._stackPointer--;
        var res = this._array[this._stackPointer];
        this._array[this._stackPointer] = undefined;
        return res;
    };
    Stack.prototype.replaceLast = function (obj) {
        if (!this._array.length)
            this.push(obj);
        else
            this._array[this._stackPointer - 1] = obj;
    };
    Stack.prototype.getLast = function () {
        if (!this._array)
            return undefined;
        else
            return this._array[this._stackPointer - 1];
    };
    Stack.prototype.getAt = function (i) {
        return this._array[i];
    };
    Stack.prototype.size = function () {
        return this._stackPointer;
    };
    Stack.prototype.isEmpty = function () {
        return this._stackPointer === 0;
    };
    return Stack;
}());


// CONCATENATED MODULE: ./engine/core/game.ts








var SCALE_STRATEGY;
(function (SCALE_STRATEGY) {
    SCALE_STRATEGY[SCALE_STRATEGY["NO_SCALE"] = 0] = "NO_SCALE";
    SCALE_STRATEGY[SCALE_STRATEGY["FIT"] = 1] = "FIT";
    SCALE_STRATEGY[SCALE_STRATEGY["STRETCH"] = 2] = "STRETCH";
})(SCALE_STRATEGY || (SCALE_STRATEGY = {}));
var game_Game = (function () {
    function Game(_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.width, width = _c === void 0 ? 320 : _c, _d = _b.height, height = _d === void 0 ? 240 : _d, _e = _b.scaleStrategy, scaleStrategy = _e === void 0 ? SCALE_STRATEGY.FIT : _e, containerElement = _b.containerElement;
        this.size = new size_Size();
        this.scale = new point2d_Point2d(1, 1);
        this.pos = new point2d_Point2d(0, 0);
        this.camera = new camera_Camera(this);
        this.fps = 0;
        this._scaleStrategy = SCALE_STRATEGY.FIT;
        this._startedTime = 0;
        this._lastTime = 0;
        this._currTime = 0;
        this._deltaTime = 0;
        this._sceneStack = new stack_Stack();
        this._running = false;
        this._destroyed = false;
        this._controls = [];
        this._mainLoop = new MainLoop(this);
        Game._instance = this;
        if (true)
            window.game = this;
        this.size.setWH(width, height);
        this._scaleStrategy = scaleStrategy;
        this._startedTime = Date.now();
        this.rootContainerElement = containerElement;
    }
    Game.getInstance = function () {
        return Game._instance;
    };
    Object.defineProperty(Game.prototype, "scaleStrategy", {
        get: function () {
            return this._scaleStrategy;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Game.prototype, "width", {
        get: function () {
            return this.size.width;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Game.prototype, "height", {
        get: function () {
            return this.size.height;
        },
        enumerable: false,
        configurable: true
    });
    Game.prototype.addControl = function (C) {
        var instance = new C(this);
        if (true) {
            for (var _i = 0, _a = this._controls; _i < _a.length; _i++) {
                var c = _a[_i];
                if (c.type === instance.type) {
                    throw new debugError_DebugError("control with type \"" + c.type + "\" added already");
                }
            }
        }
        this._controls.push(instance);
        instance.listenTo();
    };
    Game.prototype.hasControl = function (type) {
        return this.getControl(type) !== undefined;
    };
    Game.prototype.getControl = function (type) {
        for (var _i = 0, _a = this._controls; _i < _a.length; _i++) {
            var c = _a[_i];
            if (c.type === type) {
                return c;
            }
        }
        return undefined;
    };
    Game.prototype.setPhysicsSystem = function (s) {
        this._physicsSystem = new s(this);
    };
    Game.prototype.getPhysicsSystem = function () {
        if ( true && this._physicsSystem === undefined)
            throw new debugError_DebugError("Physics system is not initialized.");
        return this._physicsSystem;
    };
    Game.prototype.hasPhysicsSystem = function () {
        return this._physicsSystem !== undefined;
    };
    Game.prototype.setAudioPLayer = function (p) {
        this._audioPlayer = new p(this);
    };
    Game.prototype.getAudioPlayer = function () {
        if ( true && !this._audioPlayer) {
            throw new debugError_DebugError('audio player is not set');
        }
        return this._audioPlayer;
    };
    Game.prototype.getCurrentTime = function () {
        return this._lastTime;
    };
    Game.prototype.getDeltaTime = function () {
        return this._deltaTime;
    };
    Game.prototype.getElapsedTime = function () {
        return this._lastTime - this._startedTime;
    };
    Game.prototype.setRenderer = function (Renderer) {
        this._renderer = new Renderer(this);
    };
    Game.prototype.getRenderer = function () {
        return this._renderer;
    };
    Game.prototype.runScene = function (scene, transition, replaceStack) {
        var _this = this;
        if (replaceStack === void 0) { replaceStack = true; }
        if (replaceStack)
            this._sceneStack.replaceLast({ scene: scene, transition: transition });
        this._prevScene = this._currScene;
        if (this._prevScene !== undefined) {
            this._prevScene.trigger(SCENE_EVENTS.INACTIVATED, undefined);
            this._prevScene.onInactivated();
            this._prevScene.lifeCycleState = SceneLifeCycleState.INACTIVATED;
        }
        this._currScene = scene;
        if (this._currSceneTransition !== undefined) {
            this._currSceneTransition.complete();
            this._currSceneTransition = undefined;
        }
        if (transition !== undefined) {
            this._currSceneTransition = transition;
            transition.start(this._prevScene, this._currScene);
            transition.onComplete(function () { return _this._currSceneTransition = undefined; });
        }
        this.revalidate();
        if (!scene.resourceLoader.isCompleted()) {
            this._currScene.trigger(SCENE_EVENTS.PRELOADING);
            scene.onPreloading();
            scene.resourceLoader.onProgress(function () {
                _this._currScene.trigger(SCENE_EVENTS.PROGRESS);
                scene.onProgress(scene.resourceLoader.getProgress());
                _this._currScene.lifeCycleState = SceneLifeCycleState.PRELOADING;
            });
            scene.resourceLoader.onCompleted(function () {
                _this._currScene.onReady();
                _this._currScene.onContinue();
                _this._currScene.trigger(SCENE_EVENTS.COMPLETED);
                _this._currScene.lifeCycleState = SceneLifeCycleState.COMPLETED;
            });
            scene.resourceLoader.startLoading();
        }
        else {
            this._currScene.trigger(SCENE_EVENTS.CONTINUE);
            this._currScene.lifeCycleState = SceneLifeCycleState.COMPLETED;
            this._currScene.onContinue();
        }
        if (!this._running) {
            this._mainLoop.start();
            this._running = true;
        }
    };
    Game.prototype.pushScene = function (scene, transition) {
        this.runScene(scene, transition, false);
        this._sceneStack.push({ scene: scene, transition: transition });
    };
    Game.prototype.popScene = function () {
        var last = this._sceneStack.pop();
        if ( true && !last)
            throw new debugError_DebugError("can not pop scene: no scene in stack");
        var transition = last.transition ? last.transition.getOppositeTransition() : undefined;
        var prevScene = this._sceneStack.getLast().scene;
        this.runScene(prevScene, transition);
    };
    Game.prototype.getCurrScene = function () {
        if ( true && !this._currScene)
            throw new debugError_DebugError("current scene is not set yet");
        return this._currScene;
    };
    Game.prototype.update = function () {
        if (this._destroyed)
            return;
        this._lastTime = this._currTime;
        this._currTime = Date.now();
        var currTimeCopy = this._currTime;
        if (!this._lastTime)
            this._lastTime = this._currTime;
        this._deltaTime = this._currTime - this._lastTime;
        if (true) {
            this.fps = ~~(1000 / this._deltaTime);
            var renderError = this._renderer.getError();
            if (renderError !== undefined) {
                throw new debugError_DebugError("rendering error with code " + renderError.code + " (" + renderError.desc + ")");
            }
        }
        var numOfLoops = (~~(this._deltaTime / Game._UPDATE_TIME_RATE)) || 1;
        this._currTime = this._currTime - numOfLoops * Game._UPDATE_TIME_RATE;
        var currentScene = this._currScene;
        var loopCnt = 0;
        do {
            this._lastTime = this._currTime;
            this._currTime += Game._UPDATE_TIME_RATE;
            this._deltaTime = this._currTime - this._lastTime;
            if (this._currSceneTransition !== undefined)
                this._currSceneTransition.update();
            else
                currentScene.update();
            for (var _i = 0, _a = this._controls; _i < _a.length; _i++) {
                var c = _a[_i];
                c.update();
            }
            loopCnt++;
            if (loopCnt > 10) {
                this._lastTime = this._currTime = currTimeCopy;
                break;
            }
        } while (loopCnt < numOfLoops);
        if (this._currSceneTransition !== undefined)
            this._currSceneTransition.render();
        else
            currentScene.render();
        this.camera.worldTransformDirty = false;
    };
    Game.prototype.destroy = function () {
        this._mainLoop.stop();
        this._destroyed = true;
        for (var _i = 0, _a = this._controls; _i < _a.length; _i++) {
            var c = _a[_i];
            c.destroy();
        }
        if (this._renderer) {
            this._renderer.cancelFullScreen();
            this._renderer.destroy();
        }
        if (this._audioPlayer)
            this._audioPlayer.stopAll();
    };
    Game.prototype.revalidate = function () {
        if ( true && !this._renderer)
            throw new debugError_DebugError("game renderer is not set");
        this.camera.revalidate();
    };
    Game._UPDATE_TIME_RATE = 20;
    return Game;
}());

if (true) {
    if (!window.__POLYFILLS_INCLUDED__)
        throw new debugError_DebugError("polyfills module is not included!");
}
if (true) {
    var now = Date.now();
    var passed = now - 1603311204115;
    console.log("last compiled " + passed / 1000 + " sec ago");
}
var MainLoop = (function () {
    function MainLoop(game) {
        this.game = game;
    }
    MainLoop.prototype.start = function () {
        var _this = this;
        var game = this.game;
        var updateFn = game.update.bind(game);
        var loopFn = function () {
            updateFn();
            _this.timerId = requestAnimationFrame(loopFn);
        };
        this.timerId = requestAnimationFrame(loopFn);
    };
    MainLoop.prototype.stop = function () {
        cancelAnimationFrame(this.timerId);
    };
    return MainLoop;
}());

// CONCATENATED MODULE: ./engine/renderer/webGl/base/shaderProgramUtils.ts


var parseErrors = function (log) {
    if (false)
        {}
    var logs = [];
    var result;
    while (!!(result = log.match(/ERROR\:([^\n]+)/))) {
        if (result.index !== undefined)
            log = log.slice((result.index + 1));
        var line = result[1].trim();
        var seps = line.split(':');
        var message = seps.slice(2).join(':').trim();
        var lineNum = +seps[1];
        logs.push({ message: message, lineNum: lineNum });
    }
    return logs;
};
var compileShader = function (gl, shaderSource, shaderType) {
    if (true) {
        if (!shaderSource)
            throw new debugError_DebugError("can not compile shader: shader source not specified for type " + shaderType);
    }
    var shader = gl.createShader(shaderType);
    if ( true && !shader)
        throw new debugError_DebugError("can not allocate memory for shader: gl.createShader(shaderType)");
    gl.shaderSource(shader, shaderSource);
    gl.compileShader(shader);
    var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compiled) {
        var lastError = gl.getShaderInfoLog(shader);
        gl.deleteShader(shader);
        if (lastError !== null) {
            if (true) {
                var parsedLogs = parseErrors(lastError);
                var lines_1 = shaderSource.split('\n');
                var errorMsg_1 = '';
                var arrow_1 = '----->';
                parsedLogs.forEach(function (inf) {
                    var i = inf.lineNum - 1;
                    if (lines_1[i].indexOf(arrow_1) === -1)
                        lines_1[i] = arrow_1 + " " + lines_1[i];
                    errorMsg_1 += lines_1[i] + " <----" + inf.message + "\n";
                });
                console.log(lines_1.join('\n'));
                throw new debugError_DebugError("Error compiling shader: " + (errorMsg_1 ? errorMsg_1 : lastError));
            }
            else {}
        }
        else {
            throw new Error( true ? 'unknown compilation error' : undefined);
        }
    }
    return shader || undefined;
};
var createProgram = function (gl, vertexShader, fragmentShader) {
    var program = gl.createProgram();
    if ( true && !program)
        throw new debugError_DebugError("can not allocate memory for gl.createProgram()");
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
        var lastError = gl.getProgramInfoLog(program);
        if (lastError) {
            if (true) {
                var status = gl.getProgramParameter(program, gl.VALIDATE_STATUS);
                console.error('VALIDATE_STATUS', status);
                var vertexSource = gl.getShaderSource(vertexShader);
                var fragmentSource = gl.getShaderSource(fragmentShader);
                console.log(vertexSource);
                console.log('\n\n');
                console.log(fragmentSource);
                gl.deleteProgram(program);
                throw new debugError_DebugError("Error in program linking. Last error \"" + lastError + "\", status: " + status);
            }
            else {}
        }
        else {
            throw new Error( true ? 'unknown linking error' : undefined);
        }
    }
    return program;
};
var GL_TABLE;
var GL_TYPE;
(function (GL_TYPE) {
    GL_TYPE["FLOAT"] = "float";
    GL_TYPE["FLOAT_VEC2"] = "vec2";
    GL_TYPE["FLOAT_VEC3"] = "vec3";
    GL_TYPE["FLOAT_VEC4"] = "vec4";
    GL_TYPE["INT"] = "int";
    GL_TYPE["INT_VEC2"] = "ivec2";
    GL_TYPE["INT_VEC3"] = "ivec3";
    GL_TYPE["INT_VEC4"] = "ivec4";
    GL_TYPE["BOOL"] = "bool";
    GL_TYPE["BOOL_VEC2"] = "bvec2";
    GL_TYPE["BOOL_VEC3"] = "bvec3";
    GL_TYPE["BOOL_VEC4"] = "bvec4";
    GL_TYPE["FLOAT_MAT2"] = "mat2";
    GL_TYPE["FLOAT_MAT3"] = "mat3";
    GL_TYPE["FLOAT_MAT4"] = "mat4";
    GL_TYPE["SAMPLER_2D"] = "sampler2D";
    GL_TYPE["SAMPLER_CUBE"] = "samplerCube";
})(GL_TYPE || (GL_TYPE = {}));
var mapType = function (gl, type) {
    if (GL_TABLE === undefined) {
        var typeNames = Object.keys(GL_TYPE);
        GL_TABLE = {};
        for (var i = 0; i < typeNames.length; ++i) {
            var tn = typeNames[i];
            GL_TABLE[gl[tn]] = GL_TYPE[tn];
        }
    }
    return GL_TABLE[type];
};
var normalizeUniformName = function (s) {
    if ( true && s.indexOf(' ') > -1)
        throw new debugError_DebugError("bad uniform name: \"" + s + "\", check spaces!");
    else
        return s;
};
var extractUniformsFromShaderBin = function (gl, program) {
    var glProgram = program.getProgram();
    var activeUniforms = gl.getProgramParameter(glProgram, gl.ACTIVE_UNIFORMS);
    var uniforms = {};
    for (var i = 0; i < activeUniforms; i++) {
        var uniformData = gl.getActiveUniform(glProgram, i);
        if ( true && !uniformData)
            throw new debugError_DebugError("can not receive active uniforms info: gl.getActiveUniform()");
        var type = mapType(gl, uniformData.type);
        var name = normalizeUniformName(uniformData.name);
        var location = gl.getUniformLocation(glProgram, name);
        if ( true && location === null) {
            console.log(program);
            throw new debugError_DebugError("error finding uniform location: " + uniformData.name);
        }
        uniforms[name] = {
            type: type,
            size: uniformData.size,
            location: location,
            setter: getUniformSetter(uniformData.size, type)
        };
        if (name.indexOf('[') > -1) {
            var arrayName = name.split(/\[/)[0];
            uniforms[arrayName] = uniforms[name];
        }
    }
    return uniforms;
};
var extractUniformsAndAttributesFromShaderSource = function (vertexSource, fragmentSource) {
    var uniforms = [];
    var attributes = [];
    var allTokens = (vertexSource + " " + fragmentSource).split(/[\s;]/).filter(function (it) { return !!it; });
    allTokens.forEach(function (it, i) {
        var possibleUniformName = allTokens[i + 2];
        if (it === 'uniform' && possibleUniformName !== undefined && uniforms.indexOf(possibleUniformName) === -1) {
            uniforms.push(possibleUniformName);
        }
        else {
            var possibleAttributeName = allTokens[i + 2];
            if (it === 'attribute' && possibleAttributeName !== undefined && attributes.indexOf(possibleAttributeName) === -1) {
                attributes.push(possibleAttributeName);
            }
        }
    });
    return { uniforms: uniforms, attributes: attributes };
};
var extractAttributes = function (gl, program) {
    var glProgram = program.getProgram();
    var activeAttributes = gl.getProgramParameter(glProgram, gl.ACTIVE_ATTRIBUTES);
    var attrMap = {};
    for (var i = 0; i < activeAttributes; i++) {
        var attrData = gl.getActiveAttrib(glProgram, i);
        if ( true && !attrData)
            throw new debugError_DebugError("can not receive active attribute info: gl.getActiveAttrib()");
        var location = gl.getAttribLocation(glProgram, attrData.name);
        if ( true && location < 0) {
            console.log(program);
            throw new debugError_DebugError("error finding attribute location: " + attrData.name);
        }
        attrMap[attrData.name] = location;
    }
    return attrMap;
};
var isNumber = function (val) {
    if (false)
        {}
    if (isNaN(parseFloat(String(val))) || !isFinite(Number(val)))
        throw new debugError_DebugError("can not set uniform with value " + val + ": expected argument of type number");
    else
        return true;
};
var isInteger = function (val) {
    if (false)
        {}
    isNumber(val);
    if (val !== ~~val)
        throw new debugError_DebugError("can not set uniform with value " + val + ": expected argument of integer type, but " + val + " found");
    else
        return true;
};
var isBoolean = function (val) {
    if (false)
        {}
    if (!(val === true || val === false))
        throw new debugError_DebugError("can not set uniform with value " + val + ": expected argument of boolean type, but " + val + " found");
    else
        return true;
};
var isArrayOfType = function (val, checker, size) {
    if (false)
        {}
    else if (!val)
        throw new debugError_DebugError("can not set uniform  value: " + val);
    else if (Object(object["b" /* isCommonArray */])(val)) {
        console.error(val);
        throw new debugError_DebugError("can not use primitive array as uniform value. Use Float32Array of Int32Array instead");
    }
    else if (!Object(object["f" /* isTypedArray */])(val)) {
        console.error('Can not set uniform value', val);
        throw new debugError_DebugError("can not set uniform with value [" + val + "]: expected argument of type Array");
    }
    if (size !== undefined && val.length !== size)
        throw new debugError_DebugError("can not set uniform with value [" + val + "]: expected array with size " + size + ", but " + val.length + " found");
    for (var i = 0, length = val.length; i < length; i++) {
        try {
            checker(val[i]);
        }
        catch (e) {
            console.error('Can not set uniform array item', val);
            throw new debugError_DebugError("can not set uniform array item with value [" + val + "]: unexpected array element type: " + val[i]);
        }
    }
    return true;
};
var getUniformSetter = function (size, type) {
    if (size === 1) {
        switch (type) {
            case GL_TYPE.FLOAT: return function (gl, location, value) {
                if (isNumber(value))
                    gl.uniform1f(location, value);
            };
            case GL_TYPE.FLOAT_VEC2: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, 2))
                    gl.uniform2f(location, value[0], value[1]);
            };
            case GL_TYPE.FLOAT_VEC3: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, 3))
                    gl.uniform3f(location, value[0], value[1], value[2]);
            };
            case GL_TYPE.FLOAT_VEC4: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, 4))
                    gl.uniform4f(location, value[0], value[1], value[2], value[3]);
            };
            case GL_TYPE.INT: return function (gl, location, value) {
                if (isInteger(value))
                    gl.uniform1i(location, value);
            };
            case GL_TYPE.INT_VEC2: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, 2))
                    gl.uniform2i(location, value[0], value[1]);
            };
            case GL_TYPE.INT_VEC3: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, 3))
                    gl.uniform3i(location, value[0], value[1], value[2]);
            };
            case GL_TYPE.INT_VEC4: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, 4))
                    gl.uniform4i(location, value[0], value[1], value[2], value[3]);
            };
            case GL_TYPE.BOOL: return function (gl, location, value) {
                if (isBoolean(value))
                    gl.uniform1i(location, value ? 1 : 0);
            };
            case GL_TYPE.BOOL_VEC2: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, 2))
                    gl.uniform2i(location, value[0], value[1]);
            };
            case GL_TYPE.BOOL_VEC3: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, 3))
                    gl.uniform3i(location, value[0], value[1], value[2]);
            };
            case GL_TYPE.BOOL_VEC4: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, 4))
                    gl.uniform4i(location, value[0], value[1], value[2], value[3]);
            };
            case GL_TYPE.FLOAT_MAT2: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, 2 * 2))
                    gl.uniformMatrix2fv(location, false, value);
            };
            case GL_TYPE.FLOAT_MAT3: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, 3 * 3))
                    gl.uniformMatrix3fv(location, false, value);
            };
            case GL_TYPE.FLOAT_MAT4: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, 4 * 4))
                    gl.uniformMatrix4fv(location, false, value);
            };
            case GL_TYPE.SAMPLER_2D: return function (gl, location, value) {
                if (isNumber(value))
                    gl.uniform1i(location, value);
            };
            case GL_TYPE.SAMPLER_CUBE: return function (gl, location, value) {
                if (isNumber(value))
                    gl.uniform1i(location, value);
            };
            default:
                if (true)
                    throw new debugError_DebugError("can not set uniform for type " + type + " and size " + size);
                break;
        }
    }
    else {
        switch (type) {
            case GL_TYPE.FLOAT: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, size))
                    gl.uniform1fv(location, value);
            };
            case GL_TYPE.FLOAT_VEC2: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, size * 2))
                    gl.uniform2fv(location, value);
            };
            case GL_TYPE.FLOAT_VEC3: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, size * 3))
                    gl.uniform3fv(location, value);
            };
            case GL_TYPE.FLOAT_VEC4: return function (gl, location, value) {
                if (isArrayOfType(value, isNumber, size * 4))
                    gl.uniform4fv(location, value);
            };
            case GL_TYPE.INT: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, size))
                    gl.uniform1iv(location, value);
            };
            case GL_TYPE.INT_VEC2: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, size * 2))
                    gl.uniform2iv(location, value);
            };
            case GL_TYPE.INT_VEC3: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, size * 3))
                    gl.uniform3iv(location, value);
            };
            case GL_TYPE.INT_VEC4: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, size * 4))
                    gl.uniform4iv(location, value);
            };
            case GL_TYPE.BOOL: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, size))
                    gl.uniform1iv(location, value);
            };
            case GL_TYPE.BOOL_VEC2: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, size * 2))
                    gl.uniform2iv(location, value);
            };
            case GL_TYPE.BOOL_VEC3: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, size * 3))
                    gl.uniform3iv(location, value);
            };
            case GL_TYPE.BOOL_VEC4: return function (gl, location, value) {
                if (isArrayOfType(value, isBoolean, size * 4))
                    gl.uniform4iv(location, value);
            };
            case GL_TYPE.SAMPLER_2D: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, size))
                    gl.uniform1iv(location, value);
            };
            case GL_TYPE.SAMPLER_CUBE: return function (gl, location, value) {
                if (isArrayOfType(value, isInteger, size))
                    gl.uniform1iv(location, value);
            };
            default:
                if (true)
                    throw new debugError_DebugError("can not set uniform for type " + type + " and size " + size);
                break;
        }
    }
    throw new Error();
};

// CONCATENATED MODULE: ./engine/renderer/webGl/base/shaderProgram.ts


var shaderProgram_ShaderProgram = (function () {
    function ShaderProgram(_gl, vertexSource, fragmentSource) {
        this._gl = _gl;
        this._attributeSourceNames = [];
        var vShader = compileShader(_gl, vertexSource, _gl.VERTEX_SHADER);
        var fShader = compileShader(_gl, fragmentSource, _gl.FRAGMENT_SHADER);
        this._program = createProgram(_gl, vShader, fShader);
        _gl.deleteShader(vShader);
        _gl.deleteShader(fShader);
        this._uniforms = extractUniformsFromShaderBin(_gl, this);
        this._attributes = extractAttributes(_gl, this);
        var sourceExtracted = extractUniformsAndAttributesFromShaderSource(vertexSource, fragmentSource);
        this._attributeSourceNames = sourceExtracted.attributes;
        this._uniformSourceNames = sourceExtracted.uniforms;
    }
    ShaderProgram.prototype.getProgram = function () {
        return this._program;
    };
    ShaderProgram.prototype.bind = function () {
        if (ShaderProgram.currentProgram === this)
            return;
        this._gl.useProgram(this._program);
        ShaderProgram.currentProgram = this;
    };
    ShaderProgram.prototype.unbind = function () {
        this._gl.useProgram(null);
        ShaderProgram.currentProgram = undefined;
    };
    ShaderProgram.prototype.setUniform = function (name, value) {
        if ( true && !name) {
            throw new debugError_DebugError("no uniform name was provided!");
        }
        var uniformWrapper = this._uniforms[name];
        if ( true && !uniformWrapper) {
            if (this._uniformSourceNames.indexOf(name) > -1) {
                return;
            }
            console.error('shader program failed', this);
            console.error('uniforms', this._uniforms);
            throw new debugError_DebugError("no uniform with name " + name + " found!");
        }
        if (true) {
            if (ShaderProgram.currentProgram !== this) {
                console.error(this);
                throw new debugError_DebugError("can not set uniform: target program is inactive");
            }
        }
        uniformWrapper.setter(this._gl, uniformWrapper.location, value);
    };
    ShaderProgram.prototype.bindBuffer = function (buffer, attrName) {
        if (true) {
            if (!attrName)
                throw new debugError_DebugError("can not find attribute location: attrName not defined");
            if (this._attributes[attrName] === undefined) {
                if (this._attributeSourceNames.indexOf(attrName) > -1) {
                    return;
                }
                console.log(this);
                throw new debugError_DebugError("can not find attribute location for  " + attrName);
            }
        }
        this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer.getGlBuffer());
        this.enableAttribute(attrName);
        var attrLocation = this._attributes[attrName];
        this._gl.vertexAttribPointer(attrLocation, buffer.getItemSize(), buffer.getItemType(), false, 0, 0);
    };
    ShaderProgram.prototype.disableAttribute = function (attrName) {
        this.toggleAttribute(attrName, false);
    };
    ShaderProgram.prototype.enableAttribute = function (attrName) {
        this.toggleAttribute(attrName, true);
    };
    ShaderProgram.prototype.destroy = function () {
        this._gl.deleteProgram(this._program);
    };
    ShaderProgram.prototype.toggleAttribute = function (attrName, on) {
        if (this._attributes[attrName] === undefined) {
            console.log(this);
            throw new debugError_DebugError("unbind error: can not find attribute location for  " + attrName);
        }
        var attrLocation = this._attributes[attrName];
        if (on)
            this._gl.enableVertexAttribArray(attrLocation);
        else
            this._gl.disableVertexAttribArray(attrLocation);
    };
    return ShaderProgram;
}());


// CONCATENATED MODULE: ./engine/misc/collection/fastMap.ts
var FastMap = (function () {
    function FastMap() {
        this._keys = [];
        this._values = [];
    }
    FastMap.prototype.put = function (key, value) {
        var index = this._keys.indexOf(key);
        if (index === -1) {
            this._keys.push(key);
            this._values.push(value);
        }
        else {
            this._values[index] = value;
        }
    };
    FastMap.prototype.get = function (key) {
        var index = this._keys.indexOf(key);
        if (index === -1)
            return undefined;
        return this._values[index];
    };
    FastMap.prototype.has = function (key) {
        var index = this._keys.indexOf(key);
        return index > -1;
    };
    FastMap.prototype.remove = function (key) {
        var index = this._keys.indexOf(key);
        if (index === -1)
            return;
        this._keys.splice(index, 1);
        this._values.splice(index, 1);
    };
    FastMap.prototype.getKeys = function () {
        return this._keys;
    };
    FastMap.prototype.getValues = function () {
        return this._values;
    };
    FastMap.prototype.size = function () {
        return this._keys.length;
    };
    return FastMap;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/programs/abstract/abstractDrawer.ts



var abstractDrawer_AbstractDrawer = (function () {
    function AbstractDrawer(gl) {
        this.uniformCache = new FastMap();
        this.texturesToBind = { length: 0, texturesInfo: [] };
        this.gl = gl;
    }
    AbstractDrawer.unbindLastInstance = function () {
        if (this.currentInstance !== undefined)
            this.currentInstance.unbind();
    };
    AbstractDrawer.prototype.destroy = function () {
        if (this.bufferInfo)
            this.bufferInfo.destroy();
        if (this.program !== undefined)
            this.program.destroy();
    };
    AbstractDrawer.prototype.setUniform = function (name, value) {
        if ( true && !name) {
            console.trace();
            throw new debugError_DebugError("can not set uniform with value " + value + ": name is not provided");
        }
        if ( true && value === null || value === undefined) {
            console.trace();
            throw new debugError_DebugError("can not set uniform with name " + name + " and value " + value);
        }
        if (this.uniformCache.has(name) && Object(object["c" /* isEqual */])(this.uniformCache.get(name).value, value)) {
            return;
        }
        if (Object(object["a" /* isArray */])(value)) {
            if (!this.uniformCache.has(name)) {
                this.uniformCache.put(name, { value: new Float32Array(value.length), dirty: true });
            }
            var uniformInCache = this.uniformCache.get(name);
            var arr = uniformInCache.value;
            arr.set(value);
            uniformInCache.dirty = true;
        }
        else {
            this.uniformCache.put(name, { value: value, dirty: true });
        }
    };
    AbstractDrawer.prototype.attachTexture = function (uniformName, texture) {
        this.texturesToBind.texturesInfo[this.texturesToBind.length] =
            this.texturesToBind.texturesInfo[this.texturesToBind.length] || { uniformName: undefined, texture: undefined };
        this.texturesToBind.texturesInfo[this.texturesToBind.length].uniformName = uniformName;
        this.texturesToBind.texturesInfo[this.texturesToBind.length].texture = texture;
        this.texturesToBind.length++;
    };
    AbstractDrawer.prototype.getAttachedTextureAt = function (i) {
        if ( true && i > this.texturesToBind.length - 1)
            throw new debugError_DebugError("can not find bound texture: out of range: index:" + i + ", length:" + this.texturesToBind.length);
        return this.texturesToBind.texturesInfo[i].texture;
    };
    AbstractDrawer.prototype.setUniformsFromMap = function (batch) {
        var keys = batch.getKeys();
        var values = batch.getValues();
        for (var i = 0; i < keys.length; i++) {
            this.setUniform(keys[i], values[i]);
        }
    };
    AbstractDrawer.prototype.draw = function () {
        this.bind();
        var keys = this.uniformCache.getKeys();
        var values = this.uniformCache.getValues();
        for (var i = 0, length = keys.length; i < length; i++) {
            var v = values[i];
            if (!v.dirty)
                continue;
            this._setUniform(keys[i], v.value);
            v.dirty = false;
        }
        for (var i = 0, max = this.texturesToBind.length; i < max; i++) {
            var t = this.texturesToBind.texturesInfo[i];
            t.texture.bind(t.uniformName, i, this.program);
        }
        this.texturesToBind.length = 0;
        this.drawElements();
    };
    AbstractDrawer.prototype.bind = function () {
        var _a;
        if ( true && this.program === undefined) {
            console.error(this);
            throw new debugError_DebugError("can not init drawer: initProgram method must be invoked!");
        }
        if (AbstractDrawer.currentInstance === this) {
            return;
        }
        (_a = AbstractDrawer.currentInstance) === null || _a === void 0 ? void 0 : _a.unbind();
        AbstractDrawer.currentInstance = this;
        this.bufferInfo.bind(this.program);
    };
    AbstractDrawer.prototype.unbind = function () {
        this.bufferInfo.unbind(this.program);
        AbstractDrawer.currentInstance = undefined;
    };
    AbstractDrawer.prototype.drawElements = function () {
        this.bufferInfo.draw();
    };
    AbstractDrawer.prototype._setUniform = function (name, value) {
        this.program.setUniform(name, value);
    };
    return AbstractDrawer;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/vertexBuffer.ts

var vertexBuffer_VertexBuffer = (function () {
    function VertexBuffer(_gl) {
        this._gl = _gl;
        this.bufferItemSize = 0;
        this.bufferItemType = 0;
        this.dataLength = 0;
        if ( true && !_gl)
            throw new debugError_DebugError("can not create VertexBuffer, gl context not passed to constructor, expected: VertexBuffer(gl)");
        this.buffer = _gl.createBuffer();
        if ( true && !this.buffer)
            throw new debugError_DebugError("can not allocate memory for vertex buffer");
    }
    VertexBuffer.prototype.setData = function (bufferData, itemType, itemSize) {
        if (true) {
            if (!bufferData)
                throw new debugError_DebugError('can not set data to vertex buffer: bufferData is not specified');
            if (!itemType)
                throw new debugError_DebugError('can not set data to vertex buffer: itemType is not specified');
            if (!itemSize)
                throw new debugError_DebugError('can not set data to vertex buffer: itemSize is not specified');
        }
        var gl = this._gl;
        gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(bufferData), gl.STATIC_DRAW);
        gl.bindBuffer(gl.ARRAY_BUFFER, null);
        this.bufferItemSize = itemSize;
        this.bufferItemType = itemType;
        this.dataLength = bufferData.length;
    };
    VertexBuffer.prototype.setAttrName = function (attrName) {
        if ( true && !attrName)
            throw new debugError_DebugError("attrName not provided");
        this.attrName = attrName;
    };
    VertexBuffer.prototype.bind = function (program) {
        if ( true && !program)
            throw new debugError_DebugError("can not bind VertexBuffer, program is not specified");
        if ( true && !this.attrName)
            throw new debugError_DebugError("can not bind VertexBuffer, attribute name is not specified");
        program.bindBuffer(this, this.attrName);
    };
    VertexBuffer.prototype.unbind = function () {
        this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
    };
    VertexBuffer.prototype.destroy = function () {
        this._gl.deleteBuffer(this.buffer);
    };
    VertexBuffer.prototype.getGlBuffer = function () {
        return this.buffer;
    };
    VertexBuffer.prototype.getItemSize = function () {
        return this.bufferItemSize;
    };
    VertexBuffer.prototype.getItemType = function () {
        return this.bufferItemType;
    };
    VertexBuffer.prototype.getBufferLength = function () {
        return this.dataLength;
    };
    return VertexBuffer;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/indexBuffer.ts

var indexBuffer_IndexBuffer = (function () {
    function IndexBuffer(_gl) {
        this._gl = _gl;
        if ( true && !_gl)
            throw new debugError_DebugError("can not create IndexBuffer, gl context not passed to constructor, expected: IndexBuffer(gl)");
        this._buffer = _gl.createBuffer();
        if ( true && !this._buffer)
            throw new debugError_DebugError("can not allocate memory for index buffer");
    }
    IndexBuffer.prototype.setData = function (bufferData) {
        if (true) {
            if (!bufferData)
                throw new debugError_DebugError('can not set data to buffer: bufferData not specified');
        }
        var gl = this._gl;
        this._dataLength = bufferData.length;
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(bufferData), gl.STATIC_DRAW);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
    };
    IndexBuffer.prototype.getGlBuffer = function () {
        return this._buffer;
    };
    IndexBuffer.prototype.bind = function () {
        this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, this._buffer);
    };
    IndexBuffer.prototype.unbind = function () {
        this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
    };
    IndexBuffer.prototype.destroy = function () {
        this._gl.deleteBuffer(this._buffer);
    };
    IndexBuffer.prototype.getBufferLength = function () {
        return this._dataLength;
    };
    return IndexBuffer;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/debug/debugUtil.ts
var debugUtil;
(function (debugUtil) {
    var map;
    debugUtil.glEnumToString = function (gl, glEnum) {
        if (!map && true) {
            map = {};
            var keymap = gl;
            for (var k in keymap) {
                if (isFinite(keymap[k]))
                    map[keymap[k]] = k;
            }
        }
        return map[glEnum];
    };
})(debugUtil || (debugUtil = {}));

// CONCATENATED MODULE: ./engine/renderer/webGl/base/bufferInfo.ts




var glEnumToString = debugUtil.glEnumToString;
var DRAW_METHOD;
(function (DRAW_METHOD) {
    DRAW_METHOD[DRAW_METHOD["LINE_STRIP"] = 0] = "LINE_STRIP";
    DRAW_METHOD[DRAW_METHOD["TRIANGLE_FAN"] = 1] = "TRIANGLE_FAN";
    DRAW_METHOD[DRAW_METHOD["TRIANGLE_STRIP"] = 2] = "TRIANGLE_STRIP";
    DRAW_METHOD[DRAW_METHOD["TRIANGLES"] = 3] = "TRIANGLES";
    DRAW_METHOD[DRAW_METHOD["LINES"] = 4] = "LINES";
    DRAW_METHOD[DRAW_METHOD["LINE_LOOP"] = 5] = "LINE_LOOP";
})(DRAW_METHOD || (DRAW_METHOD = {}));
var drawMethodToGlEnum = function (gl, m) {
    switch (m) {
        case DRAW_METHOD.LINE_STRIP:
            return gl.LINE_STRIP;
        case DRAW_METHOD.TRIANGLE_FAN:
            return gl.TRIANGLE_FAN;
        case DRAW_METHOD.TRIANGLE_STRIP:
            return gl.TRIANGLE_STRIP;
        case DRAW_METHOD.TRIANGLES:
            return gl.TRIANGLES;
        case DRAW_METHOD.LINES:
            return gl.LINES;
        case DRAW_METHOD.LINE_LOOP:
            return gl.LINE_LOOP;
    }
    if (true) {
        throw new debugError_DebugError("unknown drawMethod enum value: " + m);
    }
};
var bufferInfo_BufferInfo = (function () {
    function BufferInfo(gl, description) {
        this.numOfElementsToDraw = 0;
        this.gl = gl;
        if ( true && description.drawMethod === undefined)
            throw new debugError_DebugError("can not create BufferInfo: drawMethod not defined");
        this.drawMethod = drawMethodToGlEnum(gl, description.drawMethod);
        if ( true && !description.posVertexInfo)
            throw new debugError_DebugError("can not create BufferInfo: posVertexInfo is mandatory");
        this.posVertexBuffer = new vertexBuffer_VertexBuffer(gl);
        this.posVertexBuffer.setData(description.posVertexInfo.array, description.posVertexInfo.type, description.posVertexInfo.size);
        this.posVertexBuffer.setAttrName(description.posVertexInfo.attrName);
        if (description.posIndexInfo) {
            this.posIndexBuffer = new indexBuffer_IndexBuffer(gl);
            this.posIndexBuffer.setData(description.posIndexInfo.array);
        }
        else
            this.numOfElementsToDraw = this._getNumOfElementsToDraw(this.drawMethod);
        if (description.texVertexInfo) {
            this.texVertexBuffer = new vertexBuffer_VertexBuffer(gl);
            this.texVertexBuffer.setData(description.texVertexInfo.array, description.texVertexInfo.type, description.texVertexInfo.size);
            this.texVertexBuffer.setAttrName(description.texVertexInfo.attrName);
        }
        if (description.normalInfo) {
            this.normalBuffer = new vertexBuffer_VertexBuffer(gl);
            this.normalBuffer.setData(description.normalInfo.array, description.normalInfo.type, description.normalInfo.size);
            this.normalBuffer.setAttrName(description.normalInfo.attrName);
        }
    }
    BufferInfo.prototype.bind = function (program) {
        program.bind();
        if (this.posIndexBuffer !== undefined)
            this.posIndexBuffer.bind();
        if (this.posVertexBuffer !== undefined)
            this.posVertexBuffer.bind(program);
        if (this.texVertexBuffer !== undefined)
            this.texVertexBuffer.bind(program);
        if (this.normalBuffer !== undefined)
            this.normalBuffer.bind(program);
    };
    BufferInfo.prototype.unbind = function (program) {
        program.unbind();
        if (this.posIndexBuffer !== undefined)
            this.posIndexBuffer.unbind();
        if (this.posVertexBuffer !== undefined)
            this.posVertexBuffer.unbind();
        if (this.texVertexBuffer !== undefined)
            this.texVertexBuffer.unbind();
        if (this.normalBuffer !== undefined)
            this.normalBuffer.unbind();
    };
    BufferInfo.prototype.destroy = function () {
        if (this.posVertexBuffer !== undefined)
            this.posVertexBuffer.destroy();
        if (this.posIndexBuffer !== undefined)
            this.posIndexBuffer.destroy();
        if (this.texVertexBuffer !== undefined)
            this.texVertexBuffer.destroy();
        if (this.normalBuffer !== undefined)
            this.normalBuffer.destroy();
    };
    BufferInfo.prototype.draw = function () {
        if (this.posIndexBuffer !== undefined) {
            this.gl.drawElements(this.drawMethod, this.posIndexBuffer.getBufferLength(), this.gl.UNSIGNED_SHORT, 0);
        }
        else {
            this.gl.drawArrays(this.drawMethod, 0, this.numOfElementsToDraw);
        }
    };
    BufferInfo.prototype._getNumOfElementsToDraw = function (drawMethod) {
        switch (drawMethod) {
            case this.gl.LINE_STRIP:
            case this.gl.TRIANGLE_FAN:
                return this.posVertexBuffer.getBufferLength() / 2;
            case this.gl.TRIANGLE_STRIP:
                return this.posVertexBuffer.getBufferLength() / 3;
            case this.gl.TRIANGLES:
                return this.posVertexBuffer.getBufferLength() / this.posVertexBuffer.getItemSize();
            default:
                throw new debugError_DebugError("unknown draw method: " + drawMethod + " (" + glEnumToString(this.gl, drawMethod) + ")");
        }
    };
    return BufferInfo;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/primitives/abstractPrimitive.ts
var AbstractPrimitive = (function () {
    function AbstractPrimitive() {
    }
    return AbstractPrimitive;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/primitives/plane.ts


var plane_Plane = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Plane, _super);
    function Plane() {
        var _this = _super.call(this) || this;
        _this.vertexArr = [
            0, 0,
            0, 1,
            1, 0,
            1, 1
        ];
        _this.indexArr = [0, 1, 2, 3];
        _this.texCoordArr = [
            0, 0,
            0, 1,
            1, 0,
            1, 1
        ];
        return _this;
    }
    return Plane;
}(AbstractPrimitive));


// CONCATENATED MODULE: ./engine/renderer/webGl/shaders/generators/shaderGenerator.ts

var shaderGenerator_ShaderGenerator = (function () {
    function ShaderGenerator() {
        this._vertexUniforms = [];
        this._fragmentUniforms = [];
        this._attributes = [];
        this._varyings = [];
        this._appendedFragCodeBlocks = [];
        this._appendedVertexCodeBlocks = [];
        this._prependedVertexCodeBlocks = [];
        this._prependedFragCodeBlocks = [];
        this._vertexMainFn = '';
        this._fragmentMainFn = '';
    }
    ShaderGenerator.prototype.addVertexUniform = function (type, name) {
        this._vertexUniforms.push({ type: type, name: name });
        return normalizeUniformName(name);
    };
    ShaderGenerator.prototype.addScalarFragmentUniform = function (type, name, extractArrayName) {
        if (extractArrayName === void 0) { extractArrayName = false; }
        return this._addFragmentUniform(type, name, extractArrayName);
    };
    ShaderGenerator.prototype.addStructFragmentUniform = function (strucName, uniformName, extractArrayName) {
        if (extractArrayName === void 0) { extractArrayName = false; }
        return this._addFragmentUniform(strucName, uniformName, extractArrayName);
    };
    ShaderGenerator.prototype.addAttribute = function (type, name) {
        this._attributes.push({ type: type, name: name });
        return normalizeUniformName(name);
    };
    ShaderGenerator.prototype.addVarying = function (type, name) {
        this._varyings.push({ type: type, name: name });
    };
    ShaderGenerator.prototype.appendVertexCodeBlock = function (code) {
        this._appendedVertexCodeBlocks.push(code);
    };
    ShaderGenerator.prototype.appendFragmentCodeBlock = function (code) {
        this._appendedFragCodeBlocks.push(code);
    };
    ShaderGenerator.prototype.prependVertexCodeBlock = function (code) {
        this._prependedVertexCodeBlocks.push(code);
    };
    ShaderGenerator.prototype.prependFragmentCodeBlock = function (code) {
        this._prependedFragCodeBlocks.push(code);
    };
    ShaderGenerator.prototype.setVertexMainFn = function (fnCode) {
        this._vertexMainFn = fnCode;
    };
    ShaderGenerator.prototype.setFragmentMainFn = function (fnCode) {
        this._fragmentMainFn = fnCode;
    };
    ShaderGenerator.prototype.getVertexSource = function () {
        return ("\nprecision mediump float;\n\n" + this._prependedVertexCodeBlocks.map(function (v) { return "" + v; }).join('\n') + "\n\n" + this._vertexUniforms.map(function (u) { return "uniform   " + u.type + " " + u.name + ";"; }).join('\n') + "\n" + this._attributes.map(function (u) { return "attribute " + u.type + " " + u.name + ";"; }).join('\n') + "\n" + this._varyings.map(function (u) { return "varying   " + u.type + " " + u.name + ";"; }).join('\n') + "\n" + this._appendedVertexCodeBlocks.map(function (v) { return "" + v; }).join('\n') + "\n\n" + this._vertexMainFn);
    };
    ShaderGenerator.prototype.getFragmentSource = function () {
        return ("\nprecision mediump float;\n\n" + this._prependedFragCodeBlocks.map(function (v) { return "" + v; }).join('\n') + "\n\n" + this._fragmentUniforms.map(function (u) { return "uniform " + u.type + " " + u.name + ";"; }).join('\n') + "\n" + this._varyings.map(function (u) { return "varying " + u.type + " " + u.name + ";"; }).join('\n') + "\n" + this._appendedFragCodeBlocks.map(function (v) { return "" + v; }).join('\n') + "\n\n" + this._fragmentMainFn + "\n");
    };
    ShaderGenerator.prototype.debug = function () {
        if (false)
            {}
        console.log('// *** vertex shader source ***');
        console.log(this.getVertexSource());
        console.log('// *** fragment shader source ***');
        console.log(this.getFragmentSource());
    };
    ShaderGenerator.prototype._addFragmentUniform = function (type, name, extractArrayName) {
        if (extractArrayName === void 0) { extractArrayName = false; }
        this._fragmentUniforms.push({ type: type, name: name });
        name = normalizeUniformName(name);
        if (extractArrayName)
            name = name.split('[')[0];
        return name;
    };
    return ShaderGenerator;
}());


// EXTERNAL MODULE: ./engine/renderer/webGl/programs/impl/base/shape/shape.fragment.glsl
var shape_fragment = __webpack_require__(3);

// EXTERNAL MODULE: ./engine/renderer/webGl/programs/impl/base/shape/fragment-structures.glsl
var fragment_structures = __webpack_require__(2);

// CONCATENATED MODULE: ./engine/renderable/impl/fill/abstract/abstractGradient.ts



var abstractGradient_AbstractGradient = (function () {
    function AbstractGradient() {
        this._points = [];
    }
    AbstractGradient.prototype.set = function (g) {
        this._points = Object(tslib_es6["e" /* __spreadArrays */])(g._points.map(function (it) { return (Object(tslib_es6["a" /* __assign */])({}, it)); }));
    };
    AbstractGradient.prototype.setColorAtPosition = function (position, color) {
        if ( true && this._points.length > AbstractGradient.MAX_NUM_OF_GRADIENT_POINTS) {
            throw new debugError_DebugError("Maxinum number of gradient points is " + AbstractGradient.MAX_NUM_OF_GRADIENT_POINTS + ",\n                to use more points change AbstractGradient.MAX_NUM_OF_GRADIENT_POINTS before Game instance creation");
        }
        this._points.push({ color: color_Color.from(color), value: position });
    };
    AbstractGradient.prototype.setUniforms = function (sd) {
        for (var i = 0; i < AbstractGradient.MAX_NUM_OF_GRADIENT_POINTS; i++) {
            var possibleColorPoint = this._points[i];
            sd.setUniform("u_fillGradientPoints[" + i + "].pointActive", possibleColorPoint !== undefined);
            sd.setUniform("u_fillGradientPoints[" + i + "].value", possibleColorPoint ? possibleColorPoint.value : 0);
            sd.setUniform("u_fillGradientPoints[" + i + "].r", possibleColorPoint ? possibleColorPoint.color.r / 255 : 0);
            sd.setUniform("u_fillGradientPoints[" + i + "].g", possibleColorPoint ? possibleColorPoint.color.g / 255 : 0);
            sd.setUniform("u_fillGradientPoints[" + i + "].b", possibleColorPoint ? possibleColorPoint.color.b / 255 : 0);
            sd.setUniform("u_fillGradientPoints[" + i + "].a", possibleColorPoint ? possibleColorPoint.color.a / 255 : 0);
        }
    };
    AbstractGradient.MAX_NUM_OF_GRADIENT_POINTS = 4;
    return AbstractGradient;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/programs/impl/base/shape/shapeDrawer.ts












var SHAPE_TYPE;
(function (SHAPE_TYPE) {
    SHAPE_TYPE[SHAPE_TYPE["ELLIPSE"] = 0] = "ELLIPSE";
    SHAPE_TYPE[SHAPE_TYPE["RECT"] = 1] = "RECT";
})(SHAPE_TYPE || (SHAPE_TYPE = {}));
var FILL_TYPE;
(function (FILL_TYPE) {
    FILL_TYPE[FILL_TYPE["COLOR"] = 0] = "COLOR";
    FILL_TYPE[FILL_TYPE["TEXTURE"] = 1] = "TEXTURE";
    FILL_TYPE[FILL_TYPE["LINEAR_GRADIENT"] = 2] = "LINEAR_GRADIENT";
    FILL_TYPE[FILL_TYPE["RADIAL_GRADIENT"] = 3] = "RADIAL_GRADIENT";
})(FILL_TYPE || (FILL_TYPE = {}));
var shapeDrawer_ShapeDrawer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(ShapeDrawer, _super);
    function ShapeDrawer(gl) {
        var _this = _super.call(this, gl) || this;
        var gen = new shaderGenerator_ShaderGenerator();
        gen.setVertexMainFn("void main(){\nv_position = a_position;\ngl_Position = u_vertexMatrix * a_position;\n}");
        _this.u_vertexMatrix = gen.addVertexUniform(GL_TYPE.FLOAT_MAT4, 'u_vertexMatrix');
        _this.a_position = gen.addAttribute(GL_TYPE.FLOAT_VEC4, 'a_position');
        gen.addVarying(GL_TYPE.FLOAT_VEC4, 'v_position');
        gen.prependFragmentCodeBlock(Object(object["h" /* parametrizeString */])(fragment_structures, {
            __STRETCH_MODE_STRETCH__: STRETCH_MODE.STRETCH,
            __STRETCH_MODE_REPEAT__: STRETCH_MODE.REPEAT,
            __FILL_TYPE_COLOR__: FILL_TYPE.COLOR,
            __FILL_TYPE_TEXTURE__: FILL_TYPE.TEXTURE,
            __FILL_TYPE_LINEAR_GRADIENT__: FILL_TYPE.LINEAR_GRADIENT,
            __FILL_TYPE_RADIAL_GRADIENT__: FILL_TYPE.RADIAL_GRADIENT,
            __SHAPE_TYPE_ELLIPSE__: SHAPE_TYPE.ELLIPSE,
            __SHAPE_TYPE_RECT__: SHAPE_TYPE.RECT,
            __PI__: Math.PI,
            __MAX_NUM_OF_GRADIENT_POINTS__: abstractGradient_AbstractGradient.MAX_NUM_OF_GRADIENT_POINTS,
        }));
        _this.u_lineWidth = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_lineWidth');
        _this.u_rx = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_rx');
        _this.u_ry = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_ry');
        _this.u_width = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_width');
        _this.u_height = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_height');
        _this.u_rectOffsetTop = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_rectOffsetTop');
        _this.u_rectOffsetLeft = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_rectOffsetLeft');
        _this.u_borderRadius = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_borderRadius');
        _this.u_color = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC4, 'u_color');
        _this.u_alpha = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_alpha');
        _this.u_fillColor = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC4, 'u_fillColor');
        gen.addStructFragmentUniform("GradientPoint", "u_fillGradientPoints[MAX_NUM_OF_GRADIENT_POINTS]");
        _this.u_fillGradientPoints = 'u_fillGradientPoints';
        _this.u_fillGradientAngle = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_fillGradientAngle');
        _this.u_radialGradientCenterX = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_radialGradientCenterX');
        _this.u_radialGradientCenterY = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_radialGradientCenterY');
        _this.u_texRect = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC4, 'u_texRect');
        _this.u_texOffset = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC2, 'u_texOffset');
        gen.addScalarFragmentUniform(GL_TYPE.SAMPLER_2D, 'texture');
        _this.u_shapeType = gen.addScalarFragmentUniform(GL_TYPE.INT, 'u_shapeType');
        _this.u_fillType = gen.addScalarFragmentUniform(GL_TYPE.INT, 'u_fillType');
        _this.u_arcAngleFrom = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_arcAngleFrom');
        _this.u_arcAngleTo = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_arcAngleTo');
        _this.u_repeatFactor = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC2, 'u_repeatFactor');
        _this.u_stretchMode = gen.addScalarFragmentUniform(GL_TYPE.INT, 'u_stretchMode');
        _this.u_anticlockwise = gen.addScalarFragmentUniform(GL_TYPE.BOOL, 'u_anticlockwise');
        gen.setFragmentMainFn(shape_fragment);
        _this.program = new shaderProgram_ShaderProgram(gl, gen.getVertexSource(), gen.getFragmentSource());
        _this.primitive = new plane_Plane();
        _this.bufferInfo = new bufferInfo_BufferInfo(gl, {
            posVertexInfo: { array: _this.primitive.vertexArr, type: gl.FLOAT, size: 2, attrName: _this.a_position },
            posIndexInfo: { array: _this.primitive.indexArr },
            drawMethod: DRAW_METHOD.TRIANGLE_STRIP,
        });
        return _this;
    }
    return ShapeDrawer;
}(abstractDrawer_AbstractDrawer));


// CONCATENATED MODULE: ./engine/geometry/mat4Special.ts
if (!Float32Array.prototype.slice) {
    Float32Array.prototype.slice = function (begin, end) {
        this.slicedPortion = this.slicedPortion || [];
        var cnt = 0;
        this.slicedPortion.length = 0;
        for (var i = begin; i < end; i++) {
            this.slicedPortion[cnt++] = this[i];
        }
        return this.slicedPortion;
    };
}
var mat4Special;
(function (mat4Special) {
    mat4Special.matrixTranslationMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r.set(b.slice(0, 12), 0);
        r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + b[12];
        r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + b[13];
        r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + b[14];
        r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + b[15];
    };
    mat4Special.matrixRotationXMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = b[0];
        r[1] = b[1];
        r[2] = b[2];
        r[3] = b[3];
        r[4] = a[5] * b[4] + a[6] * b[8];
        r[5] = a[5] * b[5] + a[6] * b[9];
        r[6] = a[5] * b[6] + a[6] * b[10];
        r[7] = a[5] * b[7] + a[6] * b[11];
        r[8] = a[9] * b[4] + a[10] * b[8];
        r[9] = a[9] * b[5] + a[10] * b[9];
        r[10] = a[9] * b[6] + a[10] * b[10];
        r[11] = a[9] * b[7] + a[10] * b[11];
        r[12] = b[12];
        r[13] = b[13];
        r[14] = b[14];
        r[15] = b[15];
    };
    mat4Special.matrixRotationYMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = a[0] * b[0] + a[2] * b[8];
        r[1] = a[0] * b[1] + a[2] * b[9];
        r[2] = a[0] * b[2] + a[2] * b[10];
        r[3] = a[0] * b[3] + a[2] * b[11];
        r[4] = b[4];
        r[5] = b[5];
        r[6] = b[6];
        r[7] = b[7];
        r[8] = a[8] * b[0] + a[10] * b[8];
        r[9] = a[8] * b[1] + a[10] * b[9];
        r[10] = a[8] * b[2] + a[10] * b[10];
        r[11] = a[8] * b[3] + a[10] * b[11];
        r[12] = b[12];
        r[13] = b[13];
        r[14] = b[14];
        r[15] = b[15];
    };
    mat4Special.matrixRotationZMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = a[0] * b[0] + a[1] * b[4];
        r[1] = a[0] * b[1] + a[1] * b[5];
        r[2] = a[0] * b[2] + a[1] * b[6];
        r[3] = a[0] * b[3] + a[1] * b[7];
        r[4] = a[4] * b[0] + a[5] * b[4];
        r[5] = a[4] * b[1] + a[5] * b[5];
        r[6] = a[4] * b[2] + a[5] * b[6];
        r[7] = a[4] * b[3] + a[5] * b[7];
        r.set(b.slice(8, 16), 8);
    };
    mat4Special.matrixScaleMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = a[0] * b[0];
        r[1] = a[0] * b[1];
        r[2] = a[0] * b[2];
        r[3] = a[0] * b[3];
        r[4] = a[5] * b[4];
        r[5] = a[5] * b[5];
        r[6] = a[5] * b[6];
        r[7] = a[5] * b[7];
        r[8] = a[10] * b[8];
        r[9] = a[10] * b[9];
        r[10] = a[10] * b[10];
        r[11] = a[10] * b[11];
        r[12] = b[12];
        r[13] = b[13];
        r[14] = b[14];
        r[15] = b[15];
    };
    mat4Special.matrixSkewXMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = b[0];
        r[1] = b[1];
        r[2] = b[2];
        r[3] = b[3];
        r[4] = a[4] * b[0] + b[4];
        r[5] = a[4] * b[1] + b[5];
        r[6] = a[4] * b[2] + b[6];
        r[7] = a[4] * b[3] + b[7];
        r.set(b.slice(8, 16), 8);
    };
    mat4Special.matrixSkewYMultiply = function (out, aHolder, bHolder) {
        var r = out.mat16;
        var a = aHolder.mat16;
        var b = bHolder.mat16;
        r[0] = b[0] + a[1] * b[4];
        r[1] = b[1] + a[1] * b[5];
        r[2] = b[2] + a[1] * b[6];
        r[3] = b[3] + a[1] * b[7];
        r.set(b.slice(4, 16), 4);
    };
})(mat4Special || (mat4Special = {}));

// CONCATENATED MODULE: ./engine/renderer/webGl/base/matrixStack.ts

var matrixStack_Mat16Holder = mat4_mat4.Mat16Holder;


var matrixStack_MatrixStack = (function () {
    function MatrixStack() {
        this._stack = new stack_Stack();
        this.restore();
    }
    MatrixStack.prototype.restore = function () {
        if (this._stack.isEmpty())
            this.setIdentity();
        else {
            var last = this._stack.pop();
            last.release();
        }
    };
    MatrixStack.prototype.save = function () {
        var copy = matrixStack_Mat16Holder.fromPool();
        copy.fromMat16(this.getCurrentValue().mat16);
        this._stack.push(copy);
    };
    MatrixStack.prototype.getCurrentValue = function () {
        return this._stack.getLast();
    };
    MatrixStack.prototype.setCurrentValue = function (m) {
        return this._stack.replaceLast(m);
    };
    MatrixStack.prototype.translate = function (x, y, z) {
        if (z === void 0) { z = 0; }
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeTranslation(t, x, y, z);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixTranslationMultiply(result, t, m);
        this.setCurrentValue(result);
        t.release();
        m.release();
        return this;
    };
    MatrixStack.prototype.setMatrixValues = function (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        this.getCurrentValue().set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
        return this;
    };
    MatrixStack.prototype.translateByMatrixValues = function (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        var t = matrixStack_Mat16Holder.fromPool();
        t.set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.matrixMultiply(result, t, m);
        this.setCurrentValue(result);
        t.release();
        m.release();
        return this;
    };
    MatrixStack.prototype.skewX = function (angle) {
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeXSkew(t, angle);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixSkewXMultiply(result, t, m);
        this.setCurrentValue(result);
        t.release();
        m.release();
        return this;
    };
    MatrixStack.prototype.skewY = function (angle) {
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeYSkew(t, angle);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixSkewYMultiply(result, t, m);
        this.setCurrentValue(result);
        t.release();
        m.release();
        return this;
    };
    MatrixStack.prototype.rotateX = function (angleInRadians) {
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeXRotation(t, angleInRadians);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixRotationXMultiply(result, t, m);
        this.setCurrentValue(result);
        m.release();
        t.release();
        return this;
    };
    MatrixStack.prototype.rotateY = function (angleInRadians) {
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeYRotation(t, angleInRadians);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixRotationYMultiply(result, t, m);
        this.setCurrentValue(result);
        m.release();
        t.release();
        return this;
    };
    MatrixStack.prototype.rotateZ = function (angleInRadians) {
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeZRotation(t, angleInRadians);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixRotationZMultiply(result, t, m);
        this.setCurrentValue(result);
        m.release();
        t.release();
        return this;
    };
    MatrixStack.prototype.scale = function (x, y, z) {
        if (z === void 0) { z = 1; }
        var t = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeScale(t, x, y, z);
        var m = this.getCurrentValue();
        var result = matrixStack_Mat16Holder.fromPool();
        mat4Special.matrixScaleMultiply(result, t, m);
        this.setCurrentValue(result);
        t.release();
        m.release();
        return this;
    };
    MatrixStack.prototype.resetTransform = function () {
        this.getCurrentValue().release();
        var identity = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeIdentity(identity);
        this.setCurrentValue(identity);
        return this;
    };
    MatrixStack.prototype.rotationReset = function () {
        var m = this.getCurrentValue();
        mat4_mat4.makeRotationReset(m);
    };
    MatrixStack.prototype.release = function () {
        for (var i = 0, max = this._stack.size(); i < max; i++) {
            this._stack.getAt(i).release();
        }
        return this;
    };
    MatrixStack.prototype.setIdentity = function () {
        var ident = matrixStack_Mat16Holder.fromPool();
        mat4_mat4.makeIdentity(ident);
        this._stack.push(ident);
    };
    return MatrixStack;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/abstract/abstractTexture.ts


var isPowerOf2 = function (value) {
    return (value & (value - 1)) === 0;
};
var INTERPOLATION_MODE;
(function (INTERPOLATION_MODE) {
    INTERPOLATION_MODE[INTERPOLATION_MODE["NEAREST"] = 0] = "NEAREST";
    INTERPOLATION_MODE[INTERPOLATION_MODE["LINEAR"] = 1] = "LINEAR";
})(INTERPOLATION_MODE || (INTERPOLATION_MODE = {}));
var abstractTexture_AbstractTexture = (function () {
    function AbstractTexture(gl) {
        this.gl = gl;
        this.size = new size_Size(0, 0);
        this.destroyed = false;
        if (true) {
            if (!gl)
                throw new debugError_DebugError("can not create Texture, gl context not passed to constructor, expected: Texture(gl)");
            if (!AbstractTexture._MAX_TEXTURE_IMAGE_UNITS) {
                AbstractTexture._MAX_TEXTURE_IMAGE_UNITS = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
                if ( true && !AbstractTexture._MAX_TEXTURE_IMAGE_UNITS)
                    throw new debugError_DebugError("Can not obtain MAX_TEXTURE_IMAGE_UNITS value");
            }
        }
        this.tex = gl.createTexture();
        if ( true && !this.tex)
            throw new debugError_DebugError("can not allocate memory for texture");
    }
    AbstractTexture.destroyAll = function () {
        for (var i = 0; i < AbstractTexture._instances.length; i++) {
            AbstractTexture._instances[i].destroy();
        }
        AbstractTexture.currentBindTextureAt = {};
    };
    AbstractTexture.prototype.bind = function (name, i, program) {
        if (true) {
            if (!name) {
                console.error(this);
                throw new debugError_DebugError("can not bind texture: uniform name was not provided");
            }
            if (i > AbstractTexture._MAX_TEXTURE_IMAGE_UNITS - 1) {
                console.error(this);
                throw new debugError_DebugError("can not bind texture with index " + i + ". Max supported value by device is " + AbstractTexture._MAX_TEXTURE_IMAGE_UNITS);
            }
            if (this.destroyed) {
                console.error(this);
                throw new debugError_DebugError("can not bind destroyed texture");
            }
        }
        program.setUniform(name, i);
        if (AbstractTexture.currentBindTextureAt[i] === this)
            return;
        var gl = this.gl;
        gl.activeTexture(gl.TEXTURE0 + i);
        gl.bindTexture(this.samplerType, this.tex);
        AbstractTexture.currentBindTextureAt[i] = this;
    };
    AbstractTexture.prototype.unbind = function (i) {
        if (i === void 0) { i = 0; }
        var gl = this.gl;
        gl.activeTexture(gl.TEXTURE0 + i);
        gl.bindTexture(gl.TEXTURE_2D, null);
        delete AbstractTexture.currentBindTextureAt[i];
    };
    AbstractTexture.prototype.destroy = function () {
        this.gl.deleteTexture(this.tex);
        AbstractTexture._instances.splice(AbstractTexture._instances.indexOf(this), 1);
        this.destroyed = true;
    };
    AbstractTexture.prototype.getGlTexture = function () {
        return this.tex;
    };
    AbstractTexture.prototype.setInterpolationMode = function (mode) {
        if (mode === this._interpolationMode)
            return;
        this.beforeOperation();
        var gl = this.gl;
        var glMode;
        switch (mode) {
            case INTERPOLATION_MODE.LINEAR:
                glMode = gl.LINEAR;
                break;
            case INTERPOLATION_MODE.NEAREST:
                glMode = gl.NEAREST;
                break;
            default:
                if (true)
                    throw new debugError_DebugError("unknown interpolation mode " + mode);
                break;
        }
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glMode);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glMode);
        this._interpolationMode = mode;
        this.afterOperation();
    };
    AbstractTexture.prototype.beforeOperation = function () {
        if (this._currentTextureAt0 !== undefined)
            return;
        this._currentTextureAt0 = AbstractTexture.currentBindTextureAt[0];
        this.gl.bindTexture(this.gl.TEXTURE_2D, this.tex);
    };
    AbstractTexture.prototype.afterOperation = function () {
        if (this._currentTextureAt0)
            this.gl.bindTexture(this.gl.TEXTURE_2D, this._currentTextureAt0.tex);
        else
            this.gl.bindTexture(this.gl.TEXTURE_2D, null);
        this._currentTextureAt0 = undefined;
    };
    AbstractTexture.prototype.setFilters = function () {
        var gl = this.gl;
        var isPowerOfTwo = isPowerOf2(this.size.width) && isPowerOf2(this.size.height);
        if (isPowerOfTwo) {
            gl.generateMipmap(gl.TEXTURE_2D);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
        }
        else {
            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);
        }
    };
    AbstractTexture.currentBindTextureAt = {};
    AbstractTexture._MAX_TEXTURE_IMAGE_UNITS = 0;
    AbstractTexture._instances = [];
    return AbstractTexture;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/texture.ts




var texture_Texture = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Texture, _super);
    function Texture(gl) {
        var _this = _super.call(this, gl) || this;
        _this.gl = gl;
        _this.samplerType = _this.gl.TEXTURE_2D;
        _this.setRawData(new Uint8Array([0, 255, 0, 255]), 1, 1);
        return _this;
    }
    Texture.prototype.setImage = function (img, size) {
        if (size === void 0) { size = new size_Size(0, 0); }
        var gl = this.gl;
        if (true) {
            if (!(img || size.width || size.height))
                throw new debugError_DebugError("texture.setImage: if image is undefined, width and height must be specified: tex.setImage(null,w,h)");
            var maxSupportedSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
            if ( true && !maxSupportedSize)
                throw new debugError_DebugError("Can not obtain MAX_TEXTURE_SIZE value");
            if (size.width > maxSupportedSize || size.height > maxSupportedSize) {
                throw new debugError_DebugError("can not create texture with size " + size.width + "x" + size.height + ", max supported size is " + maxSupportedSize);
            }
        }
        if (img !== undefined)
            this.size.setWH(img.width, img.height);
        else
            this.size.set(size);
        this.beforeOperation();
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
        if (img) {
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
        }
        else {
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size.width, size.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
        }
        this.setFilters();
        this.setInterpolationMode(INTERPOLATION_MODE.LINEAR);
        this.afterOperation();
    };
    Texture.prototype.toDataArray = function () {
        var gl = this.gl;
        var wxh = this.size.width * this.size.height;
        var fb = gl.createFramebuffer();
        this.beforeOperation();
        gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.tex, 0);
        if ( true && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)
            throw new debugError_DebugError("wrong framebuffer state!");
        var pixels = new Uint8Array(wxh * 4);
        gl.readPixels(0, 0, this.size.width, this.size.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
        this.afterOperation();
        return pixels;
    };
    Texture.prototype.toDataUrl = function () {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = this.size.width;
        canvas.height = this.size.height;
        var imgData = ctx.createImageData(this.size.width, this.size.height);
        imgData.data.set(this.toDataArray());
        ctx.putImageData(imgData, 0, 0);
        return canvas.toDataURL();
    };
    Texture.prototype.setRawData = function (data, width, height, mode) {
        if (mode === void 0) { mode = INTERPOLATION_MODE.LINEAR; }
        if (true) {
            var numOfBytes = width * height * 4;
            if (data.length !== numOfBytes) {
                throw new debugError_DebugError("unexpected Uint8Array length, expected width*height*4 (" + width + "*" + height + "*4=" + numOfBytes + "), but is found " + data.length);
            }
        }
        var gl = this.gl;
        this.beforeOperation();
        this.size.setWH(width, height);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
        this.setFilters();
        this.setInterpolationMode(mode);
        this.afterOperation();
    };
    return Texture;
}(abstractTexture_AbstractTexture));


// CONCATENATED MODULE: ./engine/renderer/common/alphaBlendStack.ts

var alphaBlendStack_AlphaBlendStack = (function () {
    function AlphaBlendStack() {
        this._stack = new stack_Stack();
        this._stack.push(1);
    }
    AlphaBlendStack.prototype.getCurrentValue = function () {
        return this._stack.getLast();
    };
    AlphaBlendStack.prototype.restore = function () {
        if (this._stack.isEmpty())
            this._stack.push(1);
        else
            this._stack.pop();
    };
    AlphaBlendStack.prototype.save = function () {
        var last = this._stack.getLast();
        this._stack.push(last);
    };
    AlphaBlendStack.prototype.mult = function (alpha) {
        this.setCurrentValue(this.getCurrentValue() * alpha);
    };
    AlphaBlendStack.prototype.setCurrentValue = function (v) {
        this._stack.replaceLast(v);
    };
    return AlphaBlendStack;
}());


// CONCATENATED MODULE: ./engine/renderer/abstract/abstractRenderer.ts




var abstractRenderer_AbstractRenderer = (function () {
    function AbstractRenderer(game) {
        this.game = game;
        this.clearBeforeRender = true;
        this.clearColor = color_Color.RGB(0, 0, 0);
        this.viewPortSize = new size_Size();
        this._alphaBlendStack = new alphaBlendStack_AlphaBlendStack();
        this._fullScreenRequested = false;
        this.game = game;
    }
    AbstractRenderer.prototype.requestFullScreen = function () {
        var _this = this;
        var canRequest = this._requestFullScreen();
        if (canRequest) {
            var fn_1 = function () {
                if (_this._fullScreenRequested)
                    _this._requestFullScreen();
                document.body.removeEventListener('click', fn_1);
            };
            document.body.addEventListener('click', fn_1);
        }
    };
    AbstractRenderer.prototype.cancelFullScreen = function () {
        this._fullScreenRequested = false;
        var doc = globalThis.document;
        if (doc.cancelFullScreen !== undefined) {
            (doc).cancelFullScreen();
        }
        else if (doc.mozCancelFullScreen !== undefined) {
            doc.mozCancelFullScreen();
        }
        else if (doc.webkitCancelFullScreen !== undefined) {
            doc.webkitCancelFullScreen();
        }
    };
    AbstractRenderer.prototype.beforeItemStackDraw = function (filters, forceDrawChildrenOnNewSurface) {
        return undefined;
    };
    AbstractRenderer.prototype.afterItemStackDraw = function (stackPointer) { };
    AbstractRenderer.prototype.beforeFrameDraw = function (filters) {
        return undefined;
    };
    AbstractRenderer.prototype.afterFrameDraw = function (stackPointer) { };
    AbstractRenderer.prototype.destroy = function () {
        globalThis.removeEventListener('resize', this.onResize);
    };
    AbstractRenderer.prototype.killObject = function (r) { };
    AbstractRenderer.prototype.saveAlphaBlend = function () {
        this._alphaBlendStack.save();
    };
    AbstractRenderer.prototype.restoreAlphaBlend = function () {
        this._alphaBlendStack.restore();
    };
    AbstractRenderer.prototype.setAlphaBlend = function (alpha) {
        this._alphaBlendStack.mult(alpha);
    };
    AbstractRenderer.prototype.getAlphaBlend = function () {
        return this._alphaBlendStack.getCurrentValue();
    };
    AbstractRenderer.prototype.getHelper = function () {
        return this.rendererHelper;
    };
    AbstractRenderer.prototype.registerResize = function () {
        var _this = this;
        this.onResize();
        globalThis.addEventListener('resize', function () {
            _this.onResize();
            setTimeout(function () { return _this.onResize(); }, 100);
        });
        document.addEventListener('gesturestart', function (e) { return e.preventDefault(); });
        this.container.addEventListener('gesturestart', function (e) { return e.preventDefault(); });
    };
    AbstractRenderer.prototype.onResize = function () {
        var container = this.container;
        var _a = this.getScreenResolution(), innerWidth = _a[0], innerHeight = _a[1];
        if (this.game.scaleStrategy === SCALE_STRATEGY.NO_SCALE)
            return;
        else if (this.game.scaleStrategy === SCALE_STRATEGY.STRETCH) {
            container.style.width = innerWidth + "px";
            container.style.height = innerHeight + "px";
            this.viewPortSize.setWH(innerWidth, innerHeight);
            this.game.scale.setXY(innerWidth / this.game.size.width, innerHeight / this.game.size.height);
            this.game.pos.setXY(0);
        }
        else {
            var canvasRatio = this.game.size.height / this.game.size.width;
            var windowRatio = innerHeight / innerWidth;
            var width = void 0;
            var height = void 0;
            if (windowRatio < canvasRatio) {
                height = innerHeight;
                width = height / canvasRatio;
            }
            else {
                width = innerWidth;
                height = width * canvasRatio;
            }
            this.game.scale.setXY(width / this.game.size.width, height / this.game.size.height);
            this.game.pos.setXY((innerWidth - width) / 2, (innerHeight - height) / 2);
            this.container.style.width = width + 'px';
            this.container.style.height = height + 'px';
            this.container.style.marginTop = this.game.pos.y + "px";
            this.viewPortSize.setWH(width, height);
        }
    };
    AbstractRenderer.prototype.getScreenResolution = function () {
        return [globalThis.innerWidth, globalThis.innerHeight];
    };
    AbstractRenderer.prototype._requestFullScreen = function () {
        var element = this.container;
        this._fullScreenRequested = true;
        var canRequest = false;
        if (element.requestFullScreen) {
            element.requestFullScreen();
            canRequest = true;
        }
        else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
            canRequest = true;
        }
        else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen();
            canRequest = true;
        }
        return canRequest;
    };
    return AbstractRenderer;
}());


// CONCATENATED MODULE: ./engine/renderer/abstract/abstractCanvasRenderer.ts


var abstractCanvasRenderer_AbstractCanvasRenderer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(AbstractCanvasRenderer, _super);
    function AbstractCanvasRenderer(game) {
        var _this = _super.call(this, game) || this;
        var canvasElement = document.createElement('canvas');
        if (game.rootContainerElement !== undefined) {
            game.rootContainerElement.appendChild(canvasElement);
        }
        else {
            document.body.appendChild(canvasElement);
        }
        canvasElement.setAttribute('width', game.size.width.toString());
        canvasElement.setAttribute('height', game.size.height.toString());
        canvasElement.ondragstart = function (e) {
            e.preventDefault();
        };
        _this.container = canvasElement;
        return _this;
    }
    return AbstractCanvasRenderer;
}(abstractRenderer_AbstractRenderer));


// EXTERNAL MODULE: ./engine/renderer/webGl/programs/impl/base/mesh/mesh.fragment.glsl
var mesh_fragment = __webpack_require__(5);

// EXTERNAL MODULE: ./engine/renderer/webGl/programs/impl/base/mesh/mesh.vertex.glsl
var mesh_vertex = __webpack_require__(4);

// CONCATENATED MODULE: ./engine/renderer/webGl/programs/impl/base/mesh/meshDrawer.ts







var meshDrawer_MeshDrawer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(MeshDrawer, _super);
    function MeshDrawer(gl) {
        var _this = _super.call(this, gl) || this;
        _this.a_position = 'a_position';
        _this.a_normal = 'a_normal';
        _this.a_texCoord = 'a_texCoord';
        _this.u_modelMatrix = 'u_modelMatrix';
        _this.u_inverseTransposeModelMatrix = 'u_inverseTransposeModelMatrix';
        _this.u_textureMatrix = 'u_textureMatrix';
        _this.u_projectionMatrix = 'u_projectionMatrix';
        _this.u_color = 'u_color';
        _this.u_color_mix = 'u_color_mix';
        _this.u_alpha = 'u_alpha';
        _this.u_reflectivity = 'u_reflectivity';
        _this.u_textureUsed = 'u_textureUsed';
        _this.u_normalsTextureUsed = 'u_normalsTextureUsed';
        _this.u_lightUsed = 'u_lightUsed';
        _this.u_heightMapTextureUsed = 'u_heightMapTextureUsed';
        _this.u_cubeMapTextureUsed = 'u_cubeMapTextureUsed';
        _this.u_heightMapFactor = 'u_heightMapFactor';
        _this.program = new shaderProgram_ShaderProgram(gl, mesh_vertex, mesh_fragment);
        return _this;
    }
    MeshDrawer.prototype.bindModel = function (mesh) {
        this.mesh = mesh;
        if (!this.mesh.bufferInfo)
            this._initBufferInfo(mesh.modelPrimitive.drawMethod, mesh.vertexItemSize);
        if (mesh.isLightAccepted() === undefined) {
            mesh.acceptLight(!!this.mesh.bufferInfo.normalBuffer);
        }
        this.bufferInfo = this.mesh.bufferInfo;
    };
    MeshDrawer.prototype.setModelMatrix = function (m) {
        this.setUniform(this.u_modelMatrix, m);
    };
    MeshDrawer.prototype.setInverseTransposeModelMatrix = function (m) {
        this.setUniform(this.u_inverseTransposeModelMatrix, m);
    };
    MeshDrawer.prototype.setProjectionMatrix = function (m) {
        this.setUniform(this.u_projectionMatrix, m);
    };
    MeshDrawer.prototype.setTextureMatrix = function (m) {
        this.setUniform(this.u_textureMatrix, m);
    };
    MeshDrawer.prototype.setAlfa = function (a) {
        this.setUniform(this.u_alpha, a);
    };
    MeshDrawer.prototype.setReflectivity = function (r) {
        this.setUniform(this.u_reflectivity, r);
    };
    MeshDrawer.prototype.setTextureUsed = function (used) {
        this.setUniform(this.u_textureUsed, used);
    };
    MeshDrawer.prototype.setNormalsTextureUsed = function (used) {
        this.setUniform(this.u_normalsTextureUsed, used);
    };
    MeshDrawer.prototype.setHeightMapTextureUsed = function (used) {
        this.setUniform(this.u_heightMapTextureUsed, used);
    };
    MeshDrawer.prototype.setCubeMapTextureUsed = function (used) {
        this.setUniform(this.u_cubeMapTextureUsed, used);
    };
    MeshDrawer.prototype.setHeightMapFactor = function (val) {
        this.setUniform(this.u_heightMapFactor, val);
    };
    MeshDrawer.prototype.setLightUsed = function (used) {
        this.setUniform(this.u_lightUsed, used);
    };
    MeshDrawer.prototype.setColor = function (c) {
        this.setUniform(this.u_color, c.asGL());
    };
    MeshDrawer.prototype.setColorMix = function (val) {
        this.setUniform(this.u_color_mix, val);
    };
    MeshDrawer.prototype.bind = function () {
        if ( true && this.mesh === undefined)
            throw new debugError_DebugError("can not bind modelDrawer;bindModel must be invoked firstly");
        _super.prototype.bind.call(this);
        this.bufferInfo.bind(this.program);
        if (!this.mesh.modelPrimitive.texCoordArr) {
            this.program.disableAttribute(this.a_texCoord);
        }
        else {
            this.program.enableAttribute(this.a_texCoord);
        }
        if (!this.mesh.modelPrimitive.normalArr) {
            this.program.disableAttribute(this.a_normal);
        }
        else {
            this.program.enableAttribute(this.a_normal);
        }
    };
    MeshDrawer.prototype._initBufferInfo = function (drawMethod, vertexSize) {
        if (drawMethod === void 0) { drawMethod = DRAW_METHOD.TRIANGLES; }
        if (vertexSize === void 0) { vertexSize = 3; }
        var bufferInfo = {
            posVertexInfo: {
                array: this.mesh.modelPrimitive.vertexArr,
                type: this.gl.FLOAT,
                size: vertexSize, attrName: this.a_position
            },
            drawMethod: drawMethod
        };
        if (this.mesh.modelPrimitive.indexArr) {
            bufferInfo.posIndexInfo = {
                array: this.mesh.modelPrimitive.indexArr
            };
        }
        if (this.mesh.modelPrimitive.normalArr) {
            bufferInfo.normalInfo = {
                array: this.mesh.modelPrimitive.normalArr,
                type: this.gl.FLOAT,
                size: 3,
                attrName: this.a_normal
            };
        }
        if (this.mesh.modelPrimitive.texCoordArr) {
            bufferInfo.texVertexInfo = {
                array: this.mesh.modelPrimitive.texCoordArr,
                type: this.gl.FLOAT,
                size: 2, attrName: this.a_texCoord
            };
        }
        this.mesh.bufferInfo = new bufferInfo_BufferInfo(this.gl, bufferInfo);
    };
    return MeshDrawer;
}(abstractDrawer_AbstractDrawer));


// CONCATENATED MODULE: ./engine/renderer/webGl/blender/blender.ts


var blender_Blender = (function () {
    function Blender(_gl) {
        this._gl = _gl;
    }
    Blender.getSingleton = function (gl) {
        if (Blender.instance === undefined)
            Blender.instance = new Blender(gl);
        return Blender.instance;
    };
    Blender.prototype.enable = function () {
        if (this._enabled)
            return;
        this._enabled = true;
        this._gl.enable(this._gl.BLEND);
    };
    Blender.prototype.disable = function () {
        if (this._enabled === false)
            return;
        this._enabled = false;
        this._gl.disable(this._gl.BLEND);
    };
    Blender.prototype.setBlendMode = function (blendMode) {
        if (blendMode === this._lastMode)
            return;
        this._lastMode = blendMode;
        var gl = this._gl;
        switch (blendMode) {
            case BLEND_MODE.NORMAL:
                gl.blendEquation(gl.FUNC_ADD);
                gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
                break;
            case BLEND_MODE.NORMAL_SEPARATE:
                gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
                break;
            case BLEND_MODE.ADDITIVE:
                gl.blendEquation(gl.FUNC_ADD);
                gl.blendFunc(gl.ONE, gl.ONE);
                break;
            case BLEND_MODE.SUBSTRACTIVE:
                gl.blendEquation(gl.FUNC_SUBTRACT);
                gl.blendFunc(gl.ONE, gl.ONE);
                break;
            case BLEND_MODE.REVERSE_SUBSTRACTIVE:
                gl.blendEquation(gl.FUNC_REVERSE_SUBTRACT);
                gl.blendFunc(gl.ONE, gl.ONE);
                break;
            default:
                if (true) {
                    throw new debugError_DebugError("unknown blend mode: " + blendMode);
                }
                break;
        }
    };
    return Blender;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/programs/impl/base/simpleRect/simpleRectDrawer.ts








var simpleRectDrawer_SimpleRectDrawer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(SimpleRectDrawer, _super);
    function SimpleRectDrawer(gl) {
        var _this = _super.call(this, gl) || this;
        _this.gen = new shaderGenerator_ShaderGenerator();
        var gen = _this.gen;
        _this.a_position = gen.addAttribute(GL_TYPE.FLOAT_VEC4, 'a_position');
        _this.a_texCoord = gen.addAttribute(GL_TYPE.FLOAT_VEC2, 'a_texCoord');
        _this.u_vertexMatrix = gen.addVertexUniform(GL_TYPE.FLOAT_MAT4, 'u_vertexMatrix');
        _this.u_textureMatrix = gen.addVertexUniform(GL_TYPE.FLOAT_MAT4, 'u_textureMatrix');
        gen.addVarying(GL_TYPE.FLOAT_VEC2, 'v_texCoord');
        gen.setVertexMainFn("void main(){\ngl_Position = u_vertexMatrix * a_position;\nv_texCoord = (u_textureMatrix * vec4(a_texCoord, 0, 1)).xy;\n}");
        gen.addScalarFragmentUniform(GL_TYPE.SAMPLER_2D, 'texture');
        gen.setFragmentMainFn("void main(){\ngl_FragColor = texture2D(texture, v_texCoord);\n}");
        return _this;
    }
    SimpleRectDrawer.prototype.initProgram = function () {
        if (true) {
            if (!this.gen)
                throw new debugError_DebugError("can not init simpleRectDrawer instance: ShaderGenerator must be created");
        }
        this.primitive = new plane_Plane();
        this.program = new shaderProgram_ShaderProgram(this.gl, this.gen.getVertexSource(), this.gen.getFragmentSource());
        this.bufferInfo = new bufferInfo_BufferInfo(this.gl, {
            posVertexInfo: { array: this.primitive.vertexArr, type: this.gl.FLOAT, size: 2, attrName: 'a_position' },
            posIndexInfo: { array: this.primitive.indexArr },
            texVertexInfo: { array: this.primitive.texCoordArr, type: this.gl.FLOAT, size: 2, attrName: 'a_texCoord' },
            drawMethod: DRAW_METHOD.TRIANGLE_STRIP
        });
    };
    return SimpleRectDrawer;
}(abstractDrawer_AbstractDrawer));


// CONCATENATED MODULE: ./engine/renderer/webGl/programs/impl/base/tileMap/tileMapDrawer.ts



var tileMapDrawer_TileMapDrawer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(TileMapDrawer, _super);
    function TileMapDrawer(gl) {
        var _this = _super.call(this, gl) || this;
        _this.tileSize = [0, 0];
        var gen = _this.gen;
        _this.u_tileSize = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC2, 'u_tileSize');
        gen.setFragmentMainFn("void main(){\nvec2 tileCoord = mod(v_texCoord,u_tileSize);\ngl_FragColor = texture2D(texture, tileCoord);\n}");
        return _this;
    }
    TileMapDrawer.prototype.setTileSize = function (width, height) {
        this.tileSize[0] = width;
        this.tileSize[1] = height;
        this.setUniform(this.u_tileSize, this.tileSize);
    };
    return TileMapDrawer;
}(simpleRectDrawer_SimpleRectDrawer));


// CONCATENATED MODULE: ./engine/renderer/abstract/rendererHelper.ts
var RendererHelper = (function () {
    function RendererHelper(game) {
        this.game = game;
    }
    RendererHelper.prototype.renderSceneToTexture = function (scene, renderTarget) {
        return undefined;
    };
    RendererHelper.prototype.renderModelToTexture = function (m, renderTarget, clearColor) {
        return undefined;
    };
    RendererHelper.prototype.createRenderTarget = function (game, size) {
        return undefined;
    };
    RendererHelper.prototype.destroyRenderTarget = function (t) { };
    return RendererHelper;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/frameBuffer.ts




var frameBuffer_FrameBuffer = (function () {
    function FrameBuffer(_gl, size) {
        this._gl = _gl;
        this._destroyed = false;
        if ( true && !_gl)
            throw new debugError_DebugError("can not create FrameBuffer, gl context not passed to constructor, expected: FrameBuffer(gl)");
        this._width = size.width;
        this._height = size.height;
        this.texture = new texture_Texture(_gl);
        this.texture.setImage(undefined, size);
        this._init(_gl, size);
        this._link = ResourceLink.create(this.texture);
        this.bind();
        this.clear(color_Color.RGB(0, 0, 0), 0);
    }
    FrameBuffer.getCurrent = function () {
        return this._currInstance;
    };
    FrameBuffer.prototype.setInterpolationMode = function (mode) {
        this.texture.setInterpolationMode(mode);
    };
    FrameBuffer.prototype.bind = function () {
        if (true) {
            if (this._destroyed) {
                console.error(this);
                throw new debugError_DebugError("can not bind destroyed frame buffer");
            }
        }
        if (FrameBuffer._currInstance === this)
            return;
        this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, this.glFrameBuffer);
        this._gl.viewport(0, 0, ~~this._width, ~~this._height);
        FrameBuffer._currInstance = this;
    };
    FrameBuffer.prototype.unbind = function () {
        this._checkBound();
        this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
        FrameBuffer._currInstance = undefined;
    };
    FrameBuffer.prototype.clear = function (color, alphaBlendValue) {
        if (alphaBlendValue === void 0) { alphaBlendValue = 1; }
        this._checkBound();
        var arr = color.asGL();
        this._gl.clearColor(arr[0], arr[1], arr[2], arr[3] * alphaBlendValue);
        this._gl.clear(this._gl.COLOR_BUFFER_BIT | this._gl.DEPTH_BUFFER_BIT);
    };
    FrameBuffer.prototype.destroy = function () {
        this._gl.deleteRenderbuffer(this.glRenderBuffer);
        this._gl.deleteFramebuffer(this.glFrameBuffer);
        this._destroyed = true;
    };
    FrameBuffer.prototype.getTexture = function () {
        return this.texture;
    };
    FrameBuffer.prototype.getResourceLink = function () {
        return this._link;
    };
    FrameBuffer.prototype._init = function (gl, size) {
        this.glRenderBuffer = gl.createRenderbuffer();
        if ( true && !this.glRenderBuffer)
            throw new debugError_DebugError("can not allocate memory for glRenderBuffer");
        gl.bindRenderbuffer(gl.RENDERBUFFER, this.glRenderBuffer);
        gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size.width, size.height);
        this.glFrameBuffer = gl.createFramebuffer();
        if ( true && !this.glFrameBuffer)
            throw new debugError_DebugError("can not allocate memory for glFrameBuffer");
        gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFrameBuffer);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.getGlTexture(), 0);
        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.glRenderBuffer);
        var fbStatus = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
        if ( true && fbStatus !== gl.FRAMEBUFFER_COMPLETE) {
            throw new debugError_DebugError("frame buffer status error: " + fbStatus + " (expected gl.FRAMEBUFFER_COMPLETE(" + gl.FRAMEBUFFER_COMPLETE + "))");
        }
        this.texture.unbind();
        gl.bindRenderbuffer(gl.RENDERBUFFER, null);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    };
    FrameBuffer.prototype._checkBound = function () {
        if (false)
            {}
        if (FrameBuffer._currInstance !== this)
            throw new debugError_DebugError("frame buffer is not bound; call bind() method firstly");
    };
    return FrameBuffer;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/doubleFrameBuffer.ts

var doubleFrameBuffer_DoubleFrameBuffer = (function () {
    function DoubleFrameBuffer(_gl, size) {
        this._gl = _gl;
        this.buffers = [
            new frameBuffer_FrameBuffer(_gl, size),
            new frameBuffer_FrameBuffer(_gl, size)
        ];
    }
    DoubleFrameBuffer.prototype.setInterpolationMode = function (mode) {
        this.buffers[0].getTexture().setInterpolationMode(mode);
        this.buffers[1].getTexture().setInterpolationMode(mode);
    };
    DoubleFrameBuffer.prototype.applyFilters = function (texture, filters) {
        var len = filters.length;
        if (len === 0)
            return texture;
        var filter = filters[0];
        if (!filter.enabled)
            return texture;
        filter.getDrawer().attachTexture('texture', texture);
        filter.doFilter(this.getDestBuffer());
        for (var i = 1; i < len; i++) {
            if (!filters[i].enabled)
                continue;
            this.flip();
            filters[i].getDrawer().attachTexture('texture', this.getSourceBuffer().getTexture());
            filters[i].doFilter(this.getDestBuffer());
        }
        this.flip();
        return this.getSourceBuffer().getTexture();
    };
    DoubleFrameBuffer.prototype.destroy = function () {
        this.buffers.forEach(function (b) { return b.destroy(); });
    };
    DoubleFrameBuffer.prototype.flip = function () {
        var tmp = this.buffers[0];
        this.buffers[0] = this.buffers[1];
        this.buffers[1] = tmp;
    };
    DoubleFrameBuffer.prototype.getSourceBuffer = function () {
        return this.buffers[0];
    };
    DoubleFrameBuffer.prototype.getDestBuffer = function () {
        return this.buffers[1];
    };
    return DoubleFrameBuffer;
}());


// CONCATENATED MODULE: ./engine/misc/device.ts
var Device = (function () {
    function Device() {
    }
    Device.logInfo = function () {
        console.log({
            isTouch: Device.isTouch,
            isFrame: Device.isFrame,
            isIPhone: Device.isIPhone,
            buildAt: 1603311205080,
            embeddedEngine: Device.embeddedEngine,
        });
    };
    Device.isTouch = ('ontouchstart' in window);
    Device.isFrame = window.top !== window.self;
    Device.isIPhone = navigator.platform.toLowerCase().indexOf('iphone') > -1;
    Device.embeddedEngine = navigator.userAgent === 'vEngine';
    return Device;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/base/frameBufferStack.ts










var IDENTITY = mat4_mat4.IDENTITY;
var frameBufferStack_Mat16Holder = mat4_mat4.Mat16Holder;

var FLIP_POSITION_MATRIX;
var NONE_FILTERS = [];
var frameBufferStack_FrameBufferStack = (function () {
    function FrameBufferStack(game, _gl, _size) {
        this.game = game;
        this._gl = _gl;
        this._size = _size;
        this.debug = false;
        this._stack = [];
        this._interpolationMode = INTERPOLATION_MODE.LINEAR;
        this._doubleFrameBuffer = new doubleFrameBuffer_DoubleFrameBuffer(this._gl, this._size);
        this._pixelPerfectMode = false;
        this._blender = blender_Blender.getSingleton(this._gl);
        this._stack.push({
            frameBuffer: new frameBuffer_FrameBuffer(this._gl, this._size),
            filters: NONE_FILTERS,
            pointer: { ptr: 0 }
        });
        this._stackPointer = 1;
        this._simpleRectDrawer = new simpleRectDrawer_SimpleRectDrawer(_gl);
        this._simpleRectDrawer.initProgram();
        this._blender.enable();
        this._blender.setBlendMode(BLEND_MODE.NORMAL);
        var m16hResult = frameBufferStack_Mat16Holder.fromPool();
        var m16Scale = frameBufferStack_Mat16Holder.fromPool();
        mat4_mat4.makeScale(m16Scale, this.game.size.width, this.game.size.height, 1);
        var m16Ortho = frameBufferStack_Mat16Holder.fromPool();
        mat4_mat4.ortho(m16Ortho, 0, this.game.size.width, 0, this.game.size.height, -1, 1);
        mat4_mat4.matrixMultiply(m16hResult, m16Scale, m16Ortho);
        FLIP_POSITION_MATRIX = m16hResult.clone();
        m16hResult.release();
        m16Scale.release();
        m16Ortho.release();
        this._resourceLink = ResourceLink.create(this._getFirst().frameBuffer.getTexture());
    }
    FrameBufferStack.prototype.pushState = function (filters, forceDrawChildrenOnNewSurface) {
        var prevPointer = this._getLast().pointer;
        if (filters.length > 0 || forceDrawChildrenOnNewSurface) {
            if (this.debug)
                console.log('state has been pushed');
            if (this._stack[this._stackPointer] === undefined) {
                this._stack[this._stackPointer] = {
                    frameBuffer: new frameBuffer_FrameBuffer(this._gl, this._size),
                    filters: NONE_FILTERS,
                    pointer: { ptr: this._stackPointer }
                };
            }
            this._stack[this._stackPointer].filters = filters;
            this._stack[this._stackPointer].frameBuffer.bind();
            this._stack[this._stackPointer].frameBuffer.clear(color_Color.NONE);
            this._stackPointer++;
        }
        else {
            this._getLast().frameBuffer.bind();
        }
        return prevPointer;
    };
    FrameBufferStack.prototype.clear = function (color, alphaBlend) {
        this._getLast().frameBuffer.bind();
        this._getLast().frameBuffer.clear(color, alphaBlend);
    };
    FrameBufferStack.prototype.setInterpolationMode = function (interpolation) {
        this._getLast().frameBuffer.setInterpolationMode(interpolation);
        this._doubleFrameBuffer.setInterpolationMode(interpolation);
        this._interpolationMode = interpolation;
    };
    FrameBufferStack.prototype.getCurrentTargetSize = function () {
        return this._getLast().frameBuffer.getTexture().size;
    };
    FrameBufferStack.prototype.setPixelPerfect = function (mode) {
        this._pixelPerfectMode = mode;
    };
    FrameBufferStack.prototype.getStackSize = function () {
        return this._stackPointer;
    };
    FrameBufferStack.prototype.destroy = function () {
        this._stack.forEach(function (f) { return f.frameBuffer.destroy(); });
        this._doubleFrameBuffer.destroy();
        this._simpleRectDrawer.destroy();
    };
    FrameBufferStack.prototype.reduceState = function (to) {
        if (this._stackPointer === 1)
            return;
        if (this.debug)
            console.log("reducing state from " + (this._stackPointer - 1) + " to " + to.ptr);
        for (var i = this._stackPointer - 1; i > to.ptr; i--) {
            var currItem = this._stack[i];
            var nextItem = this._stack[i - 1];
            var filteredTexture = this._doubleFrameBuffer.applyFilters(currItem.frameBuffer.getTexture(), currItem.filters);
            currItem.filters = NONE_FILTERS;
            nextItem.frameBuffer.bind();
            nextItem.frameBuffer.setInterpolationMode(this._interpolationMode);
            this._simpleRectDrawer.setUniform(this._simpleRectDrawer.u_textureMatrix, IDENTITY);
            var m16h = makeIdentityPositionMatrix(0, 0, this._getLast().frameBuffer.getTexture().size);
            this._simpleRectDrawer.setUniform(this._simpleRectDrawer.u_vertexMatrix, m16h.mat16);
            this._simpleRectDrawer.attachTexture('texture', filteredTexture);
            this._blender.setBlendMode(BLEND_MODE.NORMAL);
            this._simpleRectDrawer.draw();
            m16h.release();
        }
        this._stackPointer = to.ptr + 1;
    };
    FrameBufferStack.prototype.renderToScreen = function () {
        this._blender.setBlendMode(BLEND_MODE.NORMAL);
        var needFullScreen = this._pixelPerfectMode || Device.embeddedEngine;
        var w = needFullScreen ? this.game.getRenderer().viewPortSize.width : this.game.size.width;
        var h = needFullScreen ? this.game.getRenderer().viewPortSize.height : this.game.size.height;
        frameBuffer_FrameBuffer.getCurrent().unbind();
        this._gl.viewport(0, 0, ~~w, ~~h);
        this._simpleRectDrawer.setUniform(this._simpleRectDrawer.u_textureMatrix, FLIP_TEXTURE_MATRIX.mat16);
        this._simpleRectDrawer.setUniform(this._simpleRectDrawer.u_vertexMatrix, FLIP_POSITION_MATRIX.mat16);
        this._simpleRectDrawer.attachTexture('texture', this._getLast().frameBuffer.getTexture());
        this._simpleRectDrawer.draw();
    };
    FrameBufferStack.prototype.getResourceLink = function () {
        return this._resourceLink;
    };
    FrameBufferStack.prototype._getLast = function () {
        return this._stack[this._stackPointer - 1];
    };
    FrameBufferStack.prototype._getFirst = function () {
        return this._stack[0];
    };
    return FrameBufferStack;
}());


// CONCATENATED MODULE: ./engine/misc/collection/lruMap.ts


var lruMap_LruMap = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(LruMap, _super);
    function LruMap(capacity) {
        if (capacity === void 0) { capacity = 16; }
        var _this = _super.call(this) || this;
        _this.capacity = capacity;
        _this.keys = new Array(_this.capacity);
        return _this;
    }
    LruMap.prototype.put = function (key, value) {
        this.keys.push(key);
        if (this.keys.length > this.capacity) {
            this.remove(this.keys[0]);
            this.keys.splice(0, 1);
        }
        _super.prototype.put.call(this, key, value);
    };
    return LruMap;
}(FastMap));


// CONCATENATED MODULE: ./engine/renderer/webGl/webGlRendererHelper.ts





var webGlRendererHelper_Mat16Holder = mat4_mat4.Mat16Holder;

var identityPositionMatrixCache = new lruMap_LruMap();
var makeIdentityPositionMatrix = function (dstX, dstY, destSize) {
    var key = dstX + "_" + dstY + "_" + destSize.width + "_" + destSize.height;
    if (identityPositionMatrixCache.has(key))
        return identityPositionMatrixCache.get(key);
    var projectionMatrix = webGlRendererHelper_Mat16Holder.create();
    var dstWidth = destSize.width;
    var dstHeight = destSize.height;
    mat4_mat4.ortho(projectionMatrix, 0, dstWidth, 0, dstHeight, -1, 1);
    var scaleMatrix = webGlRendererHelper_Mat16Holder.create();
    mat4_mat4.makeScale(scaleMatrix, dstWidth, dstHeight, 1);
    var result = webGlRendererHelper_Mat16Holder.create();
    mat4_mat4.matrixMultiply(result, scaleMatrix, projectionMatrix);
    identityPositionMatrixCache.put(key, result);
    return result;
};
var FLIP_TEXTURE_MATRIX = new matrixStack_MatrixStack().translate(0, 1).scale(1, -1).release().getCurrentValue().clone();
var webGlRendererHelper_WebGlRendererHelper = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(WebGlRendererHelper, _super);
    function WebGlRendererHelper() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    WebGlRendererHelper.prototype.createRenderTarget = function (game, size) {
        var renderer = this.game.getRenderer();
        return new frameBufferStack_FrameBufferStack(game, renderer.getNativeContext(), size);
    };
    WebGlRendererHelper.prototype.renderSceneToTexture = function (scene, renderTarget) {
        var renderer = this.game.getRenderer();
        renderer.setRenderTarget(renderTarget);
        scene.render();
        renderer.setDefaultRenderTarget();
    };
    WebGlRendererHelper.prototype.renderModelToTexture = function (m, renderTarget, clearColor) {
        var renderer = this.game.getRenderer();
        if (m.size.isZero())
            m.revalidate();
        renderer.setRenderTarget(renderTarget);
        var clearBeforeRenderOrig = renderer.clearBeforeRender;
        var clearColorOrig = renderer.clearColor;
        renderer.clearBeforeRender = clearColor !== undefined;
        if (clearColor !== undefined)
            renderer.clearColor.set(clearColor);
        var statePointer = renderer.beforeFrameDraw(m.filters);
        m.render();
        renderer.afterFrameDraw(statePointer);
        renderer.setDefaultRenderTarget();
        renderer.clearBeforeRender = clearBeforeRenderOrig;
        renderer.clearColor.set(clearColorOrig);
    };
    return WebGlRendererHelper;
}(RendererHelper));


// CONCATENATED MODULE: ./engine/renderer/webGl/base/cubeMapTexture.ts



var cubeMapTexture_CubeMapTexture = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(CubeMapTexture, _super);
    function CubeMapTexture(gl) {
        var _this = _super.call(this, gl) || this;
        _this.gl = gl;
        _this.samplerType = _this.gl.TEXTURE_CUBE_MAP;
        return _this;
    }
    CubeMapTexture.prototype.setImages = function (left, right, top, bottom, front, back) {
        this.validate(left, right, top, bottom, front, back);
        this.init(left, right, top, bottom, front, back);
    };
    CubeMapTexture.prototype.setAsZero = function () {
        var _this = this;
        var gl = this.gl;
        var faceInfos = [
            gl.TEXTURE_CUBE_MAP_POSITIVE_X,
            gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
            gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
            gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
            gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
            gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
        ];
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.tex);
        faceInfos.forEach(function (faceInfo) {
            gl.bindTexture(gl.TEXTURE_CUBE_MAP, _this.tex);
            gl.texImage2D(faceInfo, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
        });
        gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
    };
    CubeMapTexture.prototype.validate = function (left, right, top, bottom, front, back) {
        if (true) {
            if (!this.gl)
                throw new debugError_DebugError("can not create Texture, gl context not passed to constructor, expected: Texture(gl)");
            var isZeroImage = function (img) {
                return img.width === 0 || img.height === 0;
            };
            var isOfSize = function (img, width, height) {
                return img.width === width && img.height === height;
            };
            if (isZeroImage(top) ||
                isZeroImage(bottom) ||
                isZeroImage(left) ||
                isZeroImage(right) ||
                isZeroImage(top) ||
                isZeroImage(bottom)) {
                throw new debugError_DebugError("can not create cube texture: wrong image is passed");
            }
            var w = top.width, h = top.height;
            if (!isOfSize(bottom, w, h) ||
                !isOfSize(left, w, h) ||
                !isOfSize(right, w, h) ||
                !isOfSize(front, w, h) ||
                !isOfSize(back, w, h)) {
                throw new debugError_DebugError("can not create cube texture: the same size of images is required");
            }
        }
    };
    CubeMapTexture.prototype.init = function (left, right, top, bottom, front, back) {
        var _this = this;
        var gl = this.gl;
        var faceInfos = [
            {
                target: gl.TEXTURE_CUBE_MAP_POSITIVE_X,
                img: left,
            },
            {
                target: gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
                img: right,
            },
            {
                target: gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
                img: top,
            },
            {
                target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
                img: bottom,
            },
            {
                target: gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                img: back,
            },
            {
                target: gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
                img: front,
            },
        ];
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.tex);
        this.size.setWH(top.width, top.height);
        faceInfos.forEach(function (faceInfo) {
            gl.bindTexture(gl.TEXTURE_CUBE_MAP, _this.tex);
            gl.texImage2D(faceInfo.target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, faceInfo.img);
        });
        if (isPowerOf2(this.size.width) && isPowerOf2(this.size.height)) {
            gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
        }
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
    };
    return CubeMapTexture;
}(abstractTexture_AbstractTexture));


// CONCATENATED MODULE: ./engine/renderer/webGl/programs/impl/base/simpleRect/simpleColoredRectDrawer.ts








var simpleColoredRectDrawer_SimpleColoredRectDrawer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(SimpleColoredRectDrawer, _super);
    function SimpleColoredRectDrawer(gl) {
        var _this = _super.call(this, gl) || this;
        _this.gl = gl;
        _this.gen = new shaderGenerator_ShaderGenerator();
        var gen = _this.gen;
        gen.addAttribute(GL_TYPE.FLOAT_VEC4, 'a_position');
        _this.u_vertexMatrix = gen.addVertexUniform(GL_TYPE.FLOAT_MAT4, 'u_vertexMatrix');
        _this.u_alpha = gen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_alpha');
        _this.u_color = gen.addScalarFragmentUniform(GL_TYPE.FLOAT_VEC4, 'u_color');
        gen.setVertexMainFn("void main(){\ngl_Position = u_vertexMatrix * a_position;\n}");
        gen.setFragmentMainFn("void main(){\ngl_FragColor = u_color*u_alpha;\n}");
        _this.initProgram();
        return _this;
    }
    SimpleColoredRectDrawer.prototype.initProgram = function () {
        if (true) {
            if (!this.gen)
                throw new debugError_DebugError("can not init simpleRectDrawer instance: ShaderGenerator must be created");
        }
        this.primitive = new plane_Plane();
        this.program = new shaderProgram_ShaderProgram(this.gl, this.gen.getVertexSource(), this.gen.getFragmentSource());
        this.bufferInfo = new bufferInfo_BufferInfo(this.gl, {
            posVertexInfo: { array: this.primitive.vertexArr, type: this.gl.FLOAT, size: 2, attrName: 'a_position' },
            posIndexInfo: { array: this.primitive.indexArr },
            drawMethod: DRAW_METHOD.TRIANGLE_STRIP
        });
    };
    return SimpleColoredRectDrawer;
}(abstractDrawer_AbstractDrawer));


// CONCATENATED MODULE: ./engine/renderer/webGl/webGlRenderer.ts





















var webGlRenderer_Mat16Holder = mat4_mat4.Mat16Holder;
var webGlRenderer_glEnumToString = debugUtil.glEnumToString;



var webGlRenderer_getCtx = function (el) {
    var contextAttrs = { alpha: false, premultipliedAlpha: false };
    var possibles = ['webgl', 'experimental-webgl', 'webkit-3d', 'moz-webgl'];
    for (var _i = 0, possibles_1 = possibles; _i < possibles_1.length; _i++) {
        var p = possibles_1[_i];
        var ctx = el.getContext(p, contextAttrs);
        if (ctx) {
            return ctx;
        }
    }
    if (true)
        throw new debugError_DebugError("webGl is not accessible on this device");
    return undefined;
};
var SCENE_DEPTH = 1000;
var zToWMatrix = webGlRenderer_Mat16Holder.create();
mat4_mat4.makeZToWMatrix(zToWMatrix, 1);
var makePositionMatrix = function (rect, viewSize, matrixStack) {
    var projectionMatrix = webGlRenderer_Mat16Holder.fromPool();
    mat4_mat4.ortho(projectionMatrix, 0, viewSize.width, 0, viewSize.height, -SCENE_DEPTH, SCENE_DEPTH);
    var scaleMatrix = webGlRenderer_Mat16Holder.fromPool();
    mat4_mat4.makeScale(scaleMatrix, rect.width, rect.height, 1);
    var translationMatrix = webGlRenderer_Mat16Holder.fromPool();
    mat4_mat4.makeTranslation(translationMatrix, rect.x, rect.y, 0);
    var matrix1 = webGlRenderer_Mat16Holder.fromPool();
    mat4Special.matrixScaleMultiply(matrix1, scaleMatrix, translationMatrix);
    var matrix2 = webGlRenderer_Mat16Holder.fromPool();
    mat4_mat4.matrixMultiply(matrix2, matrix1, matrixStack.getCurrentValue());
    var matrix3 = webGlRenderer_Mat16Holder.fromPool();
    mat4_mat4.matrixMultiply(matrix3, matrix2, projectionMatrix);
    var matrix4 = webGlRenderer_Mat16Holder.fromPool();
    mat4_mat4.matrixMultiply(matrix4, matrix3, zToWMatrix);
    projectionMatrix.release();
    scaleMatrix.release();
    translationMatrix.release();
    matrix1.release();
    matrix2.release();
    matrix3.release();
    return matrix4;
};
var InstanceHolder = (function () {
    function InstanceHolder(clazz) {
        this.clazz = clazz;
    }
    InstanceHolder.prototype.getInstance = function (gl) {
        if (this.instance === undefined)
            this.instance = new this.clazz(gl);
        return this.instance;
    };
    InstanceHolder.prototype.destroy = function () {
        if (this.instance !== undefined)
            this.instance.destroy();
    };
    InstanceHolder.prototype.isInvoked = function () {
        return this.instance !== undefined;
    };
    return InstanceHolder;
}());
var webGlRenderer_WebGlRenderer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(WebGlRenderer, _super);
    function WebGlRenderer(game) {
        var _this = _super.call(this, game) || this;
        _this.type = 'WebGlRenderer';
        _this.rendererHelper = new webGlRendererHelper_WebGlRendererHelper(_this.game);
        _this._matrixStack = new matrixStack_MatrixStack();
        _this._shapeDrawerHolder = new InstanceHolder(shapeDrawer_ShapeDrawer);
        _this._coloredRectDrawer = new InstanceHolder(simpleColoredRectDrawer_SimpleColoredRectDrawer);
        _this._meshDrawerHolder = new InstanceHolder(meshDrawer_MeshDrawer);
        _this._tileMapDrawerHolder = new InstanceHolder(tileMapDrawer_TileMapDrawer);
        _this._pixelPerfectMode = false;
        _this.registerResize();
        _this._init();
        return _this;
    }
    WebGlRenderer.prototype.setPixelPerfect = function (mode) {
        var interpolation = mode ? INTERPOLATION_MODE.NEAREST : INTERPOLATION_MODE.LINEAR;
        this._currFrameBufferStack.setInterpolationMode(interpolation);
        this._currFrameBufferStack.setPixelPerfect(mode);
        this._pixelPerfectMode = mode;
        this.onResize();
    };
    WebGlRenderer.prototype.drawImage = function (img) {
        if (true) {
            if (!img.getResourceLink()) {
                throw new debugError_DebugError("image resource link is not set");
            }
            if (!img.getResourceLink().getTarget()) {
                console.error(img);
                throw new debugError_DebugError("no target associated with resource link");
            }
            if (img.getResourceLink().state !== ResourceLinkState.COMPLETED) {
                throw new debugError_DebugError("can not access resource link: it has wrong state " + img.getResourceLink().state + ", " + ResourceLinkState.COMPLETED + " state is expected");
            }
        }
        img.getResourceLink().getTarget().
            setInterpolationMode(img.isPixelPerfect() ? INTERPOLATION_MODE.NEAREST : INTERPOLATION_MODE.LINEAR);
        var texture = img.getResourceLink().getTarget();
        var maxSize = Math.max(img.size.width, img.size.height);
        var sd = this._shapeDrawerHolder.getInstance(this._gl);
        this.prepareGeometryUniformInfo(img);
        sd.setUniform(sd.u_lineWidth, Math.min(img.lineWidth / maxSize, 1));
        sd.setUniform(sd.u_color, img.color.asGL());
        var repeatFactor = size_Size.fromPool();
        repeatFactor.setWH(img.size.width / img.getSrcRect().width, img.size.height / img.getSrcRect().height);
        sd.setUniform(sd.u_repeatFactor, repeatFactor.toArray());
        repeatFactor.release();
        sd.setUniform(sd.u_borderRadius, Math.min(img.borderRadius / maxSize, 1));
        sd.setUniform(sd.u_shapeType, SHAPE_TYPE.RECT);
        sd.setUniform(sd.u_fillType, FILL_TYPE.TEXTURE);
        var _a = texture.size, textureWidth = _a.width, textureHeight = _a.height;
        var _b = img.getSrcRect(), srcRectX = _b.x, srcRectY = _b.y;
        var _c = img.getSrcRect(), destRectWidth = _c.width, destRectHeight = _c.height;
        var destArr = rect_Rect.fromPool().setXYWH(srcRectX / textureWidth, srcRectY / textureHeight, destRectWidth / textureWidth, destRectHeight / textureHeight).release().toArray();
        sd.setUniform(sd.u_texRect, destArr);
        var offSetArr = size_Size.fromPool().setWH(img.offset.x / maxSize, img.offset.y / maxSize).release().toArray();
        sd.setUniform(sd.u_texOffset, offSetArr);
        sd.setUniform(sd.u_stretchMode, img.stretchMode);
        sd.attachTexture('texture', texture);
        sd.draw();
    };
    WebGlRenderer.prototype.drawMesh = function (mesh) {
        var md = this._meshDrawerHolder.getInstance(this._gl);
        md.bindModel(mesh);
        md.bind();
        var modelMatrix = this._matrixStack.getCurrentValue();
        var orthoProjectionMatrix = webGlRenderer_Mat16Holder.fromPool();
        var currViewSize = this._currFrameBufferStack.getCurrentTargetSize();
        mat4_mat4.ortho(orthoProjectionMatrix, 0, currViewSize.width, 0, currViewSize.height, -SCENE_DEPTH, SCENE_DEPTH);
        var zToWProjectionMatrix = webGlRenderer_Mat16Holder.fromPool();
        mat4_mat4.matrixMultiply(zToWProjectionMatrix, orthoProjectionMatrix, zToWMatrix);
        var inverseTransposeModelMatrix = webGlRenderer_Mat16Holder.fromPool();
        mat4_mat4.inverse(inverseTransposeModelMatrix, modelMatrix);
        mat4_mat4.transpose(inverseTransposeModelMatrix, inverseTransposeModelMatrix);
        md.setModelMatrix(modelMatrix.mat16);
        md.setInverseTransposeModelMatrix(inverseTransposeModelMatrix.mat16);
        md.setProjectionMatrix(zToWProjectionMatrix.mat16);
        md.setAlfa(this.getAlphaBlend());
        var isTextureUsed = mesh.texture !== undefined;
        if ( true && isTextureUsed && mesh.modelPrimitive.texCoordArr === undefined)
            throw new debugError_DebugError("can not apply texture without texture coordinates");
        md.setTextureUsed(isTextureUsed);
        if (isTextureUsed)
            md.setTextureMatrix(FLIP_TEXTURE_MATRIX.mat16);
        md.attachTexture('u_texture', isTextureUsed ? mesh.texture : this._nullTexture);
        var isNormalsTextureUsed = mesh.normalsTexture !== undefined;
        md.setNormalsTextureUsed(isNormalsTextureUsed);
        md.attachTexture('u_normalsTexture', isNormalsTextureUsed ? mesh.normalsTexture : this._nullTexture);
        var isHeightMapTextureUsed = mesh.heightMapTexture !== undefined;
        md.setHeightMapTextureUsed(isHeightMapTextureUsed);
        md.attachTexture('u_heightMapTexture', isHeightMapTextureUsed ? mesh.heightMapTexture : this._nullTexture);
        md.setHeightMapFactor(mesh.heightMapFactor);
        var isCubeMapTextureUsed = mesh.cubeMapTexture !== undefined;
        if ( true && !isCubeMapTextureUsed && mesh.reflectivity !== 0)
            throw new debugError_DebugError("can not apply reflectivity without cubeMapTexture");
        md.setCubeMapTextureUsed(isCubeMapTextureUsed);
        md.setReflectivity(mesh.reflectivity);
        md.attachTexture('u_cubeMapTexture', isCubeMapTextureUsed ? mesh.cubeMapTexture : this._nullCubeMapTexture);
        md.setLightUsed(mesh.isLightAccepted() || false);
        md.setColor(mesh.fillColor);
        md.setColorMix(mesh.colorMix);
        if (mesh.depthTest)
            this._gl.enable(this._gl.DEPTH_TEST);
        else
            this._gl.disable(this._gl.DEPTH_TEST);
        md.draw();
        zToWMatrix.release();
        orthoProjectionMatrix.release();
        zToWProjectionMatrix.release();
        inverseTransposeModelMatrix.release();
    };
    WebGlRenderer.prototype.drawRectangle = function (rectangle) {
        if (rectangle.lineWidth === 0 && rectangle.borderRadius === 0 && rectangle.fillGradient === undefined) {
            this.drawSimpleColoredRectangle(rectangle);
        }
        else {
            var rw = rectangle.size.width;
            var rh = rectangle.size.height;
            var maxSize = Math.max(rw, rh);
            var sd = this._shapeDrawerHolder.getInstance(this._gl);
            this.prepareGeometryUniformInfo(rectangle);
            this.prepareShapeUniformInfo(rectangle);
            sd.setUniform(sd.u_borderRadius, Math.min(rectangle.borderRadius / maxSize, 1));
            sd.setUniform(sd.u_shapeType, SHAPE_TYPE.RECT);
            sd.attachTexture('texture', this._nullTexture);
            sd.draw();
        }
    };
    WebGlRenderer.prototype.drawLine = function (line) {
        var r = line.getRectangleRepresentation();
        this.drawRectangle(r);
    };
    WebGlRenderer.prototype.drawEllipse = function (ellipse) {
        var maxR = Math.max(ellipse.radiusX, ellipse.radiusY);
        this.prepareGeometryUniformInfo(ellipse);
        this.prepareShapeUniformInfo(ellipse);
        var sd = this._shapeDrawerHolder.getInstance(this._gl);
        if (maxR === ellipse.radiusX) {
            sd.setUniform(sd.u_rx, 0.5);
            sd.setUniform(sd.u_ry, ellipse.radiusY / ellipse.radiusX * 0.5);
        }
        else {
            sd.setUniform(sd.u_ry, 0.5);
            sd.setUniform(sd.u_rx, ellipse.radiusX / ellipse.radiusY * 0.5);
        }
        sd.setUniform(sd.u_shapeType, SHAPE_TYPE.ELLIPSE);
        sd.setUniform(sd.u_width, 1);
        sd.setUniform(sd.u_height, 1);
        sd.setUniform(sd.u_rectOffsetLeft, 1);
        sd.setUniform(sd.u_rectOffsetTop, 1);
        sd.setUniform(sd.u_arcAngleFrom, ellipse.arcAngleFrom % (2 * Math.PI));
        sd.setUniform(sd.u_arcAngleTo, ellipse.arcAngleTo % (2 * Math.PI));
        sd.setUniform(sd.u_anticlockwise, ellipse.anticlockwise);
        sd.attachTexture('texture', this._nullTexture);
        sd.draw();
    };
    WebGlRenderer.prototype.transformSave = function () {
        this._matrixStack.save();
    };
    WebGlRenderer.prototype.transformScale = function (x, y, z) {
        if (z === void 0) { z = 1; }
        if (x === 1 && y === 1 && z === 1)
            return;
        this._matrixStack.scale(x, y, z);
    };
    WebGlRenderer.prototype.transformReset = function () {
        this._matrixStack.resetTransform();
    };
    WebGlRenderer.prototype.transformRotateX = function (angleInRadians) {
        if (angleInRadians === 0)
            return;
        this._matrixStack.rotateX(angleInRadians);
    };
    WebGlRenderer.prototype.transformRotateY = function (angleInRadians) {
        if (angleInRadians === 0)
            return;
        this._matrixStack.rotateY(angleInRadians);
    };
    WebGlRenderer.prototype.transformRotateZ = function (angleInRadians) {
        if (angleInRadians === 0)
            return;
        this._matrixStack.rotateZ(angleInRadians);
    };
    WebGlRenderer.prototype.transformTranslate = function (x, y, z) {
        if (z === void 0) { z = 0; }
        if (x === 0 && y === 0 && z === 0)
            return;
        this._matrixStack.translate(x, y, z);
    };
    WebGlRenderer.prototype.transformRotationReset = function () {
        this._matrixStack.rotationReset();
    };
    WebGlRenderer.prototype.transformSkewX = function (angle) {
        if (angle === 0)
            return;
        this._matrixStack.skewX(angle);
    };
    WebGlRenderer.prototype.transformSkewY = function (angle) {
        if (angle === 0)
            return;
        this._matrixStack.skewY(angle);
    };
    WebGlRenderer.prototype.transformRestore = function () {
        this._matrixStack.restore();
    };
    WebGlRenderer.prototype.transformSet = function (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        this._matrixStack.setMatrixValues(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
    };
    WebGlRenderer.prototype.transformTranslateByMatrixValues = function (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        this._matrixStack.translateByMatrixValues(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
    };
    WebGlRenderer.prototype.transformGet = function () {
        return this._matrixStack.getCurrentValue().mat16;
    };
    WebGlRenderer.prototype.setLockRect = function (rect) {
        this._lockRect = rect;
    };
    WebGlRenderer.prototype.unsetLockRect = function () {
        this._lockRect = undefined;
    };
    WebGlRenderer.prototype.beforeItemStackDraw = function (filters, forceDrawChildrenOnNewSurface) {
        return this._currFrameBufferStack.pushState(filters, forceDrawChildrenOnNewSurface);
    };
    WebGlRenderer.prototype.afterItemStackDraw = function (stackPointer) {
        this._gl.disable(this._gl.DEPTH_TEST);
        this._currFrameBufferStack.reduceState(stackPointer);
    };
    WebGlRenderer.prototype.beforeFrameDraw = function (filters) {
        var ptr = this._currFrameBufferStack.pushState(filters, false);
        if (this.clearBeforeRender) {
            this._currFrameBufferStack.clear(this.clearColor, this.getAlphaBlend());
        }
        return ptr;
    };
    WebGlRenderer.prototype.afterFrameDraw = function (stackPointer) {
        this._currFrameBufferStack.reduceState(stackPointer);
        if (this._currFrameBufferStack === this._origFrameBufferStack) {
            if (this._lockRect !== undefined) {
                var rect = this._lockRect;
                this._gl.enable(this._gl.SCISSOR_TEST);
                this._gl.scissor(~~rect.x, ~~(this.game.size.height - rect.height - rect.y), ~~rect.width, ~~rect.height);
            }
            this._currFrameBufferStack.renderToScreen();
            this._gl.disable(this._gl.SCISSOR_TEST);
        }
    };
    WebGlRenderer.prototype.getError = function () {
        if (false)
            {}
        var err = this._gl.getError();
        if (err !== this._gl.NO_ERROR) {
            return { code: err, desc: webGlRenderer_glEnumToString(this._gl, err) };
        }
        return undefined;
    };
    WebGlRenderer.prototype.createTexture = function (bitmap) {
        var texture = new texture_Texture(this._gl);
        texture.setImage(bitmap);
        return texture;
    };
    WebGlRenderer.prototype.createCubeTexture = function (imgLeft, imgRight, imgTop, imgBottom, imgFront, imgBack) {
        var cubeTexture = new cubeMapTexture_CubeMapTexture(this._gl);
        cubeTexture.setImages(imgLeft, imgRight, imgTop, imgBottom, imgFront, imgBack);
        return cubeTexture;
    };
    WebGlRenderer.prototype.getNativeContext = function () {
        return this._gl;
    };
    WebGlRenderer.prototype.setRenderTarget = function (fbs) {
        if (this._currFrameBufferStack !== fbs) {
            abstractDrawer_AbstractDrawer.unbindLastInstance();
        }
        this._currFrameBufferStack = fbs;
    };
    WebGlRenderer.prototype.setDefaultRenderTarget = function () {
        abstractDrawer_AbstractDrawer.unbindLastInstance();
        this._currFrameBufferStack = this._origFrameBufferStack;
    };
    WebGlRenderer.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        this._origFrameBufferStack.destroy();
        this._nullTexture.destroy();
        this._nullCubeMapTexture.destroy();
        this._shapeDrawerHolder.destroy();
        this._meshDrawerHolder.destroy();
        this._tileMapDrawerHolder.destroy();
        texture_Texture.destroyAll();
    };
    WebGlRenderer.prototype.onResize = function () {
        _super.prototype.onResize.call(this);
        if (this._pixelPerfectMode && (this.game.scaleStrategy === SCALE_STRATEGY.STRETCH || this.game.scaleStrategy === SCALE_STRATEGY.FIT)) {
            this.container.width = this.viewPortSize.width;
            this.container.height = this.viewPortSize.height;
        }
        else {
            this.container.width = this.game.size.width;
            this.container.height = this.game.size.height;
        }
    };
    WebGlRenderer.prototype._init = function () {
        var gl = webGlRenderer_getCtx(this.container);
        if ( true && gl === undefined)
            throw new debugError_DebugError("WebGLRenderingContext is not supported by this device");
        this._gl = gl;
        this._nullTexture = new texture_Texture(gl);
        this._nullCubeMapTexture = new cubeMapTexture_CubeMapTexture(gl);
        this._nullCubeMapTexture.setAsZero();
        this._blender = blender_Blender.getSingleton(gl);
        this._blender.enable();
        this._blender.setBlendMode(BLEND_MODE.NORMAL);
        this._origFrameBufferStack = new frameBufferStack_FrameBufferStack(this.game, this.getNativeContext(), this.game.size);
        this.setDefaultRenderTarget();
    };
    WebGlRenderer.prototype.drawSimpleColoredRectangle = function (rectangle) {
        var scd = this._coloredRectDrawer.getInstance(this._gl);
        var rect = rect_Rect.fromPool();
        rect.setXYWH(0, 0, rectangle.size.width, rectangle.size.height);
        var size = size_Size.fromPool();
        size.set(this._currFrameBufferStack.getCurrentTargetSize());
        var pos16h = makePositionMatrix(rect, size, this._matrixStack);
        scd.setUniform(scd.u_vertexMatrix, pos16h.mat16);
        pos16h.release();
        rect.release();
        size.release();
        scd.setUniform(scd.u_alpha, this.getAlphaBlend());
        scd.setUniform(scd.u_color, (rectangle.fillColor).asGL());
        scd.draw();
    };
    WebGlRenderer.prototype.prepareGeometryUniformInfo = function (model) {
        if (true) {
            if (!model.size.width || !model.size.height) {
                console.error(model);
                throw new debugError_DebugError("Can not render model with zero size");
            }
        }
        var _a = model.size, rw = _a.width, rh = _a.height;
        var maxSize = Math.max(rw, rh);
        var sd = this._shapeDrawerHolder.getInstance(this._gl);
        var offsetX = 0, offsetY = 0;
        if (maxSize === rw) {
            sd.setUniform(sd.u_width, 1);
            sd.setUniform(sd.u_height, rh / rw);
            offsetY = (maxSize - rh) / 2;
            sd.setUniform(sd.u_rectOffsetLeft, 0);
            sd.setUniform(sd.u_rectOffsetTop, offsetY / maxSize);
        }
        else {
            sd.setUniform(sd.u_height, 1);
            sd.setUniform(sd.u_width, rw / rh);
            offsetX = (maxSize - rw) / 2;
            sd.setUniform(sd.u_rectOffsetLeft, offsetX / maxSize);
            sd.setUniform(sd.u_rectOffsetTop, 0);
        }
        var rect = rect_Rect.fromPool();
        rect.setXYWH(-offsetX, -offsetY, maxSize, maxSize);
        var size = size_Size.fromPool();
        size.set(this._currFrameBufferStack.getCurrentTargetSize());
        var pos16h = makePositionMatrix(rect, size, this._matrixStack);
        sd.setUniform(sd.u_vertexMatrix, pos16h.mat16);
        pos16h.release();
        rect.release();
        size.release();
        sd.setUniform(sd.u_alpha, this.getAlphaBlend());
        sd.setUniform(sd.u_stretchMode, STRETCH_MODE.STRETCH);
        this._blender.setBlendMode(model.blendMode);
        if (model.depthTest)
            this._gl.enable(this._gl.DEPTH_TEST);
        else
            this._gl.disable(this._gl.DEPTH_TEST);
    };
    WebGlRenderer.prototype.prepareShapeUniformInfo = function (model) {
        if (true) {
            if (!model.size.width || !model.size.height) {
                console.error(model);
                throw new debugError_DebugError("Can not render model with zero size");
            }
        }
        var maxSize = Math.max(model.size.width, model.size.height);
        var sd = this._shapeDrawerHolder.getInstance(this._gl);
        sd.setUniform(sd.u_lineWidth, Math.min(model.lineWidth / maxSize, 1));
        sd.setUniform(sd.u_color, model.color.asGL());
        if (model.fillGradient !== undefined) {
            model.fillGradient.setUniforms(sd);
            if (model.fillGradient.type === 'LinearGradient') {
                sd.setUniform(sd.u_fillType, FILL_TYPE.LINEAR_GRADIENT);
            }
            else {
                model.fillGradient.setUniforms(sd);
                sd.setUniform(sd.u_fillType, FILL_TYPE.RADIAL_GRADIENT);
            }
        }
        else {
            sd.setUniform(sd.u_fillColor, model.fillColor.asGL());
            sd.setUniform(sd.u_fillType, FILL_TYPE.COLOR);
        }
    };
    return WebGlRenderer;
}(abstractCanvasRenderer_AbstractCanvasRenderer));


// CONCATENATED MODULE: ./engine/control/keyboard/keyboardControl.ts



var keyboardControl_KeyboardControl = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(KeyboardControl, _super);
    function KeyboardControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.type = 'KeyboardControl';
        _this.keyPressed = KEYBOARD_EVENTS.keyPressed;
        _this.keyHold = KEYBOARD_EVENTS.keyHold;
        _this.keyReleased = KEYBOARD_EVENTS.keyReleased;
        return _this;
    }
    KeyboardControl.prototype.isJustPressed = function (key) {
        var event = this.findEvent(key);
        if (event === undefined)
            return false;
        return event.keyState === KEY_STATE.KEY_JUST_PRESSED;
    };
    KeyboardControl.prototype.isReleased = function (key) {
        var event = this.findEvent(key);
        if (event === undefined)
            return false;
        return event.keyState <= KEY_STATE.KEY_JUST_RELEASED;
    };
    KeyboardControl.prototype.isJustReleased = function (key) {
        var event = this.findEvent(key);
        if (event === undefined)
            return false;
        return event.keyState === KEY_STATE.KEY_JUST_RELEASED;
    };
    KeyboardControl.prototype.listenTo = function () {
        var _this = this;
        this._keyDownListener = function (e) {
            e.preventDefault();
            e.stopPropagation();
            var code = e.keyCode;
            _this.triggerKeyPress(code, e);
        };
        this._keyUpListener = function (e) {
            var code = e.keyCode;
            _this.triggerKeyRelease(code, e);
        };
        globalThis.addEventListener('keydown', this._keyDownListener);
        globalThis.addEventListener('keyup', this._keyUpListener);
    };
    KeyboardControl.prototype.triggerKeyPress = function (code, nativeEvent) {
        if (this.isPressed(code))
            return;
        var eventFromBuffer = keyboardEvents_KeyBoardEvent.fromPool();
        if (eventFromBuffer === undefined) {
            if (true)
                console.warn('keyboard pool is full');
            return;
        }
        eventFromBuffer.key = code;
        eventFromBuffer.nativeEvent = nativeEvent;
        this.press(eventFromBuffer);
    };
    KeyboardControl.prototype.triggerKeyRelease = function (code, nativeEvent) {
        var eventFromBuffer = this.findEvent(code);
        if (eventFromBuffer === undefined)
            return;
        eventFromBuffer.nativeEvent = nativeEvent;
        this.release(eventFromBuffer);
    };
    KeyboardControl.prototype.destroy = function () {
        globalThis.removeEventListener('keydown', this._keyDownListener);
        globalThis.removeEventListener('keyup', this._keyUpListener);
    };
    KeyboardControl.prototype.isPressed = function (key) {
        var event = this.findEvent(key);
        if (event === undefined)
            return false;
        return event.keyState >= KEY_STATE.KEY_PRESSED;
    };
    KeyboardControl.prototype.findEvent = function (key) {
        for (var _i = 0, _a = this.buffer; _i < _a.length; _i++) {
            var event = _a[_i];
            if (event.key === key)
                return event;
        }
        return undefined;
    };
    return KeyboardControl;
}(abstractKeypad_AbstractKeypad));


// CONCATENATED MODULE: ./engine/renderer/webGl/filters/abstract/abstractGlFilter.ts







var abstractGlFilter_IDENTITY = mat4_mat4.IDENTITY;
var abstractGlFilter_AbstractGlFilter = (function () {
    function AbstractGlFilter(game) {
        this.game = game;
        this.type = 'WebglFilter';
        this.enabled = true;
        this._uniformCache = new FastMap();
        var renderer = game.getRenderer();
        if ( true && !(renderer instanceof webGlRenderer_WebGlRenderer)) {
            throw new debugError_DebugError("can not apply filter: filters awailable only for WebGlRenerer");
        }
        this.gl = game.getRenderer().getNativeContext();
        this.simpleRectDrawer = new simpleRectDrawer_SimpleRectDrawer(this.gl);
    }
    AbstractGlFilter.prototype.setUniform = function (name, value) {
        this._uniformCache.put(name, value);
    };
    AbstractGlFilter.prototype.getDrawer = function () {
        return this.simpleRectDrawer;
    };
    AbstractGlFilter.prototype.doFilter = function (destFrameBuffer) {
        var keys = this._uniformCache.getKeys();
        for (var i = 0; i < keys.length; i++) {
            var name = keys[i];
            var value = this._uniformCache.get(keys[i]);
            this.simpleRectDrawer.setUniform(name, value);
        }
        var size = this.simpleRectDrawer.getAttachedTextureAt(0).size;
        this.simpleRectDrawer.setUniform(this.simpleRectDrawer.u_textureMatrix, abstractGlFilter_IDENTITY);
        var m16h = makeIdentityPositionMatrix(0, 0, size);
        this.simpleRectDrawer.setUniform(this.simpleRectDrawer.u_vertexMatrix, m16h.mat16);
        m16h.release();
        destFrameBuffer.bind();
        destFrameBuffer.clear(color_Color.NONE);
        this.simpleRectDrawer.draw();
    };
    return AbstractGlFilter;
}());


// CONCATENATED MODULE: ./engine/renderer/webGl/filters/accumulative/abstract/abstractAccumulativeFilter.ts









var abstractAccumulativeFilter_IDENTITY = mat4_mat4.IDENTITY;
var abstractAccumulativeFilter_img;
var abstractAccumulativeFilter_AbstractAccumulativeFilter = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(AbstractAccumulativeFilter, _super);
    function AbstractAccumulativeFilter(game) {
        var _this = _super.call(this, game) || this;
        var gl = _this.game.getRenderer().getNativeContext();
        _this._simpleRectCopyDrawer = new simpleRectDrawer_SimpleRectDrawer(gl);
        _this._simpleRectCopyDrawer.initProgram();
        _this.accumulatorBefore = new frameBuffer_FrameBuffer(gl, _this.game.size);
        _this.accumulatorAfter = new frameBuffer_FrameBuffer(gl, _this.game.size);
        abstractAccumulativeFilter_img = document.createElement('img');
        document.body.appendChild(abstractAccumulativeFilter_img);
        return _this;
    }
    AbstractAccumulativeFilter.prototype.doFilter = function (destFrameBuffer) {
        var size = destFrameBuffer.getTexture().size;
        var m16h = makeIdentityPositionMatrix(0, 0, size);
        this._simpleRectCopyDrawer.setUniform(this._simpleRectCopyDrawer.u_textureMatrix, abstractAccumulativeFilter_IDENTITY);
        this._simpleRectCopyDrawer.setUniform(this._simpleRectCopyDrawer.u_vertexMatrix, m16h.mat16);
        blender_Blender.getSingleton(this.game.getRenderer().getNativeContext()).setBlendMode(BLEND_MODE.NORMAL);
        this.accumulatorBefore.bind();
        this.accumulatorBefore.clear(color_Color.NONE);
        this._simpleRectCopyDrawer.attachTexture('texture', this.accumulatorAfter.getTexture());
        this._simpleRectCopyDrawer.draw();
        this.accumulatorBefore.bind();
        this._simpleRectCopyDrawer.attachTexture('texture', this.simpleRectDrawer.getAttachedTextureAt(0));
        this._simpleRectCopyDrawer.draw();
        this.simpleRectDrawer.attachTexture('texture', this.accumulatorBefore.getTexture());
        _super.prototype.doFilter.call(this, destFrameBuffer);
        this.accumulatorAfter.bind();
        this.accumulatorAfter.clear(color_Color.NONE);
        this._simpleRectCopyDrawer.attachTexture('texture', destFrameBuffer.getTexture());
        this._simpleRectCopyDrawer.draw();
        m16h.release();
    };
    return AbstractAccumulativeFilter;
}(abstractGlFilter_AbstractGlFilter));


// CONCATENATED MODULE: ./engine/renderer/webGl/filters/accumulative/abstract/abstractKernelAccumulativeFilter.ts



var abstractKernelAccumulativeFilter_AbstractKernelAccumulativeFilter = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(AbstractKernelAccumulativeFilter, _super);
    function AbstractKernelAccumulativeFilter(game) {
        var _this = _super.call(this, game) || this;
        _this.kernelWeight = 0;
        _this.noiseIntensity = 0;
        _this.time = 0;
        var programGen = _this.simpleRectDrawer.gen;
        programGen.setFragmentMainFn("float PHI = 1.61803398874989484820459;  // \u03A6 = Golden Ratio\nfloat rand(vec2 xy,float seed) {\nreturn fract(tan(distance(xy*PHI, xy)*seed)*xy.x);\n}\nvoid main(){\nvec2 onePixel = vec2(1.0, 1.0) / vec2(rt_w,rt_h);\nvec4 colorSum =\ntexture2D(texture, v_texCoord + onePixel * vec2(-1, -1)) * u_kernel[0] +\ntexture2D(texture, v_texCoord + onePixel * vec2( 0, -1)) * u_kernel[1] +\ntexture2D(texture, v_texCoord + onePixel * vec2( 1, -1)) * u_kernel[2] +\ntexture2D(texture, v_texCoord + onePixel * vec2(-1,  0)) * u_kernel[3] +\ntexture2D(texture, v_texCoord + onePixel * vec2( 0,  0)) * u_kernel[4] +\ntexture2D(texture, v_texCoord + onePixel * vec2( 1,  0)) * u_kernel[5] +\ntexture2D(texture, v_texCoord + onePixel * vec2(-1,  1)) * u_kernel[6] +\ntexture2D(texture, v_texCoord + onePixel * vec2( 0,  1)) * u_kernel[7] +\ntexture2D(texture, v_texCoord + onePixel * vec2( 1,  1)) * u_kernel[8] ;\ngl_FragColor = vec4((colorSum / (u_kernelWeight + rand(gl_FragCoord.xy,u_time)*u_noiseIntensity)));\n}");
        _this.rt_w = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'rt_w');
        _this.rt_h = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'rt_h');
        _this.u_kernel = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_kernel[9]', true);
        _this.u_kernelWeight = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_kernelWeight');
        _this.u_noiseIntensity = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_noiseIntensity');
        _this.u_time = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_time');
        _this.setKernel([0, 0, 0, 0, 0, 0, 0, 0, 0]);
        _this.simpleRectDrawer.initProgram();
        return _this;
    }
    AbstractKernelAccumulativeFilter.prototype.doFilter = function (destFrameBuffer) {
        var _a = this.simpleRectDrawer.getAttachedTextureAt(0).size, width = _a.width, height = _a.height;
        this.setUniform(this.rt_w, width);
        this.setUniform(this.rt_h, height);
        this.setUniform(this.u_kernel, this.kernel);
        this.setUniform(this.u_kernelWeight, this.kernelWeight);
        this.setUniform(this.u_noiseIntensity, this.noiseIntensity);
        this.time += 0.01;
        this.setUniform(this.u_time, this.time);
        _super.prototype.doFilter.call(this, destFrameBuffer);
    };
    AbstractKernelAccumulativeFilter.prototype.setKernel = function (kernel) {
        var _this = this;
        this.kernel = kernel;
        this.kernelWeight = 0;
        this.kernel.forEach(function (it) { return _this.kernelWeight += it; });
    };
    AbstractKernelAccumulativeFilter.prototype.setNoiseIntensity = function (intensity) {
        this.noiseIntensity = intensity;
    };
    return AbstractKernelAccumulativeFilter;
}(abstractAccumulativeFilter_AbstractAccumulativeFilter));


// CONCATENATED MODULE: ./engine/renderer/webGl/filters/accumulative/kernelBurnAccumulativeFilter.ts


var kernelBurnAccumulativeFilter_KernelBurnAccumulativeFilter = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(KernelBurnAccumulativeFilter, _super);
    function KernelBurnAccumulativeFilter(game) {
        var _this = _super.call(this, game) || this;
        _this.setKernel([
            0.0, 0.0, 0.0,
            0.1, 0.0, 0.1,
            1.0, 1.0, 1.0
        ]);
        return _this;
    }
    return KernelBurnAccumulativeFilter;
}(abstractKernelAccumulativeFilter_AbstractKernelAccumulativeFilter));


// EXTERNAL MODULE: ./node_tools/loaders/xml/angelcode-loader.js!./demo/pix32/resources/font/font32.fnt
var font32 = __webpack_require__(6);

// CONCATENATED MODULE: ./engine/renderable/impl/general/nullGameObject.ts


var nullGameObject_NullGameObject = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(NullGameObject, _super);
    function NullGameObject(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        return _this;
    }
    NullGameObject.prototype.draw = function () { };
    return NullGameObject;
}(renderableModel_RenderableModel));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/_internal/markableNullGameObject.ts


var markableNullGameObject_MarkableNullGameObject = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(MarkableNullGameObject, _super);
    function MarkableNullGameObject(game) {
        var _this = _super.call(this, game) || this;
        _this._dirty = false;
        _this.size.addOnChangeListener(function () { return _this.markAsDirty(); });
        return _this;
    }
    MarkableNullGameObject.prototype.revalidate = function () {
        this._dirty = false;
        _super.prototype.revalidate.call(this);
    };
    MarkableNullGameObject.prototype.markAsDirty = function () {
        this._dirty = true;
    };
    MarkableNullGameObject.prototype.isDirty = function () {
        return this._dirty;
    };
    MarkableNullGameObject.prototype.update = function () {
        _super.prototype.update.call(this);
        if (this.isDirty()) {
            this.revalidate();
            this.onCleared();
        }
    };
    MarkableNullGameObject.prototype.onCleared = function () { };
    return MarkableNullGameObject;
}(nullGameObject_NullGameObject));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/_internal/defaultBackgroundObject.ts


var DEFAULT_BACKGROUND_OBJECT_TYPE = 'DefaultBackgroundObject';
var defaultBackgroundObject_DefaultBackgroundObject = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(DefaultBackgroundObject, _super);
    function DefaultBackgroundObject() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.type = DEFAULT_BACKGROUND_OBJECT_TYPE;
        return _this;
    }
    return DefaultBackgroundObject;
}(nullGameObject_NullGameObject));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/container.ts






var ContainerState;
(function (ContainerState) {
    ContainerState[ContainerState["NORMAL"] = 0] = "NORMAL";
    ContainerState[ContainerState["ACTIVE"] = 1] = "ACTIVE";
    ContainerState[ContainerState["HOVERED"] = 2] = "HOVERED";
    ContainerState[ContainerState["DISABLED"] = 3] = "DISABLED";
})(ContainerState || (ContainerState = {}));
var container_Container = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Container, _super);
    function Container(game) {
        var _this = _super.call(this, game) || this;
        _this.type = 'Container';
        _this.marginLeft = 0;
        _this.marginTop = 0;
        _this.marginRight = 0;
        _this.marginBottom = 0;
        _this.paddingLeft = 0;
        _this.paddingTop = 0;
        _this.paddingRight = 0;
        _this.paddingBottom = 0;
        _this.background = new nullGameObject_NullGameObject(_this.game);
        _this.backgroundHover = new defaultBackgroundObject_DefaultBackgroundObject(_this.game);
        _this.backgroundActive = new defaultBackgroundObject_DefaultBackgroundObject(_this.game);
        _this.backgroundDisabled = new defaultBackgroundObject_DefaultBackgroundObject(_this.game);
        _this.state = ContainerState.NORMAL;
        _this.clientRect = new rect_Rect();
        _this.hoverEffectListened = false;
        _this.activeEffectListened = false;
        _this.hovered = false;
        _this.clicked = false;
        _this.appendChild(_this.background);
        _this.appendChild(_this.backgroundHover);
        _this.appendChild(_this.backgroundActive);
        _this.appendChild(_this.backgroundDisabled);
        return _this;
    }
    Container.normalizeBorders = function (top, right, bottom, left) {
        if (right === undefined && bottom === undefined && left === undefined) {
            right = bottom = left = top;
        }
        else if (bottom === undefined && left === undefined) {
            bottom = top;
            left = right;
        }
        else if (left === undefined) {
            left = right;
        }
        return { top: top, right: right, bottom: bottom, left: left };
    };
    Container.prototype.setMargin = function (top, right, bottom, left) {
        var _a;
        (_a = Container.normalizeBorders(top, right, bottom, left), top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left);
        var thisWriteable = this;
        thisWriteable.marginTop = top;
        thisWriteable.marginRight = right;
        thisWriteable.marginBottom = bottom;
        thisWriteable.marginLeft = left;
        this.recalculateClientRect();
        this.fitBackgroundToSize();
        this.markAsDirty();
    };
    Container.prototype.setBackground = function (background) {
        this.replaceChild(this.background, background);
        this.background = background;
        this.fitBackgroundToSize();
    };
    Container.prototype.setBackgroundHover = function (backgroundHover) {
        this.replaceChild(this.backgroundHover, backgroundHover);
        this.backgroundHover = backgroundHover;
        this.fitBackgroundToSize();
        this.listenToHoverState();
    };
    Container.prototype.setBackgroundActive = function (backgroundActive) {
        this.replaceChild(this.backgroundActive, backgroundActive);
        this.backgroundActive = backgroundActive;
        this.fitBackgroundToSize();
        this.listenToActiveState();
    };
    Container.prototype.setBackgroundDisabled = function (backgroundDisabled) {
        this.replaceChild(this.backgroundDisabled, backgroundDisabled);
        this.backgroundDisabled = backgroundDisabled;
        this.fitBackgroundToSize();
    };
    Container.prototype.setPadding = function (top, right, bottom, left) {
        var _a;
        (_a = Container.normalizeBorders(top, right, bottom, left), top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left);
        var thisWriteable = this;
        thisWriteable.paddingTop = top;
        thisWriteable.paddingRight = right;
        thisWriteable.paddingBottom = bottom;
        thisWriteable.paddingLeft = left;
        this.recalculateClientRect();
        this.fitBackgroundToSize();
        this.markAsDirty();
    };
    Container.prototype.revalidate = function () {
        _super.prototype.revalidate.call(this);
        this.recalculateClientRect();
        this.fitBackgroundToSize();
        this.setState(this.state);
    };
    Container.prototype.getClientRect = function () {
        return this.clientRect;
    };
    Container.prototype.setState = function (state) {
        this.state = state;
        switch (state) {
            case ContainerState.ACTIVE: {
                var isDefaultBg = this.backgroundActive.type === DEFAULT_BACKGROUND_OBJECT_TYPE;
                this.background.visible = isDefaultBg;
                this.backgroundHover.visible = false;
                this.backgroundActive.visible = !isDefaultBg;
                this.backgroundDisabled.visible = false;
                break;
            }
            case ContainerState.HOVERED: {
                var isDefaultBg = this.backgroundHover.type === DEFAULT_BACKGROUND_OBJECT_TYPE;
                this.background.visible = isDefaultBg;
                this.backgroundHover.visible = !isDefaultBg;
                this.backgroundActive.visible = false;
                this.backgroundDisabled.visible = false;
                break;
            }
            case ContainerState.NORMAL: {
                this.background.visible = true;
                this.backgroundHover.visible = false;
                this.backgroundActive.visible = false;
                this.backgroundDisabled.visible = false;
                break;
            }
            case ContainerState.DISABLED: {
                var isDefaultBg = this.backgroundDisabled.type === DEFAULT_BACKGROUND_OBJECT_TYPE;
                this.background.visible = isDefaultBg;
                this.backgroundHover.visible = false;
                this.backgroundActive.visible = false;
                this.backgroundDisabled.visible = !isDefaultBg;
                break;
            }
        }
    };
    Container.prototype.listenToHoverState = function () {
        var _this = this;
        if (this.hoverEffectListened)
            return;
        this.on(MOUSE_EVENTS.mouseEnter, function (e) {
            if (_this.state === ContainerState.DISABLED)
                return;
            _this.hovered = true;
            _this.setState(ContainerState.HOVERED);
        });
        this.on(MOUSE_EVENTS.mouseLeave, function (e) {
            if (_this.state === ContainerState.DISABLED)
                return;
            _this.hovered = false;
            _this.setState(ContainerState.NORMAL);
        });
    };
    Container.prototype.listenToActiveState = function () {
        var _this = this;
        if (this.activeEffectListened)
            return;
        this.on(MOUSE_EVENTS.mouseDown, function (e) {
            if (_this.state === ContainerState.DISABLED)
                return;
            _this.clicked = true;
            _this.setState(ContainerState.ACTIVE);
        });
        this.on(MOUSE_EVENTS.mouseUp, function (e) {
            if (_this.state === ContainerState.DISABLED)
                return;
            _this.clicked = false;
            if (_this.hovered)
                _this.setState(ContainerState.HOVERED);
            else
                _this.setState(ContainerState.NORMAL);
        });
    };
    Container.prototype.fitBackgroundToSize = function () {
        this.background.setPosAndSize(this.marginLeft, this.marginTop, this.size.width - this.marginRight - this.marginLeft, this.size.height - this.marginBottom - this.marginTop);
        if (this.background.size.width <= 0) {
            this.background.pos.x = 0;
            this.background.size.width = this.size.width;
        }
        if (this.background.size.height <= 0) {
            this.background.pos.y = 0;
            this.background.size.height = this.size.height;
        }
        this.backgroundHover.setPosAndSize(this.background.pos.x, this.background.pos.y, this.background.size.width, this.background.size.height);
        this.backgroundActive.setPosAndSize(this.background.pos.x, this.background.pos.y, this.background.size.width, this.background.size.height);
        this.backgroundDisabled.setPosAndSize(this.background.pos.x, this.background.pos.y, this.background.size.width, this.background.size.height);
    };
    Container.prototype.recalculateClientRect = function () {
        this.clientRect.setXYWH(this.marginLeft + this.paddingLeft, this.marginTop + this.paddingTop, this.size.width - this.marginLeft - this.paddingLeft - this.marginRight - this.paddingRight, this.size.height - this.marginTop - this.paddingTop - this.marginBottom - this.paddingBottom);
        if (this.clientRect.width <= 0) {
            this.clientRect.x = 0;
            this.clientRect.width = this.size.width;
        }
        if (this.clientRect.height <= 0) {
            this.clientRect.y = 0;
            this.clientRect.height = this.size.height;
        }
    };
    return Container;
}(markableNullGameObject_MarkableNullGameObject));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/_internal/characterImage.ts




var characterImage_CharacterImage = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(CharacterImage, _super);
    function CharacterImage(game, font, characterInfo, color) {
        var _this = _super.call(this, game) || this;
        _this.font = font;
        _this.characterInfo = characterInfo;
        _this.colorCloned = false;
        var actualFont = characterInfo.font || font;
        _this.stretchMode = STRETCH_MODE.STRETCH;
        var _a = actualFont.fontContext.padding, padUp = _a[0], padRight = _a[1], padDown = _a[2], padLeft = _a[3];
        var charRect = actualFont.fontContext.symbols[characterInfo.rawChar] || actualFont.fontContext.symbols['?'];
        if (charRect === undefined) {
            var key = Object.keys(actualFont.fontContext.symbols)[0];
            if ( true && key === undefined) {
                throw new debugError_DebugError("Bad fontContext has been provided");
            }
            charRect = actualFont.fontContext.symbols[key];
        }
        if (true) {
            if (charRect.width === 0 || charRect.height === 0) {
                console.error(actualFont.fontContext);
                console.error(characterInfo);
                throw new debugError_DebugError("font context error: wrong character rect for symbol \"" + characterInfo.rawChar + "\"");
            }
        }
        _this.getSrcRect().setXYWH(charRect.x + padLeft, charRect.y + padUp, charRect.width - padLeft - padRight, charRect.height - padUp - padDown);
        if (_this.getSrcRect().width <= 0)
            _this.getSrcRect().width = 0.001;
        if (_this.getSrcRect().height <= 0)
            _this.getSrcRect().height = 0.001;
        _this.setScaleFromCurrFontSize(_this.characterInfo.scaleFromCurrFontSize);
        _this.pos.setXY(charRect.destOffsetX, charRect.destOffsetY);
        _this.setResourceLink(actualFont.getResourceLink());
        _this.transformPoint.setToCenter();
        if (!characterInfo.multibyte)
            _this.color = color;
        if (characterInfo.italic)
            _this.setItalic(true);
        if (characterInfo.bold)
            _this.setBold(true);
        if (characterInfo.color)
            _this.setColor(characterInfo.color);
        if (characterInfo.underlined)
            _this.setUnderLined(true);
        if (characterInfo.linedThrough)
            _this.setLinedThrough(true);
        _this.updateVisibility();
        return _this;
    }
    CharacterImage.prototype.setItalic = function (val) {
        if (val)
            this.skew.setX(val ? -0.2 : 0);
        this.characterInfo.italic = val;
    };
    CharacterImage.prototype.setBold = function (val) {
        var scale = val ? 1.2 : 1;
        if (val)
            this.scale.setXY(scale);
        this.characterInfo.bold = val;
    };
    CharacterImage.prototype.setColor = function (color) {
        if (this.characterInfo.multibyte)
            return;
        if (!this.colorCloned) {
            this.color = this.color.clone();
            this.colorCloned = true;
        }
        this.color.set(color);
        this.characterInfo.color = color;
        if (this.textDecoratorLine !== undefined)
            this.textDecoratorLine.color.set(this.color);
    };
    CharacterImage.prototype.setUnderLined = function (val) {
        if (val) {
            this.createTextDecoratorLineIfNotExists();
            this.textDecoratorLine.pos.setXY(1, this.size.height - this.textDecoratorLine.size.height);
            this.textDecoratorLine.visible = true;
        }
        else {
            if (this.textDecoratorLine)
                this.textDecoratorLine.visible = false;
        }
        this.characterInfo.underlined = val;
        this.updateVisibility();
    };
    CharacterImage.prototype.setLinedThrough = function (val) {
        if (val) {
            this.createTextDecoratorLineIfNotExists();
            this.textDecoratorLine.pos.setXY(0, (this.size.height - this.textDecoratorLine.size.height) / 2);
            this.textDecoratorLine.visible = true;
        }
        else {
            if (this.textDecoratorLine)
                this.textDecoratorLine.visible = false;
        }
        this.characterInfo.linedThrough = val;
        this.updateVisibility();
    };
    CharacterImage.prototype.getCharacterInfo = function () {
        return this.characterInfo;
    };
    CharacterImage.prototype.setScaleFromCurrFontSize = function (scaleFromCurrFontSize) {
        this.characterInfo.scaleFromCurrFontSize = scaleFromCurrFontSize;
        this.size.setWH(this.getSrcRect().width * scaleFromCurrFontSize, this.getSrcRect().height * scaleFromCurrFontSize);
    };
    CharacterImage.prototype.createTextDecoratorLineIfNotExists = function () {
        if (this.textDecoratorLine === undefined) {
            var textDecoratorLine = new rectangle_Rectangle(this.game);
            var height = ~~((this.font.fontContext.lineHeight * this.characterInfo.scaleFromCurrFontSize) / 12) || 1;
            textDecoratorLine.size.setWH(this.size.width + this.font.fontContext.spacing[0] * 2, height);
            textDecoratorLine.lineWidth = 0;
            this.appendChild(textDecoratorLine);
            this.textDecoratorLine = textDecoratorLine;
        }
        this.textDecoratorLine.fillColor.set(this.color);
    };
    CharacterImage.prototype.updateVisibility = function () {
        this.visible = !(this.characterInfo.rawChar === ' ' && !this.characterInfo.linedThrough && !this.characterInfo.underlined);
    };
    return CharacterImage;
}(image_Image));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/_internal/word.ts



var word_Word = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Word, _super);
    function Word(game, font, chars, color, pixelPerfect) {
        var _this = _super.call(this, game) || this;
        _this.font = font;
        _this.chars = chars;
        _this.color = color;
        _this.pixelPerfect = pixelPerfect;
        _this.caret = 0;
        chars.forEach(function (c) {
            var characterFont = c.font || font;
            var char = new characterImage_CharacterImage(game, font, c, color);
            char.setPixelPerfect(pixelPerfect);
            char.pos.setX(_this.caret);
            _this.caret += char.size.width + characterFont.fontContext.spacing[0];
            _this.appendChild(char);
            _this.size.width += char.size.width + characterFont.fontContext.spacing[0];
        });
        var maxRawHeight = Math.max.apply(Math, Object(tslib_es6["e" /* __spreadArrays */])(_this.children.map(function (it) { return it.size.height; }), [0]));
        var maxSpacingVertical = Math.max.apply(Math, Object(tslib_es6["e" /* __spreadArrays */])(_this.chars.map(function (it) { return it.font ? it.font.fontContext.spacing[1] : 0; }), [font.fontContext.spacing[1]]));
        _this.size.height = maxRawHeight + maxSpacingVertical;
        _this.rawValue = chars.join('');
        return _this;
    }
    Word.prototype.getMaxCharacterFontScale = function () {
        var _a;
        return (_a = Math.max.apply(Math, this.chars.map(function (it) { return it.scaleFromCurrFontSize; }))) !== null && _a !== void 0 ? _a : 1;
    };
    return Word;
}(nullGameObject_NullGameObject));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/textAlign.ts
var AlignTextContentVertical;
(function (AlignTextContentVertical) {
    AlignTextContentVertical[AlignTextContentVertical["TOP"] = 0] = "TOP";
    AlignTextContentVertical[AlignTextContentVertical["CENTER"] = 1] = "CENTER";
    AlignTextContentVertical[AlignTextContentVertical["BOTTOM"] = 2] = "BOTTOM";
})(AlignTextContentVertical || (AlignTextContentVertical = {}));
var AlignTextContentHorizontal;
(function (AlignTextContentHorizontal) {
    AlignTextContentHorizontal[AlignTextContentHorizontal["LEFT"] = 0] = "LEFT";
    AlignTextContentHorizontal[AlignTextContentHorizontal["CENTER"] = 1] = "CENTER";
    AlignTextContentHorizontal[AlignTextContentHorizontal["RIGHT"] = 2] = "RIGHT";
})(AlignTextContentHorizontal || (AlignTextContentHorizontal = {}));
var AlignText;
(function (AlignText) {
    AlignText[AlignText["LEFT"] = 0] = "LEFT";
    AlignText[AlignText["CENTER"] = 1] = "CENTER";
    AlignText[AlignText["RIGHT"] = 2] = "RIGHT";
    AlignText[AlignText["JUSTIFY"] = 3] = "JUSTIFY";
})(AlignText || (AlignText = {}));
var WordBrake;
(function (WordBrake) {
    WordBrake[WordBrake["PREDEFINED"] = 0] = "PREDEFINED";
    WordBrake[WordBrake["FIT"] = 1] = "FIT";
    WordBrake[WordBrake["PREDEFINED_BREAK_LONG_WORDS"] = 2] = "PREDEFINED_BREAK_LONG_WORDS";
})(WordBrake || (WordBrake = {}));

// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/_internal/textRow.ts





var textRow_TextRow = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(TextRow, _super);
    function TextRow(game, font, constrainWidth, rowSet) {
        var _this = _super.call(this, game) || this;
        _this.font = font;
        _this.constrainWidth = constrainWidth;
        _this.rowSet = rowSet;
        _this.caret = 0;
        _this.alignText = AlignText.LEFT;
        return _this;
    }
    TextRow.prototype.canAddWord = function (word) {
        if (this.children.length === 0)
            return true;
        var currentSpaceWidth = word.getMaxCharacterFontScale() * this.rowSet.DEFAULT_SPACE_CHAR_WIDTH;
        return this.caret + currentSpaceWidth + word.size.width <= this.constrainWidth;
    };
    TextRow.prototype.addWord = function (word, addWhiteSpaceBeforeIfNeed) {
        if (this.children.length !== 0 && addWhiteSpaceBeforeIfNeed) {
            var scaleFromCurrFontSize = word.getMaxCharacterFontScale();
            var space = new word_Word(this.game, this.font, [{ rawChar: ' ', multibyte: false, scaleFromCurrFontSize: scaleFromCurrFontSize }], color_Color.NONE, this.rowSet.isPixelPerfect());
            this._addWord(space);
        }
        this._addWord(word);
    };
    TextRow.prototype.complete = function () {
        if (this.children.length === 0) {
            this.size.height = this.font.fontContext.lineHeight + this.font.fontContext.spacing[1];
        }
        else {
            this.size.height = Math.max.apply(Math, this.children.map(function (it) { return it.size.height; }));
        }
    };
    TextRow.prototype.updateWordsVisibility = function () {
        for (var i = 0; i < this.children.length; i++) {
            var c = this.children[i];
            if ((c.pos.x + this.rowSet.pos.x + c.size.width) < 0)
                c.visible = false;
            else {
                c.visible = (c.pos.x + this.rowSet.pos.x) <= this.constrainWidth;
            }
        }
    };
    TextRow.prototype.getMaxCharacterFontScale = function () {
        var _a;
        return (_a = Math.max.apply(Math, this.children.map(function (it) { return it.getMaxCharacterFontScale(); }))) !== null && _a !== void 0 ? _a : 1;
    };
    TextRow.prototype.setAlignText = function (align) {
        var _this = this;
        if (this.children.length === 0)
            return;
        if (align === this.alignText)
            return;
        switch (align) {
            case AlignText.RIGHT:
                this.pos.setX(this.rowSet.size.width - this.size.width);
                break;
            case AlignText.CENTER:
                this.pos.setX((this.rowSet.size.width - this.size.width) / 2);
                break;
            case AlignText.LEFT:
                this.pos.setX(0);
                break;
            case AlignText.JUSTIFY:
                var onlyWords = this.children.filter(function (it) { return it.rawValue !== ' '; });
                var onlyWordsWidth = onlyWords.
                    map(function (it) { return it.size.width; }).
                    reduce(function (it, prev) { return it + prev; }, 0);
                var spaceCharWidth = this.getMaxCharacterFontScale() * this.rowSet.DEFAULT_SPACE_CHAR_WIDTH;
                var spaceWidth_1 = (this.rowSet.size.width - onlyWordsWidth) / (onlyWords.length - 1);
                if (spaceWidth_1 > spaceCharWidth * 2)
                    spaceWidth_1 = spaceCharWidth;
                this.removeChildren();
                this.caret = 0;
                onlyWords.forEach(function (w) {
                    if (_this.children.length !== 0) {
                        _this.caret += spaceWidth_1;
                    }
                    _this._addWord(w);
                });
                break;
        }
        this.alignText = align;
    };
    TextRow.prototype._addWord = function (word) {
        var _a, _b, _c;
        var lastCharacterFont = (_c = (_b = (_a = word.children[word.children.length - 1]) === null || _a === void 0 ? void 0 : _a.getCharacterInfo()) === null || _b === void 0 ? void 0 : _b.font) !== null && _c !== void 0 ? _c : this.font;
        word.pos.setX(this.caret);
        this.caret += word.size.width + lastCharacterFont.fontContext.spacing[0];
        this.appendChild(word);
        this.size.width += word.size.width + lastCharacterFont.fontContext.spacing[0];
    };
    return TextRow;
}(nullGameObject_NullGameObject));


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/_internal/textRowSet.ts







var textRowSet_TextRowSet = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(TextRowSet, _super);
    function TextRowSet(game, font, constrainSize, color) {
        var _this = _super.call(this, game) || this;
        _this.font = font;
        _this.constrainSize = constrainSize;
        _this.color = color;
        _this.DEFAULT_SPACE_CHAR_WIDTH = new word_Word(_this.game, _this.font, [{ rawChar: ' ', multibyte: false, scaleFromCurrFontSize: 1 }], color_Color.NONE, false).size.width;
        _this.caret = 0;
        return _this;
    }
    TextRowSet.prototype.addWord = function (word, applyNewLineIfCurrentIsFull, addWhiteSpaceBeforeIfNeed) {
        if (this.currentTextRow === undefined) {
            this.currentTextRow = new textRow_TextRow(this.game, this.font, this.constrainSize.width, this);
            this.appendChild(this.currentTextRow);
        }
        if (applyNewLineIfCurrentIsFull && !this.currentTextRow.canAddWord(word)) {
            this.newRow();
        }
        this.currentTextRow.addWord(word, addWhiteSpaceBeforeIfNeed);
    };
    TextRowSet.prototype.newRow = function () {
        if (this.currentTextRow === undefined) {
            this.currentTextRow = new textRow_TextRow(this.game, this.font, this.constrainSize.width, this);
            this.appendChild(this.currentTextRow);
        }
        this.currentTextRow.complete();
        this.caret += this.currentTextRow.size.height;
        this.currentTextRow = new textRow_TextRow(this.game, this.font, this.constrainSize.width, this);
        this.currentTextRow.pos.y = this.caret;
        this.appendChild(this.currentTextRow);
    };
    TextRowSet.prototype.setFont = function (font) {
        this.font = font;
    };
    TextRowSet.prototype.setWordBrake = function (wordBrake) {
        this.wordBrake = wordBrake;
    };
    TextRowSet.prototype.setPixelPerfect = function (value) {
        this.pixelPerfect = value;
    };
    TextRowSet.prototype.isPixelPerfect = function () {
        return this.pixelPerfect;
    };
    TextRowSet.prototype.setAlignTextContentHorizontal = function (align) {
        if (this.children.length === 0)
            return;
        switch (align) {
            case AlignTextContentHorizontal.CENTER:
                var pos = (this.constrainSize.width - this.size.width) / 2;
                if (pos < 0)
                    pos = 0;
                this.pos.x = pos;
                break;
            case AlignTextContentHorizontal.LEFT:
                this.pos.setX(0);
                break;
            case AlignTextContentHorizontal.RIGHT:
                this.pos.setX(this.constrainSize.width - this.size.width);
                break;
        }
        this.alignTextContentHorizontal = align;
    };
    TextRowSet.prototype.setAlignTextContentVertical = function (align) {
        if (this.children.length === 0)
            return;
        switch (align) {
            case AlignTextContentVertical.CENTER:
                var pos = (this.constrainSize.height - this.size.height) / 2;
                if (pos < 0)
                    pos = 0;
                this.pos.y = pos;
                break;
            case AlignTextContentVertical.TOP:
                this.pos.setY(0);
                break;
            case AlignTextContentVertical.BOTTOM:
                this.pos.setY(this.constrainSize.height - this.size.height);
                break;
        }
        this.alignTextContentVertical = align;
    };
    TextRowSet.prototype.setAlignText = function (align) {
        if (this.children.length === 0)
            return;
        if (align === this.alignText)
            return;
        this.children.forEach(function (c) { return c.setAlignText(align); });
    };
    TextRowSet.prototype.updateRowsVisibility = function () {
        for (var i = 0, max = this.children.length; i < max; i++) {
            var c = this.children[i];
            if ((c.pos.y + this.pos.y + c.size.height) < 0)
                c.visible = false;
            else {
                c.visible = (c.pos.y + this.pos.y) <= this.constrainSize.height;
                if (c.visible)
                    c.updateWordsVisibility();
            }
        }
    };
    TextRowSet.prototype.getWordBrake = function () {
        return this.wordBrake;
    };
    TextRowSet.prototype.setText = function (stringEx) {
        var _this = this;
        this.clear();
        switch (this.wordBrake) {
            case WordBrake.PREDEFINED_BREAK_LONG_WORDS:
            case WordBrake.PREDEFINED: {
                var applyNewLineIfCurrentIsFull_1 = this.wordBrake === WordBrake.PREDEFINED_BREAK_LONG_WORDS;
                stringEx.split(['\t', '\n', '\r', ' '], true).forEach(function (s) {
                    switch (s.getAllChars()[0].rawChar) {
                        case '\r':
                            break;
                        case '\n':
                            _this.newRow();
                            break;
                        case ' ':
                            _this.addWord(new word_Word(_this.game, _this.font, s.getAllChars(), _this.color, _this.pixelPerfect), applyNewLineIfCurrentIsFull_1, false);
                            break;
                        case '\t':
                            var char = s.getAllChars()[0];
                            char.rawChar = ' ';
                            _this.addWord(new word_Word(_this.game, _this.font, [char, char, char, char], _this.color, _this.pixelPerfect), applyNewLineIfCurrentIsFull_1, false);
                            break;
                        default:
                            _this.addWord(new word_Word(_this.game, _this.font, s.getAllChars(), _this.color, _this.pixelPerfect), applyNewLineIfCurrentIsFull_1, false);
                            break;
                    }
                });
                break;
            }
            case WordBrake.FIT: {
                stringEx.
                    split(['\t', '\n', '\r', ' '], false).filter(function (it) { return it.asRaw().trim().length; }).
                    forEach(function (s) {
                    _this.addWord(new word_Word(_this.game, _this.font, s.getAllChars(), _this.color, _this.pixelPerfect), true, true);
                });
                break;
            }
            default: {
                if (true)
                    throw new debugError_DebugError("unknown wordBrake value: " + this.wordBrake);
            }
        }
        if (this.currentTextRow !== undefined)
            this.currentTextRow.complete();
        this.fitSize();
    };
    TextRowSet.prototype.fitSize = function () {
        this.fitWidth();
        this.fitHeight();
    };
    TextRowSet.prototype.fitWidth = function () {
        this.size.width = Math.max.apply(Math, Object(tslib_es6["e" /* __spreadArrays */])(this.children.map(function (it) { return it.size.width; }), [0]));
    };
    TextRowSet.prototype.fitHeight = function () {
        var height = 0;
        this.children.forEach(function (row) { return height += row.size.height; });
        this.size.height = height;
    };
    TextRowSet.prototype.clear = function () {
        this.removeChildren();
        this.caret = 0;
        this.currentTextRow = undefined;
    };
    return TextRowSet;
}(nullGameObject_NullGameObject));


// CONCATENATED MODULE: ./engine/renderable/impl/geometry/line.ts




var line_Line = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Line, _super);
    function Line(game) {
        var _this = _super.call(this, game) || this;
        _this.borderRadius = 0;
        _this.pointTo = new point2d_Point2d(0, 0, function () { return _this.onPointChanged(); });
        _this._rectangleRepresentation = new rectangle_Rectangle(_this.game);
        _this.lineWidth = 1;
        _this._rectangleRepresentation.lineWidth = 0;
        return _this;
    }
    Line.prototype.setXYX1Y1 = function (x, y, x1, y1) {
        this.pos.setXY(x, y);
        this.pointTo.setXY(x1, y1);
        var dx = this.pointTo.x - this.pos.x;
        var dy = this.pointTo.y - this.pos.y;
        this.pointTo.setXY(dx, dy);
    };
    Line.prototype.clone = function () {
        var l = new Line(this.game);
        this.setClonedProperties(l);
        return l;
    };
    Line.prototype.draw = function () {
        this.game.getRenderer().drawLine(this);
    };
    Line.prototype.translate = function () {
        _super.prototype.translate.call(this);
        this.game.getRenderer().transformTranslate(0, -this.lineWidth / 2);
    };
    Line.prototype.getRectangleRepresentation = function () {
        this._rectangleRepresentation.borderRadius = this.borderRadius;
        this._rectangleRepresentation.fillColor = this.color;
        return this._rectangleRepresentation;
    };
    Line.prototype.setProps = function (props) {
        var _a, _b, _c, _d;
        _super.prototype.setProps.call(this, props);
        this.setXYX1Y1((_b = (_a = props.pos) === null || _a === void 0 ? void 0 : _a.x) !== null && _b !== void 0 ? _b : 0, (_d = (_c = props.pos) === null || _c === void 0 ? void 0 : _c.y) !== null && _d !== void 0 ? _d : 0, props.pointTo.x, props.pointTo.y);
        if (props.borderRadius)
            this.borderRadius = props.borderRadius;
    };
    Line.prototype.setClonedProperties = function (cloned) {
        cloned.borderRadius = this.borderRadius;
        cloned.pointTo.set(this.pointTo);
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    Line.prototype.onPointChanged = function () {
        var w = Math.abs(this.pointTo.x);
        var h = Math.abs(this.pointTo.y);
        var l = Math.sqrt(w * w + h * h) + this.lineWidth / 2;
        this.size.setWH(w, h + this.lineWidth);
        this._rectangleRepresentation.size.setWH(l, this.lineWidth);
        this.angle = Math.atan2(this.pointTo.y, this.pointTo.x);
        this.transformPoint.setXY(0, this.lineWidth / 2);
    };
    return Line;
}(shape_Shape));


// CONCATENATED MODULE: ./engine/renderable/impl/geometry/ellipse.ts



var ellipse_Ellipse = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Ellipse, _super);
    function Ellipse(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.type = 'Ellipse';
        _this.center = new point2d_Point2d();
        _this.arcAngleFrom = 0;
        _this.arcAngleTo = 0;
        _this.anticlockwise = false;
        _this.radiusX = 10;
        _this.radiusY = 20;
        _this.center.observe(function () {
            var maxR = _this._getMaxRadius();
            _this.pos.setXY(_this.center.x - maxR, _this.center.y - maxR);
        });
        _this.pos.observe(function () {
            var maxR = _this._getMaxRadius();
            _this.center.setXY(_this.pos.x + maxR, _this.pos.y + maxR);
        });
        return _this;
    }
    Object.defineProperty(Ellipse.prototype, "radiusX", {
        get: function () {
            return this._radiusX;
        },
        set: function (value) {
            if (this._radiusX === value)
                return;
            this._radiusX = value;
            this.size.setWH(this._getMaxRadius() * 2);
            this.center.forceTriggerChange();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Ellipse.prototype, "radiusY", {
        get: function () {
            return this._radiusY;
        },
        set: function (value) {
            if (this._radiusY === value)
                return;
            this._radiusY = value;
            this.size.setWH(this._getMaxRadius() * 2);
            this.center.forceTriggerChange();
        },
        enumerable: false,
        configurable: true
    });
    Ellipse.prototype.draw = function () {
        this.game.getRenderer().drawEllipse(this);
    };
    Ellipse.prototype.update = function () {
        _super.prototype.update.call(this);
    };
    Ellipse.prototype.clone = function () {
        var cloned = new Ellipse(this.game);
        this.setClonedProperties(cloned);
        return cloned;
    };
    Ellipse.prototype.setProps = function (props) {
        _super.prototype.setProps.call(this, props);
        if (props.center !== undefined)
            this.center.setXY(props.center.x, props.center.y);
        if (props.arcAngleFrom !== undefined)
            this.arcAngleFrom = props.arcAngleFrom;
        if (props.arcAngleTo !== undefined)
            this.arcAngleTo = props.arcAngleTo;
        if (props.anticlockwise !== undefined)
            this.anticlockwise = props.anticlockwise;
        if (props.radiusX !== undefined)
            this.radiusX = props.radiusX;
        if (props.radiusY !== undefined)
            this.radiusY = props.radiusY;
    };
    Ellipse.prototype.setClonedProperties = function (cloned) {
        cloned.radiusX = this.radiusX;
        cloned.radiusY = this.radiusY;
        cloned.arcAngleFrom = this.arcAngleFrom;
        cloned.arcAngleTo = this.arcAngleTo;
        cloned.anticlockwise = this.anticlockwise;
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    Ellipse.prototype._getMaxRadius = function () {
        return this._radiusX > this._radiusY ? this._radiusX : this._radiusY;
    };
    return Ellipse;
}(shape_Shape));


// CONCATENATED MODULE: ./engine/renderable/abstract/mesh.ts




var mesh_Mesh = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Mesh, _super);
    function Mesh(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.heightMapFactor = 0.01;
        _this.fillColor = color_Color.BLACK.clone();
        _this.colorMix = 0;
        _this.reflectivity = 0;
        _this.invertY = false;
        _this.vertexItemSize = 3;
        return _this;
    }
    Mesh.prototype.acceptLight = function (val) {
        if ( true && val) {
            if (!this.bufferInfo.normalBuffer) {
                throw new debugError_DebugError("can not accept light: normals are not specified");
            }
        }
        this._lightAccepted = val;
    };
    Mesh.prototype.isLightAccepted = function () {
        return this._lightAccepted;
    };
    Mesh.prototype.revalidate = function () {
        _super.prototype.revalidate.call(this);
        if (true) {
            if (!this.modelPrimitive)
                throw new debugError_DebugError("model primitive is not set");
            if (this.modelPrimitive.vertexArr.length % this.vertexItemSize !== 0) {
                console.error(this);
                throw new debugError_DebugError("Wrong vertexArr size, actual size is " + this.modelPrimitive.vertexArr.length + ",\n                    but number must be a multiple of " + this.vertexItemSize + " ");
            }
        }
    };
    Mesh.prototype.transform = function () {
        _super.prototype.transform.call(this);
        if (this.invertY)
            this.game.getRenderer().transformScale(1, -1, 1);
    };
    Mesh.prototype.draw = function () {
        this.game.getRenderer().drawMesh(this);
    };
    Mesh.prototype.setClonedProperties = function (cloned) {
        cloned.texture = this.texture;
        cloned.cubeMapTexture = this.cubeMapTexture;
        cloned.normalsTexture = this.normalsTexture;
        cloned.heightMapTexture = this.heightMapTexture;
        cloned.heightMapFactor = this.heightMapFactor;
        cloned.fillColor = this.fillColor.clone();
        cloned.colorMix = this.colorMix;
        cloned.reflectivity = this.reflectivity;
        cloned.depthTest = this.depthTest;
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    return Mesh;
}(renderableModel_RenderableModel));


// CONCATENATED MODULE: ./engine/renderable/impl/geometry/_internal/earClippingTriangulator.ts

var earClippingTriangulator_EarClippingTriangulator = (function () {
    function EarClippingTriangulator() {
        this.indices = [];
        this.vertexTypes = [];
        this.triangles = [];
    }
    EarClippingTriangulator.areVerticesClockwise = function (vertices, offset, count) {
        if (count <= 2)
            return false;
        var area = 0, p1x, p1y, p2x, p2y;
        for (var i = offset, n = offset + count - 3; i < n; i += 2) {
            p1x = vertices[i];
            p1y = vertices[i + 1];
            p2x = vertices[i + 2];
            p2y = vertices[i + 3];
            area += p1x * p2y - p2x * p1y;
        }
        p1x = vertices[offset + count - 2];
        p1y = vertices[offset + count - 1];
        p2x = vertices[offset];
        p2y = vertices[offset + 1];
        return area + p1x * p2y - p2x * p1y < 0;
    };
    EarClippingTriangulator.computeSpannedAreaSign = function (p1x, p1y, p2x, p2y, p3x, p3y) {
        var area = p1x * (p3y - p2y);
        area += p2x * (p1y - p3y);
        area += p3x * (p2y - p1y);
        if (area === 0)
            return 0;
        return area > 0 ? 1 : -1;
    };
    EarClippingTriangulator.prototype.computeTriangles = function (vertices) {
        this.vertices = vertices;
        var offset = 0;
        var count = vertices.length;
        if ( true && count % 2 !== 0)
            throw new debugError_DebugError("wrong vertices size");
        var vertexCount = this.vertexCount = ~~(count / 2);
        var vertexOffset = ~~(offset / 2);
        this.indices = [];
        if (EarClippingTriangulator.areVerticesClockwise(vertices, offset, count)) {
            for (var i = 0; i < vertexCount; i++)
                this.indices[i] = vertexOffset + i;
        }
        else {
            for (var i = 0, n = vertexCount - 1; i < vertexCount; i++)
                this.indices[i] = vertexOffset + n - i;
        }
        var vertexTypes = [];
        for (var i = 0, n = vertexCount; i < n; ++i)
            vertexTypes.push(this.classifyVertex(i));
        var triangles = this.triangles = [];
        this.vertexTypes = vertexTypes;
        this.triangulate();
        return triangles;
    };
    EarClippingTriangulator.prototype.triangulate = function () {
        var vertexTypes = this.vertexTypes;
        var triangles = this.triangles;
        while (this.vertexCount > 3) {
            var earTipIndex = this.findEarTip();
            this.cutEarTip(earTipIndex);
            var previousIndex = this.previousIndex(earTipIndex);
            var nextIndex = earTipIndex === this.vertexCount ? 0 : earTipIndex;
            vertexTypes[previousIndex] = this.classifyVertex(previousIndex);
            vertexTypes[nextIndex] = this.classifyVertex(nextIndex);
        }
        if (this.vertexCount === 3) {
            var indices = this.indices;
            triangles.push(indices[0]);
            triangles.push(indices[1]);
            triangles.push(indices[2]);
        }
        this.vertexTypes = vertexTypes;
        this.triangles = triangles;
    };
    EarClippingTriangulator.prototype.classifyVertex = function (index) {
        var indices = this.indices;
        var previous = indices[this.previousIndex(index)] * 2;
        var current = indices[index] * 2;
        var next = indices[this.nextIndex(index)] * 2;
        var vertices = this.vertices;
        return EarClippingTriangulator.computeSpannedAreaSign(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]);
    };
    EarClippingTriangulator.prototype.findEarTip = function () {
        var vertexCount = this.vertexCount;
        for (var i = 0; i < vertexCount; i++)
            if (this.isEarTip(i))
                return i;
        var vertexTypes = this.vertexTypes;
        for (var i = 0; i < vertexCount; i++)
            if (vertexTypes[i] !== EarClippingTriangulator._CONCAVE)
                return i;
        return 0;
    };
    EarClippingTriangulator.prototype.isEarTip = function (earTipIndex) {
        var vertexTypes = this.vertexTypes;
        if (vertexTypes[earTipIndex] === EarClippingTriangulator._CONCAVE)
            return false;
        var previousIndex = this.previousIndex(earTipIndex);
        var nextIndex = this.nextIndex(earTipIndex);
        var indices = this.indices;
        var p1 = indices[previousIndex] * 2;
        var p2 = indices[earTipIndex] * 2;
        var p3 = indices[nextIndex] * 2;
        var vertices = this.vertices;
        var p1x = vertices[p1], p1y = vertices[p1 + 1];
        var p2x = vertices[p2], p2y = vertices[p2 + 1];
        var p3x = vertices[p3], p3y = vertices[p3 + 1];
        for (var i = this.nextIndex(nextIndex); i !== previousIndex; i = this.nextIndex(i)) {
            if (vertexTypes[i] !== EarClippingTriangulator._CONVEX) {
                var v = indices[i] * 2;
                var vx = vertices[v];
                var vy = vertices[v + 1];
                if (EarClippingTriangulator.computeSpannedAreaSign(p3x, p3y, p1x, p1y, vx, vy) >= 0) {
                    if (EarClippingTriangulator.computeSpannedAreaSign(p1x, p1y, p2x, p2y, vx, vy) >= 0) {
                        if (EarClippingTriangulator.computeSpannedAreaSign(p2x, p2y, p3x, p3y, vx, vy) >= 0)
                            return false;
                    }
                }
            }
        }
        return true;
    };
    EarClippingTriangulator.prototype.cutEarTip = function (earTipIndex) {
        var indices = this.indices;
        var triangles = this.triangles;
        triangles.push(indices[this.previousIndex(earTipIndex)]);
        triangles.push(indices[earTipIndex]);
        triangles.push(indices[this.nextIndex(earTipIndex)]);
        this.triangles = triangles;
        this.indices.splice(earTipIndex, 1);
        this.vertexTypes.splice(earTipIndex, 1);
        this.vertexCount--;
    };
    EarClippingTriangulator.prototype.previousIndex = function (index) {
        return (index === 0 ? this.vertexCount : index) - 1;
    };
    EarClippingTriangulator.prototype.nextIndex = function (index) {
        return (index + 1) % this.vertexCount;
    };
    EarClippingTriangulator._CONCAVE = -1;
    EarClippingTriangulator._CONVEX = 1;
    return EarClippingTriangulator;
}());


// CONCATENATED MODULE: ./engine/renderable/impl/geometry/_internal/arcToBezier.ts
var TAU = Math.PI * 2;
var mapToEllipse = function (_a, rx, ry, cosphi, sinphi, centerx, centery) {
    var x = _a.x, y = _a.y;
    x *= rx;
    y *= ry;
    var xp = cosphi * x - sinphi * y;
    var yp = sinphi * x + cosphi * y;
    return {
        x: xp + centerx,
        y: yp + centery
    };
};
var approxUnitArc = function (ang1, ang2) {
    var a = ang2 === 1.5707963267948966
        ? 0.551915024494
        : ang2 === -1.5707963267948966
            ? -0.551915024494
            : 4 / 3 * Math.tan(ang2 / 4);
    var x1 = Math.cos(ang1);
    var y1 = Math.sin(ang1);
    var x2 = Math.cos(ang1 + ang2);
    var y2 = Math.sin(ang1 + ang2);
    return [
        {
            x: x1 - y1 * a,
            y: y1 + x1 * a
        },
        {
            x: x2 + y2 * a,
            y: y2 - x2 * a
        },
        {
            x: x2,
            y: y2
        }
    ];
};
var vectorAngle = function (ux, uy, vx, vy) {
    var sign = (ux * vy - uy * vx < 0) ? -1 : 1;
    var umag = Math.sqrt(ux * ux + uy * uy);
    var vmag = Math.sqrt(ux * ux + uy * uy);
    var dot = ux * vx + uy * vy;
    var div = dot / (umag * vmag);
    if (div > 1) {
        div = 1;
    }
    if (div < -1) {
        div = -1;
    }
    return sign * Math.acos(div);
};
var getArcCenter = function (px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) {
    var rxsq = Math.pow(rx, 2);
    var rysq = Math.pow(ry, 2);
    var pxpsq = Math.pow(pxp, 2);
    var pypsq = Math.pow(pyp, 2);
    var radicant = (rxsq * rysq) - (rxsq * pypsq) - (rysq * pxpsq);
    if (radicant < 0) {
        radicant = 0;
    }
    radicant /= (rxsq * pypsq) + (rysq * pxpsq);
    radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
    var centerxp = radicant * rx / ry * pyp;
    var centeryp = radicant * -ry / rx * pxp;
    var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
    var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;
    var vx1 = (pxp - centerxp) / rx;
    var vy1 = (pyp - centeryp) / ry;
    var vx2 = (-pxp - centerxp) / rx;
    var vy2 = (-pyp - centeryp) / ry;
    var ang1 = vectorAngle(1, 0, vx1, vy1);
    var ang2 = vectorAngle(vx1, vy1, vx2, vy2);
    if (sweepFlag === 0 && ang2 > 0) {
        ang2 -= TAU;
    }
    if (sweepFlag === 1 && ang2 < 0) {
        ang2 += TAU;
    }
    return [centerx, centery, ang1, ang2];
};
var arcToBezier = function (px, py, cx, cy, rx, ry, xAxisRotation, largeArcFlag, sweepFlag) {
    var _a;
    if (xAxisRotation === void 0) { xAxisRotation = 0; }
    if (largeArcFlag === void 0) { largeArcFlag = 0; }
    if (sweepFlag === void 0) { sweepFlag = 0; }
    var curves = [];
    if (rx === 0 || ry === 0) {
        return undefined;
    }
    var sinphi = Math.sin(xAxisRotation * TAU / 360);
    var cosphi = Math.cos(xAxisRotation * TAU / 360);
    var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2;
    var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2;
    if (pxp === 0 && pyp === 0) {
        return undefined;
    }
    rx = Math.abs(rx);
    ry = Math.abs(ry);
    var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) +
        Math.pow(pyp, 2) / Math.pow(ry, 2);
    if (lambda > 1) {
        rx *= Math.sqrt(lambda);
        ry *= Math.sqrt(lambda);
    }
    var centerx, centery, ang1, ang2;
    _a = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), centerx = _a[0], centery = _a[1], ang1 = _a[2], ang2 = _a[3];
    var ratio = Math.abs(ang2) / (TAU / 4);
    if (Math.abs(1.0 - ratio) < 0.0000001) {
        ratio = 1.0;
    }
    var segments = Math.max(Math.ceil(ratio), 1);
    ang2 /= segments;
    for (var i = 0; i < segments; i++) {
        curves.push(approxUnitArc(ang1, ang2));
        ang1 += ang2;
    }
    return curves.map(function (curve) {
        var _a = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), x1 = _a.x, y1 = _a.y;
        var _b = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), x2 = _b.x, y2 = _b.y;
        var _c = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), x = _c.x, y = _c.y;
        return { x: x, y: y, x1: x1, y1: y1, x2: x2, y2: y2 };
    });
};

// CONCATENATED MODULE: ./engine/renderable/impl/geometry/_internal/splineFromPoints.ts
var createSplinePathFromPoints = function (points) {
    var x = [];
    var y = [];
    var cnt = 0;
    for (var i = 0; i < points.length; i = i + 2) {
        x[cnt] = points[i];
        y[cnt] = points[i + 1];
        cnt++;
    }
    var px = computeControlPoints(x);
    var py = computeControlPoints(y);
    var numOfPoints = points.length / 2;
    var pathStr = '';
    for (var i = 0; i < numOfPoints - 1; i++) {
        pathStr += splineFromPoints_path(i, x[i], y[i], px.p1[i], py.p1[i], px.p2[i], py.p2[i], x[i + 1], y[i + 1]);
    }
    return pathStr;
};
var splineFromPoints_path = function (i, x1, y1, px1, py1, px2, py2, x2, y2) {
    var res = '';
    if (i === 0)
        res += "M " + x1 + " " + y1 + " ";
    res += " C " + px1 + " " + py1 + " " + px2 + " " + py2 + " " + x2 + " " + y2;
    return res;
};
var computeControlPoints = function (K) {
    var p1 = [];
    var p2 = [];
    var n = K.length - 1;
    var a = [];
    var b = [];
    var c = [];
    var r = [];
    a[0] = 0;
    b[0] = 2;
    c[0] = 1;
    r[0] = K[0] + 2 * K[1];
    for (var i = 1; i < n - 1; i++) {
        a[i] = 1;
        b[i] = 4;
        c[i] = 1;
        r[i] = 4 * K[i] + 2 * K[i + 1];
    }
    a[n - 1] = 2;
    b[n - 1] = 7;
    c[n - 1] = 0;
    r[n - 1] = 8 * K[n - 1] + K[n];
    for (var i = 1; i < n; i++) {
        var m = a[i] / b[i - 1];
        b[i] = b[i] - m * c[i - 1];
        r[i] = r[i] - m * r[i - 1];
    }
    p1[n - 1] = r[n - 1] / b[n - 1];
    for (var i = n - 2; i >= 0; --i) {
        p1[i] = (r[i] - c[i] * p1[i + 1]) / b[i];
    }
    for (var i = 0; i < n - 1; i++) {
        p2[i] = 2 * K[i + 1] - p1[i + 1];
    }
    p2[n - 1] = 0.5 * (K[n] + p1[n - 1]);
    return { p1: p1, p2: p2 };
};
var polarToCartesian = function (centerX, centerY, radius, angle) {
    return {
        x: centerX + (radius * Math.cos(angle)),
        y: centerY + (radius * Math.sin(angle))
    };
};
var describeArc = function (x, y, radius, startAngle, endAngle, anticlockwise) {
    if (anticlockwise === void 0) { anticlockwise = false; }
    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);
    var largeArcFlag = endAngle - startAngle <= Math.PI ? '0' : '1';
    return [
        "M", start.x, start.y,
        "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");
};

// CONCATENATED MODULE: ./engine/renderable/impl/geometry/polyLine.ts







var clearString = function (s) {
    return s.replace(/\s\s+/g, ' ').trim();
};
var add = function (a) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    var n = Object(tslib_es6["e" /* __spreadArrays */])(a);
    args.forEach(function (p) {
        n[0] += p[0];
        n[1] += p[1];
    });
    return n;
};
var mult = function (a, s) {
    return [a[0] * s, a[1] * s];
};
var polyLine_length = function (a, b) {
    return Math.sqrt(Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]));
};
var getPointOnBezierCurve = function (points, offset, t) {
    var invT = 1 - t;
    return add(mult(points[offset + 0], invT * invT * invT), mult(points[offset + 1], 3 * t * invT * invT), mult(points[offset + 2], 3 * invT * t * t), mult(points[offset + 3], t * t * t));
};
var getPointsOnBezierCurve = function (points, offset, numPoints) {
    var cPoints = [];
    for (var i = 0; i < numPoints - 1; ++i) {
        var t = i / (numPoints - 1);
        cPoints.push(getPointOnBezierCurve(points, offset, t));
    }
    cPoints[cPoints.length - 1] = points[points.length - 1];
    return cPoints;
};
var polyLine_SvgTokenizer = (function () {
    function SvgTokenizer(path) {
        this.path = path;
        this._pos = 0;
        this._CHAR = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        this._NUM = '01234567890.';
        this.path = clearString(path);
    }
    SvgTokenizer.prototype.isEof = function () {
        return this._pos === this.path.length;
    };
    SvgTokenizer.prototype.releaseNextToken = function () {
        if ( true && this._lastPos === undefined)
            throw new debugError_DebugError("can not release next token");
        this._pos = this._lastPos;
        this._lastPos = undefined;
    };
    SvgTokenizer.prototype.getNextCommand = function () {
        var tkn = this.getNextToken(this._CHAR, 1);
        if (!tkn)
            tkn = '' + this.getNextNumber();
        return tkn;
    };
    SvgTokenizer.prototype.getNextNumber = function () {
        this.skipWhiteSpaces();
        var lastPos = this._lastPos;
        var sign = 1;
        if (this.path[this._pos] === '-') {
            sign = -1;
            this._pos++;
        }
        var s = this.getNextToken(this._NUM);
        if (this.path[this._pos] === 'e') {
            this._pos++;
            s += 'e' + this.getNextNumber();
        }
        if ( true && s.length === 0) {
            throw new debugError_DebugError("can not read number, wrong next symbol: " + this.path[this._pos]);
        }
        var n = +s;
        if ( true && isNaN(n))
            throw new debugError_DebugError("can not read number: " + (sign === 1 ? '' : '-') + s);
        n *= sign;
        this._lastPos = lastPos;
        return n;
    };
    SvgTokenizer.prototype.skipWhiteSpaces = function () {
        while (!this.isEof()) {
            if ([',', ' '].indexOf(this.path[this._pos]) === -1)
                break;
            this._pos++;
        }
    };
    SvgTokenizer.prototype.getNextToken = function (allowedSymbols, limit) {
        if (limit === void 0) { limit = 0; }
        if ( true && this.isEof())
            throw new debugError_DebugError("unexpected end of string");
        var char;
        var res = '';
        this.skipWhiteSpaces();
        this._lastPos = this._pos;
        while (!this.isEof()) {
            char = this.path[this._pos];
            if (allowedSymbols.indexOf(char) === -1)
                break;
            if (limit > 0 && res.length === limit)
                break;
            res += char;
            this._pos++;
        }
        return res;
    };
    return SvgTokenizer;
}());
var polyLine_PolyLine = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(PolyLine, _super);
    function PolyLine(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.lastPenPoint = new point2d_Point2d();
        _this._borderRadius = 1;
        _this.closed = false;
        _this.interrupted = false;
        _this._lineWidth = 1;
        _this.color.addOnChangeListener(function () { return _this.passPropertiesChildren(); });
        return _this;
    }
    Object.defineProperty(PolyLine.prototype, "lineWidth", {
        get: function () {
            return this._lineWidth;
        },
        set: function (val) {
            this._lineWidth = val;
            this.passPropertiesChildren();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PolyLine.prototype, "borderRadius", {
        get: function () {
            return this._borderRadius;
        },
        set: function (val) {
            this._borderRadius = val;
            this.passPropertiesChildren();
        },
        enumerable: false,
        configurable: true
    });
    PolyLine.fromMultiCurveSvgPath = function (game, path) {
        var polyLines = [];
        var prefix = '';
        path.split('\n').join(' ').split(/(.*?z)/gi).forEach(function (p) {
            p = p.trim();
            if (!p)
                return;
            if (p.indexOf('m') === 0)
                p = prefix + " " + p;
            var polyLine = PolyLine.fromSvgPath(game, p);
            prefix = "M " + polyLine.lastPenPoint.x + " " + polyLine.lastPenPoint.y;
            polyLines.push(polyLine);
        });
        return polyLines;
    };
    PolyLine.fromPoints = function (game, points) {
        if (typeof points === 'string') {
            points = clearString(points).split(/[ |,]/).map(function (it) {
                var n = parseFloat(it);
                if ( true && isNaN(n))
                    throw new debugError_DebugError("can not parse vertex array " + points + ": unexpected value " + it);
                return n;
            });
        }
        if ( true && points.length === 0)
            throw new debugError_DebugError("can not create polyline from empty vertex array");
        var pl = new PolyLine(game);
        pl.moveTo(points[0], points[1]);
        for (var i = 2; i < points.length; i += 2) {
            pl.lineTo(points[i], points[i + 1]);
        }
        return pl;
    };
    PolyLine.fromSvgPath = function (game, path) {
        var pl = new PolyLine(game);
        pl.passMouseEventsThrough = true;
        pl.tokenizer = new polyLine_SvgTokenizer(path);
        var lastCommand;
        while (!pl.tokenizer.isEof()) {
            var command = pl.tokenizer.getNextCommand();
            if (isFinite(+command) && lastCommand) {
                pl.tokenizer.releaseNextToken();
                pl.executeCommand(lastCommand);
            }
            else {
                pl.executeCommand(command);
                lastCommand = command;
            }
        }
        return pl;
    };
    PolyLine.splineFromPoints = function (game, points) {
        return PolyLine.fromSvgPath(game, createSplinePathFromPoints(points));
    };
    PolyLine.prototype.moveTo = function (x, y) {
        if (this.children.length > 0)
            this.complete();
        if (!this.lastPoint)
            this.lastPoint = new point2d_Point2d();
        this.lastPoint.setXY(x, y);
        this.lastPenPoint.setXY(x, y);
        if (!this.firstPoint)
            this.firstPoint = new point2d_Point2d();
        this.firstPoint.setXY(x, y);
    };
    PolyLine.prototype.moveBy = function (x, y) {
        var lastX = this.lastPoint ? this.lastPoint.x : 0;
        var lastY = this.lastPoint ? this.lastPoint.y : 0;
        this.moveTo(lastX + x, lastY + y);
    };
    PolyLine.prototype.lineTo = function (x, y) {
        if (!this.lastPoint)
            this.lastPoint = new point2d_Point2d();
        if (!this.firstPoint)
            this.firstPoint = new point2d_Point2d(x, y);
        this.addSegment(this.lastPoint.x, this.lastPoint.y, x, y);
        this.lastPoint.setXY(x, y);
        this.lastPenPoint.setXY(x, y);
    };
    PolyLine.prototype.lineBy = function (x, y) {
        var lastX = this.lastPoint ? this.lastPoint.x : 0;
        var lastY = this.lastPoint ? this.lastPoint.y : 0;
        this.lineTo(lastX + x, lastY + y);
    };
    PolyLine.prototype.arcTo = function (rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) {
        this._arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y, false);
    };
    PolyLine.prototype.arcBy = function (rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) {
        this._arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y, true);
    };
    PolyLine.prototype.isClosed = function () {
        return (this.closed ||
            this.children[0].pos.equalPoint(this.children[this.children.length - 1].pos));
    };
    PolyLine.prototype.isInterrupted = function () {
        return this.interrupted;
    };
    PolyLine.prototype.close = function () {
        if ( true && !this.firstPoint)
            throw new debugError_DebugError("can not close polyline: no first point defined");
        this.lineTo(this.firstPoint.x, this.firstPoint.y);
        this.closed = true;
        this.complete();
    };
    PolyLine.prototype.clone = function () {
        var l = new PolyLine(this.game);
        this.setClonedProperties(l);
        return l;
    };
    PolyLine.prototype.draw = function () { };
    PolyLine.prototype.setClonedProperties = function (cloned) {
        _super.prototype.setClonedProperties.call(this, cloned);
    };
    PolyLine.prototype.bezierTo = function (p1, p2, p3, p4) {
        var _this = this;
        var l = polyLine_length(p1, p2) + polyLine_length(p2, p3) + polyLine_length(p3, p4);
        var bezier = getPointsOnBezierCurve([p1, p2, p3, p4], 0, l);
        bezier.forEach(function (v) {
            _this.lineTo(v[0], v[1]);
        });
    };
    PolyLine.prototype._arcTo = function (rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y, isRelativeCoordinates) {
        var _this = this;
        if ( true && largeArcFlag !== 0 && largeArcFlag !== 1)
            throw new debugError_DebugError("wrong largeArcFlag value: " + largeArcFlag);
        if ( true && sweepFlag !== 0 && sweepFlag !== 1)
            throw new debugError_DebugError("wrong largeArcFlag value: " + sweepFlag);
        if (isRelativeCoordinates) {
            x += this.lastPoint.x;
            y += this.lastPoint.y;
        }
        var arcs = arcToBezier(this.lastPoint.x, this.lastPoint.y, x, y, rx, ry, xAxisRotation, largeArcFlag, sweepFlag);
        if (arcs !== undefined)
            arcs.forEach(function (arc, i) {
                var xTo = arc.x;
                var yTo = arc.y;
                if (i === arcs.length - 1) {
                    xTo = x;
                    yTo = y;
                }
                _this.bezierTo([_this.lastPoint.x, _this.lastPoint.y], [arc.x1, arc.y1], [arc.x2, arc.y2], [xTo, yTo]);
            });
    };
    PolyLine.prototype.complete = function () {
        this.lastPoint = undefined;
        this.firstPoint = undefined;
        this.interrupted = true;
    };
    PolyLine.prototype.passPropertiesToChild = function (l) {
        l.borderRadius = this.borderRadius;
        l.color = this.color;
        l.lineWidth = this.lineWidth;
        l.pointTo.forceTriggerChange();
    };
    PolyLine.prototype.passPropertiesChildren = function () {
        var _this = this;
        this.children.forEach(function (l) { return _this.passPropertiesToChild(l); });
    };
    PolyLine.prototype.addSegment = function (x, y, x1, y1) {
        var line = new line_Line(this.game);
        this.passPropertiesToChild(line);
        line.setXYX1Y1(x, y, x1, y1);
        this.appendChild(line);
        var maxW = this.children[0].pos.x + this.children[0].size.width;
        var maxH = this.children[0].pos.y + this.children[0].size.height;
        for (var i = 1; i < this.children.length; i++) {
            if (this.children[i].pos.x + this.children[i].size.width > maxW)
                maxW = this.children[i].pos.x + this.children[i].size.width;
            if (this.children[i].pos.y + this.children[i].size.height > maxH)
                maxH = this.children[i].pos.y + this.children[i].size.height;
        }
        this.size.setWH(maxW, maxH);
    };
    PolyLine.prototype.executeCommand = function (command) {
        var tokenizer = this.tokenizer;
        switch (command) {
            case 'L': {
                this.lineTo(tokenizer.getNextNumber(), tokenizer.getNextNumber());
                break;
            }
            case 'l': {
                this.lineBy(tokenizer.getNextNumber(), tokenizer.getNextNumber());
                break;
            }
            case 'H': {
                this.lineTo(tokenizer.getNextNumber(), this.lastPoint.y);
                break;
            }
            case 'h': {
                this.lineBy(tokenizer.getNextNumber(), 0);
                break;
            }
            case 'V': {
                this.lineTo(this.lastPoint.x, tokenizer.getNextNumber());
                break;
            }
            case 'v': {
                this.lineBy(0, tokenizer.getNextNumber());
                break;
            }
            case 'M': {
                this.moveTo(tokenizer.getNextNumber(), tokenizer.getNextNumber());
                break;
            }
            case 'm': {
                this.moveBy(tokenizer.getNextNumber(), tokenizer.getNextNumber());
                break;
            }
            case 'C': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                var p2 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                var p3 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                var p4 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 'c': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                var p2 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                var p3 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                var p4 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                this.lastBezierPoint = add(p1, p3);
                this.bezierTo(p1, add(p1, p2), add(p1, p3), add(p1, p4));
                break;
            }
            case 'S': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                if (!this.lastBezierPoint || ['c', 'C', 'S', 's'].indexOf(tokenizer.lastCommand) === -1) {
                    this.lastBezierPoint = p1;
                }
                var p2 = [2 * p1[0] - this.lastBezierPoint[0], 2 * p1[1] - this.lastBezierPoint[1]];
                var p3 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                var p4 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 's': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                if (!this.lastBezierPoint || ['c', 'C', 'S', 's'].indexOf(tokenizer.lastCommand) === -1)
                    this.lastBezierPoint = p1;
                var p2 = [2 * p1[0] - this.lastBezierPoint[0], 2 * p1[1] - this.lastBezierPoint[1]];
                var p3 = add(p1, [tokenizer.getNextNumber(), tokenizer.getNextNumber()]);
                var p4 = add(p1, [tokenizer.getNextNumber(), tokenizer.getNextNumber()]);
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 'Q': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                var p2 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                var p3 = [p2[0], p2[1]];
                var p4 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 'q': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                var p2 = add(p1, [tokenizer.getNextNumber(), tokenizer.getNextNumber()]);
                var p3 = [p2[0], p2[1]];
                var p4 = add(p1, [tokenizer.getNextNumber(), tokenizer.getNextNumber()]);
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 'T': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                if (!this.lastBezierPoint || ['q', 'Q', 'T', 't'].indexOf(tokenizer.lastCommand) === -1)
                    this.lastBezierPoint = p1;
                var p2 = [2 * p1[0] - this.lastBezierPoint[0], 2 * p1[1] - this.lastBezierPoint[1]];
                var p3 = [p2[0], p2[1]];
                var p4 = [tokenizer.getNextNumber(), tokenizer.getNextNumber()];
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 't': {
                var p1 = [this.lastPoint.x, this.lastPoint.y];
                if (!this.lastBezierPoint || ['q', 'Q', 'T', 't'].indexOf(tokenizer.lastCommand) === -1)
                    this.lastBezierPoint = p1;
                var p2 = [2 * p1[0] - this.lastBezierPoint[0], 2 * p1[1] - this.lastBezierPoint[1]];
                var p3 = [p2[0], p2[1]];
                var p4 = add(p1, [tokenizer.getNextNumber(), tokenizer.getNextNumber()]);
                this.lastBezierPoint = p3;
                this.bezierTo(p1, p2, p3, p4);
                break;
            }
            case 'A':
            case 'a':
                var rx = tokenizer.getNextNumber();
                var ry = tokenizer.getNextNumber();
                var xAxisRotation = tokenizer.getNextNumber();
                var largeArcFlag = tokenizer.getNextNumber();
                var sweepFlag = tokenizer.getNextNumber();
                var x = tokenizer.getNextNumber();
                var y = tokenizer.getNextNumber();
                var relative = command === 'a';
                this._arcTo(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y, relative);
                break;
            case 'Z':
            case 'z':
                this.close();
                break;
            default:
                if (true)
                    throw new debugError_DebugError("unexpected command: '" + command + "'");
                break;
        }
        tokenizer.lastCommand = command;
    };
    return PolyLine;
}(shape_Shape));


// CONCATENATED MODULE: ./engine/renderable/impl/geometry/_internal/calcNormal.ts
var calcNormal = function (p1, p2, p3) {
    var a = {
        x: p2.x - p1.x,
        y: p2.y - p1.y,
        z: p2.z - p1.z,
    };
    var b = {
        x: p3.x - p1.x,
        y: p3.y - p1.y,
        z: p3.z - p1.z,
    };
    var n = {
        x: a.y * b.z - a.z * b.y,
        y: a.z * b.x - a.x * b.z,
        z: a.x * b.y - a.y * b.x
    };
    var l = Math.sqrt(n.x * n.x + n.y * n.y + n.z * n.z);
    return {
        x: n.x / l,
        y: n.y / l,
        z: n.z / l
    };
};

// CONCATENATED MODULE: ./engine/renderable/impl/geometry/_internal/isPolylineClockWise.ts
var isPolylineCloseWise = function (vertices) {
    var sum = 0.0;
    var l = vertices.length;
    for (var i = 0; i < l; i += 2) {
        var v1x = vertices[i];
        var v1y = vertices[(i + 1) % l];
        var v2x = vertices[(i + 2) % l];
        var v2y = vertices[(i + 3) % l];
        sum += (v2x - v1x) * (v2y + v1y);
    }
    return sum > 0.0;
};

// CONCATENATED MODULE: ./engine/renderable/impl/geometry/polygon.ts








var polygon_PolygonPrimitive = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(PolygonPrimitive, _super);
    function PolygonPrimitive() {
        var _this = _super.call(this) || this;
        _this.vertexArr = [];
        return _this;
    }
    return PolygonPrimitive;
}(AbstractPrimitive));
var polygon_Polygon = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Polygon, _super);
    function Polygon(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.type = 'Polygon';
        _this.invertY = false;
        _this.vertexItemSize = 2;
        return _this;
    }
    Polygon.fromMultiCurveSvgPath = function (game, path) {
        var polygons = [];
        var polyLines = polyLine_PolyLine.fromMultiCurveSvgPath(game, path);
        polyLines.forEach(function (p) { return polygons.push(Polygon.fromPolyline(game, p)); });
        return polygons;
    };
    Polygon.createStar = function (game, points, radius, innerRadius, rotation) {
        if (innerRadius === void 0) { innerRadius = radius / 2; }
        if (rotation === void 0) { rotation = 0; }
        var startAngle = (-1 * Math.PI / 2) + rotation;
        var len = points * 2;
        var delta = Math.PI * 2 / len;
        var vertices = [];
        for (var i = 0; i < len; i++) {
            var r = i % 2 ? innerRadius : radius;
            var angle = (i * delta) + startAngle;
            vertices.push((r * Math.cos(angle)), (r * Math.sin(angle)));
        }
        vertices.push(vertices[0], vertices[1]);
        var p = polyLine_PolyLine.fromPoints(game, vertices);
        return Polygon.fromPolyline(game, p);
    };
    Polygon.fromPolyline = function (game, p) {
        var vertices = [];
        p.children.forEach(function (l) {
            vertices.push(l.pos.x, l.pos.y);
        });
        var triangulator = new earClippingTriangulator_EarClippingTriangulator();
        var triangulatedIndices = triangulator.computeTriangles(vertices);
        var triangulatedVertices = [];
        for (var _i = 0, triangulatedIndices_1 = triangulatedIndices; _i < triangulatedIndices_1.length; _i++) {
            var ind = triangulatedIndices_1[_i];
            triangulatedVertices.push(vertices[2 * ind], vertices[2 * ind + 1]);
        }
        var pg = new Polygon(game);
        pg.setVertices(triangulatedVertices);
        pg.size.set(p.size);
        pg._edgeVertices = vertices;
        return pg;
    };
    Polygon.fromSvgPath = function (game, p) {
        if ( true && p.split(/z/gi).length - 1 > 1)
            throw new debugError_DebugError("multiple closing operation ('z') in one svg path. Use static method Polygon.fromMultiCurveSvgPath() instead");
        var polyline = polyLine_PolyLine.fromSvgPath(game, p);
        if ( true && !polyline.isClosed())
            throw new debugError_DebugError("can not create polygon from unclosed path");
        if ( true && !polyline.isInterrupted())
            throw new debugError_DebugError("can not create polygon from interrupted path");
        return Polygon.fromPolyline(game, polyline);
    };
    Polygon.fromPoints = function (game, points) {
        return Polygon.fromPolyline(game, polyLine_PolyLine.fromPoints(game, points));
    };
    Polygon.prototype.extrudeToMesh = function (depth) {
        var _a;
        var isClockWise = isPolylineCloseWise(this._edgeVertices);
        var primitive = new (function (_super) {
            Object(tslib_es6["c" /* __extends */])(class_1, _super);
            function class_1() {
                var _this = _super.call(this) || this;
                _this.normalArr = [];
                _this.vertexArr = [];
                _this.normalArr = [];
                return _this;
            }
            return class_1;
        }(AbstractPrimitive))();
        var d2 = depth / 2;
        for (var i = 0; i < this.modelPrimitive.vertexArr.length; i += 6) {
            var vertexA1 = this.modelPrimitive.vertexArr[i];
            var vertexA2 = this.modelPrimitive.vertexArr[i + 1];
            var vertexB1 = this.modelPrimitive.vertexArr[i + 2];
            var vertexB2 = this.modelPrimitive.vertexArr[i + 3];
            var vertexC1 = this.modelPrimitive.vertexArr[i + 4];
            var vertexC2 = this.modelPrimitive.vertexArr[i + 5];
            primitive.vertexArr.push(vertexA1, vertexA2, d2, vertexB1, vertexB2, d2, vertexC1, vertexC2, d2);
            primitive.normalArr.push(0, 0, 1, 0, 0, 1, 0, 0, 1);
            primitive.vertexArr.push(vertexA1, vertexA2, -d2, vertexB1, vertexB2, -d2, vertexC1, vertexC2, -d2);
            primitive.normalArr.push(0, 0, -1, 0, 0, -1, 0, 0, -1);
        }
        for (var i = 0; i < this._edgeVertices.length - 2; i += 2) {
            var edgeVertexA1 = this._edgeVertices[i];
            var edgeVertexA2 = this._edgeVertices[i + 1];
            var edgeVertexB1 = this._edgeVertices[i + 2];
            var edgeVertexB2 = this._edgeVertices[i + 3];
            if (!isClockWise) {
                _a = [edgeVertexB1, edgeVertexB2, edgeVertexA1, edgeVertexA2], edgeVertexA1 = _a[0], edgeVertexA2 = _a[1], edgeVertexB1 = _a[2], edgeVertexB2 = _a[3];
            }
            primitive.vertexArr.push(edgeVertexA1, edgeVertexA2, d2, edgeVertexB1, edgeVertexB2, d2, edgeVertexA1, edgeVertexA2, -d2, edgeVertexA1, edgeVertexA2, -d2, edgeVertexB1, edgeVertexB2, d2, edgeVertexB1, edgeVertexB2, -d2);
            var normal = calcNormal({ x: edgeVertexA1, y: edgeVertexA2, z: d2 }, { x: edgeVertexB1, y: edgeVertexB2, z: d2 }, { x: edgeVertexA1, y: edgeVertexA2, z: -d2 });
            primitive.normalArr.push(normal.x, normal.y, normal.z, normal.x, normal.y, normal.z, normal.x, normal.y, normal.z, normal.x, normal.y, normal.z, normal.x, normal.y, normal.z, normal.x, normal.y, normal.z);
        }
        var game = this.game;
        var m = new (function (_super) {
            Object(tslib_es6["c" /* __extends */])(class_2, _super);
            function class_2() {
                var _this = _super.call(this, game) || this;
                _this.invertY = true;
                _this.modelPrimitive = primitive;
                _this.vertexItemSize = 3;
                return _this;
            }
            return class_2;
        }(mesh_Mesh))();
        this.setClonedProperties(m);
        m.depthTest = true;
        return m;
    };
    Polygon.prototype.setVertices = function (vertices) {
        this.modelPrimitive = new polygon_PolygonPrimitive();
        this.modelPrimitive.vertexArr = vertices;
    };
    return Polygon;
}(mesh_Mesh));


// CONCATENATED MODULE: ./engine/renderable/impl/general/drawingSurface.ts

















var drawingSurface_ContainerForDrawingSurface = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(ContainerForDrawingSurface, _super);
    function ContainerForDrawingSurface(game, matrixStack) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        _this.matrixStack = matrixStack;
        _this._parentChildDelegate.afterChildAppended = undefined;
        _this._parentChildDelegate.afterChildRemoved = undefined;
        return _this;
    }
    ContainerForDrawingSurface.prototype.render = function () {
        var renderer = this.game.getRenderer();
        renderer.transformSave();
        renderer.transformSet.apply(renderer, this.matrixStack.getCurrentValue().mat16);
        renderer.transformTranslate(this.pos.x, this.pos.y);
        this.pos.setXY(0);
        this.worldTransformDirty = true;
        _super.prototype.render.call(this);
        this.game.getRenderer().transformRestore();
    };
    return ContainerForDrawingSurface;
}(nullGameObject_NullGameObject));
var drawingSurface_DrawingSurface = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(DrawingSurface, _super);
    function DrawingSurface(game, size) {
        var _this = _super.call(this, game) || this;
        _this.filters = [];
        _this.setResourceLink = undefined;
        _this._matrixStack = new matrixStack_MatrixStack();
        _this.canvasImage = new image_Image(_this.game);
        _this._rect = new rectangle_Rectangle(_this.game);
        _this._ellipse = new ellipse_Ellipse(_this.game);
        _this._line = new line_Line(_this.game);
        _this._nullGameObject = new nullGameObject_NullGameObject(_this.game);
        _this._transformableContainer = new drawingSurface_ContainerForDrawingSurface(_this.game, _this._matrixStack);
        _this.fillColor = color_Color.RGBA(0, 0, 0, 255);
        _this.drawColor = color_Color.RGBA(0, 0, 0, 255);
        _this._lineWidth = 1;
        _this._pointMoveTo = new point2d_Point2d();
        _this._omitSelfOnRendering = false;
        _this.size.set(size);
        _this.canvasImage.size.set(_this.size);
        _this._renderTarget = _this.game.getRenderer().getHelper().createRenderTarget(_this.game, size);
        _this.canvasImage.setResourceLink(_this._renderTarget.getResourceLink());
        _this.canvasImage.revalidate();
        return _this;
    }
    DrawingSurface.normalizeColor = function (col, g, b, a) {
        if (a === void 0) { a = 255; }
        if (b === undefined) {
            var color = color_Color.fromRGBNumeric(col);
            color.a = g;
            return color;
        }
        else {
            return new color_Color(col, g, b, a);
        }
    };
    DrawingSurface.prototype.clone = function () { return undefined; };
    DrawingSurface.prototype.draw = function () {
        if (this._omitSelfOnRendering)
            return;
        this.game.getRenderer().drawImage(this.canvasImage);
    };
    DrawingSurface.prototype.getResourceLink = function () {
        return this.canvasImage.getResourceLink();
    };
    DrawingSurface.prototype.setFillColor = function (col, g, b, a) {
        if (a === void 0) { a = 255; }
        this.fillColor.set(DrawingSurface.normalizeColor(col, g, b, a));
    };
    DrawingSurface.prototype.getFillColor = function () {
        return this.fillColor;
    };
    DrawingSurface.prototype.getDrawColor = function () {
        return this.drawColor;
    };
    DrawingSurface.prototype.setDrawColor = function (col, g, b, a) {
        if (a === void 0) { a = 255; }
        this.drawColor.set(DrawingSurface.normalizeColor(col, g, b, a));
    };
    DrawingSurface.prototype.setLineWidth = function (v) {
        this._lineWidth = v;
    };
    DrawingSurface.prototype.transformReset = function () {
        this._matrixStack.resetTransform();
    };
    DrawingSurface.prototype.transformSet = function (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        this._matrixStack.setMatrixValues(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15);
    };
    DrawingSurface.prototype.transformRestore = function () {
        this._matrixStack.restore();
    };
    DrawingSurface.prototype.transformRotateX = function (angleInRadians) {
        this._matrixStack.rotateX(angleInRadians);
    };
    DrawingSurface.prototype.transformRotateY = function (angleInRadians) {
        this._matrixStack.rotateY(angleInRadians);
    };
    DrawingSurface.prototype.transformRotateZ = function (angleInRadians) {
        this._matrixStack.rotateZ(angleInRadians);
    };
    DrawingSurface.prototype.transformSave = function () {
        this._matrixStack.save();
    };
    DrawingSurface.prototype.transformScale = function (x, y, z) {
        this._matrixStack.scale(x, y, z);
    };
    DrawingSurface.prototype.transformSkewX = function (angle) {
        this._matrixStack.skewX(angle);
    };
    DrawingSurface.prototype.transformSkewY = function (angle) {
        this._matrixStack.skewY(angle);
    };
    DrawingSurface.prototype.transformTranslate = function (x, y, z) {
        this._matrixStack.translate(x, y, z);
    };
    DrawingSurface.prototype.clear = function () {
        this.drawModel(this._nullGameObject, color_Color.NONE);
    };
    DrawingSurface.prototype.drawRoundedRect = function (x, y, width, height, radius) {
        this._rect.borderRadius = radius;
        this.drawRect(x, y, width, height);
    };
    DrawingSurface.prototype.drawRect = function (x, y, width, height) {
        if (width === 0 || height === 0)
            return;
        if (width < 0) {
            x -= width;
            width = -width;
        }
        if (height < 0) {
            y -= height;
            height = -height;
        }
        this._rect.pos.setXY(x, y);
        this._rect.size.setWH(width, height);
        this.drawSimpleShape(this._rect);
        this._rect.borderRadius = 0;
    };
    DrawingSurface.prototype.drawCircle = function (cx, cy, radius) {
        this.drawEllipse(cx, cy, radius, radius);
    };
    DrawingSurface.prototype.drawEllipse = function (cx, cy, radiusX, radiusY) {
        if (radiusX === 0 || radiusY === 0)
            return;
        this._ellipse.radiusX = radiusX;
        this._ellipse.radiusY = radiusY;
        this._ellipse.center.setXY(cx, cy);
        this._ellipse.arcAngleFrom = 0;
        this._ellipse.arcAngleTo = 0;
        this.drawSimpleShape(this._ellipse);
    };
    DrawingSurface.prototype.drawArc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) {
        if (anticlockwise === void 0) { anticlockwise = false; }
        if (radius === 0)
            return;
        this._ellipse.radiusX = radius;
        this._ellipse.radiusY = radius;
        this._ellipse.center.setXY(cx, cy);
        this._ellipse.arcAngleFrom = startAngle;
        this._ellipse.arcAngleTo = endAngle;
        this._ellipse.anticlockwise = anticlockwise;
        var fillColor = this.fillColor;
        this.fillColor = color_Color.NONE;
        this.drawSimpleShape(this._ellipse);
        this.fillColor = fillColor;
    };
    DrawingSurface.prototype.drawText = function (text, x, y) {
        if ( true && this._font === undefined) {
            throw new debugError_DebugError("font is not set");
        }
        if (this._textField === undefined)
            this._textField = new textField_TextFieldWithoutCache(this.game, this._font);
        this._textField.setFont(this._font);
        this._textField.setAutoSize(true);
        this._textField.setWordBrake(WordBrake.PREDEFINED);
        this._textField.textColor.set(this.drawColor);
        this._textField.pos.setXY(x, y);
        this._textField.setText(text);
        this.drawModel(this._textField);
    };
    DrawingSurface.prototype.setFont = function (font) {
        this._font = font;
    };
    DrawingSurface.prototype.fillArc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) {
        if (anticlockwise === void 0) { anticlockwise = false; }
        if (radius === 0)
            return;
        if (Math.abs(Math.abs(startAngle % (Math.PI * 2)) -
            Math.abs(endAngle % (Math.PI * 2))) <= 0.001) {
            var lineWidth = this._lineWidth;
            this._lineWidth = 0;
            this.drawCircle(cx, cy, radius);
            this._lineWidth = lineWidth;
        }
        else {
            if (anticlockwise) {
                var tmp = startAngle;
                startAngle = endAngle;
                endAngle = tmp + 2 * Math.PI;
            }
            var path = describeArc(cx, cy, radius, startAngle, endAngle, anticlockwise) + " z";
            var polygon = polygon_Polygon.fromSvgPath(this.game, path);
            polygon.fillColor = this.fillColor;
            this.drawModel(polygon);
        }
    };
    DrawingSurface.prototype.moveTo = function (x, y) {
        this._pointMoveTo.setXY(x, y);
    };
    DrawingSurface.prototype.lineTo = function (x, y) {
        this._line.setXYX1Y1(this._pointMoveTo.x, this._pointMoveTo.y, x, y);
        this.drawSimpleShape(this._line);
        this.moveTo(x, y);
    };
    DrawingSurface.prototype.drawPolygon = function (pathOrVertices) {
        if (pathOrVertices.push !== undefined) {
            this.drawPolygonFromVertices(pathOrVertices);
        }
        else {
            this.drawPolygonFromSvgPath(pathOrVertices);
        }
    };
    DrawingSurface.prototype.drawPolyline = function (pathOrVertices) {
        var p;
        if (Object(object["e" /* isString */])(pathOrVertices)) {
            p = polyLine_PolyLine.fromSvgPath(this.game, pathOrVertices);
        }
        else {
            p = polyLine_PolyLine.fromPoints(this.game, pathOrVertices);
        }
        p.fillColor = this.fillColor;
        p.color = this.drawColor;
        p.lineWidth = this._lineWidth;
        this.drawModel(p);
    };
    DrawingSurface.prototype.drawModel = function (model, clearColor) {
        if ( true && !model)
            throw new debugError_DebugError("illegal argument");
        var parent = model.parent;
        this.appendChild(this._transformableContainer);
        this._transformableContainer.appendChild(model);
        this._omitSelfOnRendering = true;
        this.renderToTexture(this._renderTarget, clearColor);
        this._omitSelfOnRendering = false;
        this.removeChild(this._transformableContainer);
        this._transformableContainer.removeChild(model);
        model.parent = parent;
    };
    DrawingSurface.prototype.setPixelPerfect = function (val) {
        this.canvasImage.setPixelPerfect(val);
    };
    DrawingSurface.prototype.destroy = function () {
        this._renderTarget.destroy();
    };
    DrawingSurface.prototype.drawPolygonFromSvgPath = function (svgPath) {
        var _this = this;
        var polyLines = polyLine_PolyLine.fromMultiCurveSvgPath(this.game, svgPath);
        polyLines.forEach(function (pl) {
            var pg = polygon_Polygon.fromPolyline(_this.game, pl);
            pg.fillColor = _this.fillColor;
            _this.drawModel(pg);
        });
        if (this._lineWidth > 0) {
            polyLines.forEach(function (pl) {
                pl.color = _this.drawColor;
                pl.lineWidth = _this._lineWidth;
                _this.drawModel(pl);
            });
        }
    };
    DrawingSurface.prototype.drawPolygonFromVertices = function (vertices) {
        var prev = vertices[vertices.length - 2];
        var last = vertices[vertices.length - 1];
        var first = vertices[0];
        var next = vertices[1];
        if (last !== next && prev !== first)
            vertices = Object(tslib_es6["e" /* __spreadArrays */])(vertices, [first, next]);
        var pl = polyLine_PolyLine.fromPoints(this.game, vertices);
        pl.color = this.drawColor;
        var pg = polygon_Polygon.fromPolyline(this.game, pl);
        pg.fillColor = this.fillColor;
        this.drawModel(pg);
        if (this._lineWidth > 0) {
            pl.lineWidth = this._lineWidth;
            this.drawModel(pl);
        }
    };
    DrawingSurface.prototype.prepareShape = function (shape) {
        shape.fillColor = this.fillColor;
        shape.lineWidth = this._lineWidth;
        shape.color = this.drawColor;
        shape.blendMode = BLEND_MODE.NORMAL_SEPARATE;
    };
    DrawingSurface.prototype.drawSimpleShape = function (shape) {
        this.prepareShape(shape);
        this.drawModel(shape);
    };
    return DrawingSurface;
}(renderableModel_RenderableModel));


// CONCATENATED MODULE: ./engine/misc/frameSkipper.ts
var FrameSkipper = (function () {
    function FrameSkipper(game) {
        this.game = game;
        this.numOfSkippedFrames = 0;
    }
    FrameSkipper.prototype.willNextFrameBeSkipped = function () {
        if (this.game.fps < 20) {
            this.numOfSkippedFrames++;
            if (this.numOfSkippedFrames < 8) {
                return true;
            }
            else {
                this.numOfSkippedFrames = 0;
                return false;
            }
        }
        this.numOfSkippedFrames = 0;
        return false;
    };
    return FrameSkipper;
}());


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/_internal/stringEx.ts
var StringEx = (function () {
    function StringEx(chars) {
        this.chars = chars;
    }
    StringEx.fromRaw = function (str) {
        var index = 0;
        var length = str.length;
        var output = [];
        for (; index < length; index++) {
            var charCode = str.charCodeAt(index);
            if (charCode >= 0xD800 && charCode <= 0xDBFF) {
                charCode = str.charCodeAt(index + 1);
                if (charCode >= 0xDC00 && charCode <= 0xDFFF) {
                    output.push({ rawChar: str.slice(index, index + 2), multibyte: true, scaleFromCurrFontSize: 1 });
                    index++;
                    continue;
                }
            }
            output.push({ rawChar: str.charAt(index), multibyte: false, scaleFromCurrFontSize: 1 });
        }
        return new StringEx(output);
    };
    StringEx.empty = function () {
        return new StringEx([]);
    };
    StringEx.prototype.split = function (delimiter, preserveDelimiter) {
        var _this = this;
        var result = [];
        var currentChars = [];
        this.chars.forEach(function (c, index) {
            if (delimiter.indexOf(c.rawChar) > -1) {
                if (currentChars.length > 0) {
                    result.push(new StringEx(currentChars));
                    currentChars = [];
                }
                if (preserveDelimiter) {
                    result.push(new StringEx([c]));
                }
            }
            else {
                currentChars.push(c);
            }
            if (index === _this.chars.length - 1 && currentChars.length > 0) {
                result.push(new StringEx(currentChars));
            }
        });
        return result;
    };
    StringEx.prototype.getAllChars = function () {
        return this.chars;
    };
    StringEx.prototype.append = function (str) {
        var _a;
        (_a = this.chars).push.apply(_a, str.chars);
    };
    StringEx.prototype.asRaw = function () {
        return this.chars.map(function (it) { return it.rawChar; }).join('');
    };
    StringEx.prototype.setBold = function (val) {
        this.chars.forEach(function (c) { return c.bold = val; });
    };
    StringEx.prototype.setItalic = function (val) {
        this.chars.forEach(function (c) { return c.italic = val; });
    };
    StringEx.prototype.setColor = function (col) {
        this.chars.forEach(function (c) { return c.color = col; });
    };
    StringEx.prototype.setFontSize = function (fontSize) {
        this.chars.forEach(function (c) { return c.fontSize = fontSize; });
    };
    StringEx.prototype.setScaleFromCurrFontSize = function (scale) {
        this.chars.forEach(function (c) { return c.scaleFromCurrFontSize = scale; });
    };
    StringEx.prototype.setUnderlined = function (val) {
        this.chars.forEach(function (c) { return c.underlined = val; });
    };
    StringEx.prototype.setLinedThrough = function (val) {
        this.chars.forEach(function (c) { return c.linedThrough = val; });
    };
    StringEx.prototype.setFont = function (font) {
        this.chars.forEach(function (c) { return c.font = font; });
    };
    return StringEx;
}());


// CONCATENATED MODULE: ./engine/renderable/impl/ui/textField/simple/textField.ts










var textField_TextField = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(TextField, _super);
    function TextField(game, font, useCache) {
        if (useCache === void 0) { useCache = true; }
        var _this = _super.call(this, game) || this;
        _this.font = font;
        _this.useCache = useCache;
        _this.type = 'TextField';
        _this.textColor = color_Color.RGB(122, 122, 122);
        _this.rowSetContainer = new markableNullGameObject_MarkableNullGameObject(_this.game);
        _this._textEx = StringEx.empty();
        _this.alignTextContentVertical = AlignTextContentVertical.TOP;
        _this.alignTextContentHorizontal = AlignTextContentHorizontal.LEFT;
        _this.alignText = AlignText.LEFT;
        _this.wordBrake = WordBrake.FIT;
        _this.pixelPerfect = false;
        _this._text = '';
        _this.frameSkipper = new FrameSkipper(_this.game);
        _this._autosize = false;
        _this.needTextRedraw = false;
        _this.appendChild(_this.rowSetContainer);
        _this.size.setWH(300, 100);
        _this.textColor.observe(function () { return _this.requestTextRedraw(); });
        return _this;
    }
    TextField.prototype.setText = function (text) {
        var strText = text.toString();
        if (strText === this._text)
            return;
        this._text = strText;
        this._textEx = StringEx.fromRaw(strText);
        this.markAsDirty();
    };
    TextField.prototype.setAutoSize = function (val) {
        this._autosize = val;
        this.markAsDirty();
    };
    TextField.prototype.setPixelPerfect = function (val) {
        this.pixelPerfect = val;
        this.markAsDirty();
    };
    TextField.prototype.revalidate = function () {
        if (this.useCache)
            this._revalidateWithCache();
        else
            this._revalidateWithoutCache();
    };
    TextField.prototype._revalidateWithCache = function () {
        if ( true && !this._autosize && (this.size.width === 0 || this.size.height === 0)) {
            throw new debugError_DebugError("can not setText: TextField size.width and/or size.height is not defined");
        }
        if (this._autosize)
            this.calculateAutoSize();
        _super.prototype.revalidate.call(this);
        var rectIsDirty = false;
        var clientRect = this.getClientRect();
        this.rowSetContainer.pos.set(clientRect);
        this.rowSetContainer.size.set(clientRect);
        if (this.cacheSurface === undefined) {
            this.cacheSurface = new drawingSurface_DrawingSurface(this.game, clientRect);
            this.rowSetContainer.appendChild(this.cacheSurface);
        }
        else {
            if (!this.cacheSurface.size.equal(clientRect)) {
                rectIsDirty = true;
                this.cacheSurface.destroy();
                var cacheSurface = new drawingSurface_DrawingSurface(this.game, clientRect);
                cacheSurface.setPixelPerfect(this.pixelPerfect);
                this.rowSetContainer.replaceChild(this.cacheSurface, cacheSurface);
                this.rowSetContainer.markAsDirty();
                this.cacheSurface = cacheSurface;
            }
        }
        if (this.rowSet === undefined || rectIsDirty)
            this.rowSet = new textRowSet_TextRowSet(this.game, this.font, clientRect, this.textColor);
        this._setText();
    };
    TextField.prototype._revalidateWithoutCache = function () {
        var clientRect = this.getClientRect();
        var rectIsDirty = true;
        if (this.rowSet !== undefined) {
            var currentClientRect = this.rowSet.getDestRect();
            rectIsDirty =
                clientRect.x !== currentClientRect.x ||
                    clientRect.y !== currentClientRect.y ||
                    clientRect.width !== currentClientRect.width ||
                    clientRect.height !== currentClientRect.height;
        }
        if (this.rowSet === undefined || rectIsDirty) {
            if (this.rowSet !== undefined)
                this.rowSet.removeSelf();
            this.rowSet = new textRowSet_TextRowSet(this.game, this.font, clientRect, this.textColor);
            this.rowSetContainer.appendChild(this.rowSet);
        }
        this.rowSetContainer.pos.set(clientRect);
        this.rowSetContainer.size.set(clientRect);
        this._setText();
        if (this._autosize) {
            this.size.setWH(this.rowSet.size.width + this.marginLeft + this.paddingLeft + this.marginRight + this.paddingRight, this.rowSet.size.height + this.marginTop + this.paddingTop + this.marginBottom + this.paddingBottom);
        }
        _super.prototype.revalidate.call(this);
    };
    TextField.prototype.getText = function () {
        return this._text;
    };
    TextField.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        if (this.cacheSurface !== undefined)
            this.cacheSurface.destroy();
    };
    TextField.prototype.update = function () {
        _super.prototype.update.call(this);
        if (this.isDirty())
            this.revalidate();
        if (this.needTextRedraw)
            this.redrawText();
    };
    TextField.prototype.setAlignTextContentHorizontal = function (align) {
        if (align === this.alignTextContentHorizontal)
            return;
        this.alignTextContentHorizontal = align;
        this.markAsDirty();
    };
    TextField.prototype.setWordBrake = function (wordBrake) {
        if (this.wordBrake === wordBrake)
            return;
        this.wordBrake = wordBrake;
        this.markAsDirty();
    };
    TextField.prototype.setAlignTextContentVertical = function (align) {
        if (align === this.alignTextContentVertical)
            return;
        this.alignTextContentVertical = align;
        this.markAsDirty();
    };
    TextField.prototype.setAlignText = function (align) {
        if (align === this.alignText)
            return;
        this.alignText = align;
        this.markAsDirty();
    };
    TextField.prototype.setFont = function (font) {
        if (font === this.font)
            return;
        this.font = font;
        this.markAsDirty();
    };
    TextField.prototype.setItalicAt = function (i, italic) {
        this.findCharImageByIndex(i).setItalic(italic);
        this.requestTextRedraw();
    };
    TextField.prototype.setBoldAt = function (i, bold) {
        this.findCharImageByIndex(i).setBold(bold);
        this.requestTextRedraw();
    };
    TextField.prototype.setColorAt = function (i, col) {
        this.findCharImageByIndex(i).setColor(col);
        this.requestTextRedraw();
    };
    TextField.prototype.collectAllChars = function () {
        var result = [];
        for (var m = 0; m < this.rowSet.children.length; m++) {
            var row = this.rowSet.children[m];
            for (var j = 0; j < row.children.length; j++) {
                var child = row.children[j];
                for (var k = 0; k < child.children.length; k++) {
                    var char = child.children[k];
                    result.push(char);
                }
            }
        }
        return result;
    };
    TextField.prototype.findCharImageByIndex = function (i) {
        var cnt = 0;
        for (var m = 0; m < this.rowSet.children.length; m++) {
            var row = this.rowSet.children[m];
            for (var j = 0; j < row.children.length; j++) {
                var child = row.children[j];
                for (var k = 0; k < child.children.length; k++) {
                    var char = child.children[k];
                    if (cnt === i)
                        return char;
                    cnt++;
                }
            }
        }
        return undefined;
    };
    TextField.prototype.requestTextRedraw = function () {
        this.needTextRedraw = true;
    };
    TextField.prototype.onCleared = function () {
        this.requestTextRedraw();
    };
    TextField.prototype._setText = function () {
        this.passPropertiesToRowSet(this.rowSet);
        this.requestTextRedraw();
    };
    TextField.prototype.calculateAutoSize = function () {
        if (this.measurer === undefined)
            this.measurer = new textRowSet_TextRowSet(this.game, this.font, { width: Infinity, height: Infinity }, color_Color.NONE);
        this.passPropertiesToRowSet(this.measurer);
        this.size.setWH(this.measurer.size.width + this.marginLeft + this.paddingLeft + this.marginRight + this.paddingRight, this.measurer.size.height + this.marginTop + this.paddingTop + this.marginBottom + this.paddingBottom);
        if (this.size.width === 0)
            this.size.width = 1;
        if (this.size.height === 0)
            this.size.height = 1;
    };
    TextField.prototype.passPropertiesToRowSet = function (rowSet) {
        rowSet.setFont(this.font);
        rowSet.setPixelPerfect(this.pixelPerfect);
        rowSet.setWordBrake(this.wordBrake);
        rowSet.setText(this._textEx);
        rowSet.setAlignText(this.alignText);
        rowSet.setAlignTextContentHorizontal(this.alignTextContentHorizontal);
        rowSet.setAlignTextContentVertical(this.alignTextContentVertical);
    };
    TextField.prototype.redrawText = function () {
        if (!this.needTextRedraw)
            return;
        this.rowSet.updateRowsVisibility();
        if (this.frameSkipper.willNextFrameBeSkipped())
            return;
        if (this.cacheSurface !== undefined) {
            this.cacheSurface.clear();
            this.cacheSurface.drawModel(this.rowSet);
        }
        this.needTextRedraw = false;
    };
    return TextField;
}(container_Container));

var textField_TextFieldWithoutCache = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(TextFieldWithoutCache, _super);
    function TextFieldWithoutCache(game, font) {
        var _this = _super.call(this, game, font, false) || this;
        _this.type = 'TextFieldWithoutCache';
        return _this;
    }
    TextFieldWithoutCache.prototype.requestTextRedraw = function () {
    };
    return TextFieldWithoutCache;
}(textField_TextField));


// CONCATENATED MODULE: ./engine/renderable/impl/general/imageCacheContainer.ts



var imageCacheContainer_ImageCacheContainer = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(ImageCacheContainer, _super);
    function ImageCacheContainer(game, drawingSurfaceSize) {
        var _this = _super.call(this, game) || this;
        _this.drawingSurfaceSize = drawingSurfaceSize;
        _this.drawingSurface = new drawingSurface_DrawingSurface(_this.game, _this.drawingSurfaceSize);
        _this.fakeEmptyChildrenArray = [];
        _this.childrenCache = [];
        _this.size.observe(function () { return _this.autoCalculateScale(); });
        _this.appendChild(_this.drawingSurface);
        return _this;
    }
    ImageCacheContainer.prototype.autoCalculateScale = function () {
        this.scale.setXY(this.size.width / this.drawingSurface.size.width, this.size.height / this.drawingSurface.size.height);
    };
    ImageCacheContainer.prototype.render = function () {
        this.childrenCache = this.children;
        this.children = this.fakeEmptyChildrenArray;
        _super.prototype.render.call(this);
        this.children = this.childrenCache;
    };
    ImageCacheContainer.prototype.draw = function () {
        this.drawingSurface.clear();
        for (var i = 0; i < this.childrenCache.length; i++) {
            var c = this.childrenCache[i];
            if (c === this.drawingSurface)
                continue;
            this.drawingSurface.drawModel(c);
        }
        this.drawingSurface.render();
    };
    ImageCacheContainer.prototype.setPixelPerfect = function (val) {
        this.drawingSurface.setPixelPerfect(val);
    };
    return ImageCacheContainer;
}(renderableModel_RenderableModel));


// CONCATENATED MODULE: ./engine/renderer/webGl/filters/texture/palletOffsetFilter.ts



var palletOffsetFilter_PalletOffsetFilter = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(PalletOffsetFilter, _super);
    function PalletOffsetFilter(game, pallet) {
        var _this = _super.call(this, game) || this;
        var programGen = _this.simpleRectDrawer.gen;
        _this.palletTexture = programGen.addScalarFragmentUniform(GL_TYPE.SAMPLER_2D, 'palletTexture');
        _this.palletTextureWidth = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'palletTextureWidth');
        _this.palletOffset = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'palletOffset');
        programGen.setFragmentMainFn("void main(){\nvec4 col = texture2D(texture, v_texCoord);\nfloat palletPoint = mod(col.r * palletTextureWidth + palletOffset,palletTextureWidth);\nfloat palletPointRelative = palletPoint/palletTextureWidth;\ngl_FragColor = texture2D(palletTexture, vec2(palletPointRelative,0.0));\ngl_FragColor.a = col.a;\n}");
        _this.setPalletOffset(0);
        _this.setPalletTexture(pallet);
        _this.setUniform(_this.palletTextureWidth, pallet.size.width);
        _this.simpleRectDrawer.initProgram();
        return _this;
    }
    PalletOffsetFilter.prototype.setPalletOffset = function (n) {
        this.setUniform(this.palletOffset, n);
    };
    PalletOffsetFilter.prototype.doFilter = function (destFrameBuffer) {
        this.simpleRectDrawer.attachTexture(this.palletTexture, this.palletTextureGl);
        _super.prototype.doFilter.call(this, destFrameBuffer);
    };
    PalletOffsetFilter.prototype.setPalletTexture = function (tx) {
        this.palletTextureGl = tx;
    };
    return PalletOffsetFilter;
}(abstractGlFilter_AbstractGlFilter));


// CONCATENATED MODULE: ./engine/renderer/webGl/filters/texture/noiseHorizontalFilter.ts



var noiseHorizontalFilter_NoiseHorizontalFilter = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(NoiseHorizontalFilter, _super);
    function NoiseHorizontalFilter(game) {
        var _this = _super.call(this, game) || this;
        _this.time = 0;
        var programGen = _this.simpleRectDrawer.gen;
        _this.rt_w = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'rt_w');
        _this.rt_h = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'rt_h');
        _this.u_time = programGen.addScalarFragmentUniform(GL_TYPE.FLOAT, 'u_time');
        programGen.appendFragmentCodeBlock("vec4 noise(vec2 uv) {\nvec3 color = texture2D(texture, uv).rgb;\ncolor -= abs(sin(uv.y * 100.0 + u_time * 5.0)) * 0.08;\ncolor -= abs(sin(uv.y * 300.0 - u_time * 10.0)) * 0.05;\nreturn vec4(color, 1.0).rgba;\n}");
        programGen.setFragmentMainFn("void main(){\nvec2 uv = vec2(gl_FragCoord.xy / vec2(rt_w,rt_h));\ngl_FragColor = noise(uv);\nvec4 colorOrig = texture2D(texture, v_texCoord);\ngl_FragColor.a = colorOrig.a;\n}");
        _this.simpleRectDrawer.initProgram();
        return _this;
    }
    NoiseHorizontalFilter.prototype.doFilter = function (destFrameBuffer) {
        var size = this.simpleRectDrawer.getAttachedTextureAt(0).size;
        this.setUniform(this.rt_w, size.width);
        this.setUniform(this.rt_h, size.height);
        this.setUniform(this.u_time, this.time += 0.01);
        _super.prototype.doFilter.call(this, destFrameBuffer);
    };
    return NoiseHorizontalFilter;
}(abstractGlFilter_AbstractGlFilter));


// CONCATENATED MODULE: ./demo/pix32/misc/chipOscilloscope.ts




var chipOscilloscope_ChipOscilloscope = (function () {
    function ChipOscilloscope(game, scene) {
        this.game = game;
        this.scene = scene;
        var container = new nullGameObject_NullGameObject(game);
        scene.topLayer.appendChild(container);
        container.pos.setXY(110, 410);
        var f = new noiseHorizontalFilter_NoiseHorizontalFilter(this.game);
        container.filters = [f];
        var indicatorA = new rectangle_Rectangle(game);
        indicatorA.size.setWH(1, 10);
        indicatorA.fillColor = color_Color.fromCssLiteral('#21ec3e');
        container.appendChild(indicatorA);
        var indicatorB = new rectangle_Rectangle(game);
        indicatorB.size.setWH(1, 10);
        indicatorB.pos.setXY(0, 10);
        indicatorB.fillColor = indicatorA.fillColor;
        container.appendChild(indicatorB);
        var indicatorC = new rectangle_Rectangle(game);
        indicatorC.size.setWH(1, 10);
        indicatorC.pos.setXY(0, 20);
        indicatorC.fillColor = indicatorA.fillColor;
        container.appendChild(indicatorC);
        this.indicatorA = indicatorA;
        this.indicatorB = indicatorB;
        this.indicatorC = indicatorC;
    }
    ChipOscilloscope.prototype.listen = function (sound, ym) {
        var _this = this;
        this.scene.setInterval((function () {
            var time = sound.getCurrentTimeSec();
            if (time === -1)
                return;
            var frame = ym.getFrameSnapshotByTimeSec(time);
            if (!frame)
                return;
            var periodA = (frame[1] & 0xF) << 8 | frame[0];
            var periodB = (frame[3] & 0xF) << 8 | frame[2];
            var periodC = (frame[5] & 0xF) << 8 | frame[4];
            var frA = (1000000 / (16 * periodA)) || 1;
            var frB = (1000000 / (16 * periodB)) || 1;
            var frC = (1000000 / (16 * periodC)) || 1;
            if (Number.isNaN(frA))
                frA = 1;
            if (Number.isNaN(frB))
                frB = 1;
            if (Number.isNaN(frC))
                frC = 1;
            if (frA === Infinity)
                frA = 1;
            if (frB === Infinity)
                frB = 1;
            if (frC === Infinity)
                frC = 1;
            _this.indicatorA.size.width = frA;
            _this.indicatorB.size.width = frB;
            _this.indicatorC.size.width = frC;
        }), 100);
    };
    return ChipOscilloscope;
}());


// CONCATENATED MODULE: ./demo/pix32/scenes/base/basePix32Scene.ts















var waitFor = function (game, time) {
    return new Promise(function (resolve) {
        game.getCurrScene().setTimeout(function () {
            resolve();
        }, time);
    });
};
var loadSound = function (game, ym) {
    var link = ResourceLink.create(undefined);
    var taskRef = game.getCurrScene().resourceLoader.q.addTask(function () { return Object(tslib_es6["b" /* __awaiter */])(void 0, void 0, void 0, function () {
        var arrayBuffer;
        return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4, ym.renderToArrayBuffer()];
                case 1:
                    arrayBuffer = _a.sent();
                    return [4, game.getAudioPlayer().loadSound(arrayBuffer, link)];
                case 2:
                    _a.sent();
                    game.getCurrScene().resourceLoader.q.resolveTask(taskRef);
                    return [2];
            }
        });
    }); });
    return link;
};
var basePix32Scene_BasePix32Scene = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(BasePix32Scene, _super);
    function BasePix32Scene(game) {
        var _this = _super.call(this, game) || this;
        _this.game = game;
        return _this;
    }
    BasePix32Scene.prototype.print = function (text, time, instant) {
        if (instant === void 0) { instant = false; }
        return Object(tslib_es6["b" /* __awaiter */])(this, void 0, Promise, function () {
            var tf;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        tf = this.textField;
                        tf.moveToFront();
                        tf.setText(text);
                        tf.revalidate();
                        tf.pos.setXY(0, 5);
                        this.addTween(new tween_Tween({
                            from: { x: 0 },
                            to: { x: -tf.size.width - 32 },
                            target: tf.pos,
                            time: time,
                            loop: instant,
                        }));
                        return [4, waitFor(this.game, time)];
                    case 1:
                        _a.sent();
                        if (!instant)
                            tf.setText("");
                        return [2];
                }
            });
        });
    };
    BasePix32Scene.prototype.onReady = function () {
        this.backgroundColor = color_Color.fromCssLiteral("#e2e2e2");
        this.btmLayer = new layer_Layer(this.game);
        this.appendChild(this.btmLayer);
        this.topLayer = new layer_Layer(this.game);
        this.topLayer.transformType = LayerTransformType.STICK_TO_CAMERA;
        this.appendChild(this.topLayer);
        var screen = new imageCacheContainer_ImageCacheContainer(this.game, new size_Size(32, 32));
        screen.size.setWH(377, 341);
        screen.pos.setXY(113, 58);
        screen.setPixelPerfect(true);
        this.btmLayer.appendChild(screen);
        this.screen = screen;
        var palletFilter = new palletOffsetFilter_PalletOffsetFilter(this.game, this.palletLink.getTarget());
        screen.filters = [palletFilter];
        var tf = new textField_TextField(this.game, this.fontLink.getTarget());
        tf.size.setWH(this.game.size.width * 3, this.game.size.height);
        tf.setPixelPerfect(true);
        tf.setAutoSize(true);
        tf.setWordBrake(WordBrake.PREDEFINED);
        tf.setAlignText(AlignText.CENTER);
        tf.setAlignTextContentHorizontal(AlignTextContentHorizontal.CENTER);
        tf.textColor.setRGBA(12, 100, 20, 255);
        screen.appendChild(tf);
        this.textField = tf;
        this.topLayer = new layer_Layer(this.game);
        this.topLayer.transformType = LayerTransformType.STICK_TO_CAMERA;
        this.appendChild(this.topLayer);
        var indicator = new rectangle_Rectangle(this.game);
        indicator.lineWidth = 0;
        var fillColorOn = color_Color.fromCssLiteral("#ff0000");
        var fillColorOff = color_Color.fromCssLiteral("#9f0404");
        indicator.pos.setXY(40, 162);
        indicator.size.setWH(60, 100);
        this.topLayer.appendChild(indicator);
        var on = false;
        indicator.setInterval(function () {
            on = !on;
            indicator.fillColor = on ? fillColorOn : fillColorOff;
        }, 2000);
        this.oscilloscope = new chipOscilloscope_ChipOscilloscope(this.game, this);
        var container = new image_Image(this.game);
        container.setResourceLink(this.containerLink);
        this.topLayer.appendChild(container);
    };
    BasePix32Scene.prototype.onPreloading = function () {
        var _this = this;
        _super.prototype.onPreloading.call(this);
        this.resourceLoader.addNextTask(function () {
            _this.fontLink = _this.resourceLoader.loadFontFromAtlas("./pix32/resources/font/font32.png", font32);
        });
        this.resourceLoader.addNextTask(function () {
            _this.palletLink = _this.resourceLoader.loadTexture("./pix32/resources/images/pallet.png");
        });
        this.resourceLoader.addNextTask(function () {
            _this.containerLink = _this.resourceLoader.loadTexture("./pix32/resources/images/container.png");
        });
    };
    return BasePix32Scene;
}(scene_Scene));


// CONCATENATED MODULE: ./engine/control/keyboard/keyboardKeys.ts
var KEYBOARD_KEY;
(function (KEYBOARD_KEY) {
    KEYBOARD_KEY[KEYBOARD_KEY["ENTER"] = 13] = "ENTER";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_0"] = 48] = "DIGIT_0";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_1"] = 49] = "DIGIT_1";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_2"] = 50] = "DIGIT_2";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_3"] = 51] = "DIGIT_3";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_4"] = 52] = "DIGIT_4";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_5"] = 53] = "DIGIT_5";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_6"] = 54] = "DIGIT_6";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_7"] = 55] = "DIGIT_7";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_8"] = 56] = "DIGIT_8";
    KEYBOARD_KEY[KEYBOARD_KEY["DIGIT_9"] = 57] = "DIGIT_9";
    KEYBOARD_KEY[KEYBOARD_KEY["SPACE"] = 32] = "SPACE";
    KEYBOARD_KEY[KEYBOARD_KEY["A"] = 65] = "A";
    KEYBOARD_KEY[KEYBOARD_KEY["B"] = 66] = "B";
    KEYBOARD_KEY[KEYBOARD_KEY["C"] = 67] = "C";
    KEYBOARD_KEY[KEYBOARD_KEY["D"] = 68] = "D";
    KEYBOARD_KEY[KEYBOARD_KEY["E"] = 69] = "E";
    KEYBOARD_KEY[KEYBOARD_KEY["F"] = 70] = "F";
    KEYBOARD_KEY[KEYBOARD_KEY["G"] = 71] = "G";
    KEYBOARD_KEY[KEYBOARD_KEY["H"] = 72] = "H";
    KEYBOARD_KEY[KEYBOARD_KEY["I"] = 73] = "I";
    KEYBOARD_KEY[KEYBOARD_KEY["J"] = 74] = "J";
    KEYBOARD_KEY[KEYBOARD_KEY["K"] = 75] = "K";
    KEYBOARD_KEY[KEYBOARD_KEY["L"] = 76] = "L";
    KEYBOARD_KEY[KEYBOARD_KEY["M"] = 77] = "M";
    KEYBOARD_KEY[KEYBOARD_KEY["N"] = 78] = "N";
    KEYBOARD_KEY[KEYBOARD_KEY["O"] = 79] = "O";
    KEYBOARD_KEY[KEYBOARD_KEY["P"] = 80] = "P";
    KEYBOARD_KEY[KEYBOARD_KEY["Q"] = 81] = "Q";
    KEYBOARD_KEY[KEYBOARD_KEY["R"] = 82] = "R";
    KEYBOARD_KEY[KEYBOARD_KEY["S"] = 83] = "S";
    KEYBOARD_KEY[KEYBOARD_KEY["T"] = 84] = "T";
    KEYBOARD_KEY[KEYBOARD_KEY["U"] = 85] = "U";
    KEYBOARD_KEY[KEYBOARD_KEY["V"] = 86] = "V";
    KEYBOARD_KEY[KEYBOARD_KEY["W"] = 87] = "W";
    KEYBOARD_KEY[KEYBOARD_KEY["X"] = 88] = "X";
    KEYBOARD_KEY[KEYBOARD_KEY["Y"] = 89] = "Y";
    KEYBOARD_KEY[KEYBOARD_KEY["Z"] = 90] = "Z";
    KEYBOARD_KEY[KEYBOARD_KEY["LEFT"] = 37] = "LEFT";
    KEYBOARD_KEY[KEYBOARD_KEY["UP"] = 38] = "UP";
    KEYBOARD_KEY[KEYBOARD_KEY["RIGHT"] = 39] = "RIGHT";
    KEYBOARD_KEY[KEYBOARD_KEY["DOWN"] = 40] = "DOWN";
    KEYBOARD_KEY[KEYBOARD_KEY["ALT"] = 18] = "ALT";
    KEYBOARD_KEY[KEYBOARD_KEY["BACKSPACE"] = 8] = "BACKSPACE";
    KEYBOARD_KEY[KEYBOARD_KEY["CAPS_LOCK"] = 20] = "CAPS_LOCK";
    KEYBOARD_KEY[KEYBOARD_KEY["ESC"] = 27] = "ESC";
    KEYBOARD_KEY[KEYBOARD_KEY["CONTROL"] = 17] = "CONTROL";
    KEYBOARD_KEY[KEYBOARD_KEY["DELETE"] = 46] = "DELETE";
    KEYBOARD_KEY[KEYBOARD_KEY["HOME"] = 36] = "HOME";
    KEYBOARD_KEY[KEYBOARD_KEY["END"] = 35] = "END";
    KEYBOARD_KEY[KEYBOARD_KEY["TAB"] = 9] = "TAB";
})(KEYBOARD_KEY || (KEYBOARD_KEY = {}));

// CONCATENATED MODULE: ./demo/pix32/ym-player/internal/binBuffer.ts

var binBuffer_BinBuffer = (function () {
    function BinBuffer(arrOrSize) {
        this.pointer = 0;
        if (Object(object["b" /* isCommonArray */])(arrOrSize)) {
            var buffer = new ArrayBuffer(arrOrSize.length);
            this.view = new DataView(buffer);
            this.inflate(arrOrSize);
        }
        else if (arrOrSize.byteLength) {
            this.view = new DataView(arrOrSize);
        }
        else {
            var buffer = new ArrayBuffer(arrOrSize);
            this.view = new DataView(buffer);
        }
    }
    BinBuffer.arrayToArrayBuffer = function (array) {
        var length = array.length;
        var buffer = new ArrayBuffer(length);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < length; i++) {
            view[i] = array[i];
        }
        return view;
    };
    BinBuffer.isBitSet = function (nBit, n) {
        var mask = 1 << nBit;
        return (n & mask) > 0;
    };
    BinBuffer.prototype.getPointer = function () {
        return this.pointer;
    };
    BinBuffer.prototype.setPointer = function (n) {
        this.pointer = n;
    };
    BinBuffer.prototype.resetPointer = function () {
        this.pointer = 0;
    };
    BinBuffer.prototype.getView = function () {
        return this.view;
    };
    BinBuffer.prototype.getArray = function () {
        var res = new Array(this.view.buffer.byteLength);
        for (var i = 0; i < this.view.buffer.byteLength; i++) {
            res[i] = this.view.getInt8(i);
        }
        return res;
    };
    BinBuffer.prototype.inflate = function (arr) {
        for (var i = 0; i < arr.length; i++) {
            this.writeByte(arr[i]);
        }
        this.resetPointer();
    };
    BinBuffer.prototype.writeString = function (string) {
        for (var i = 0; i < string.length; i++) {
            this.view.setUint8(this.pointer + i, string.charCodeAt(i));
        }
        this.pointer += string.length;
    };
    BinBuffer.prototype.writeUInt32 = function (n, littleEndian) {
        this.view.setUint32(this.pointer, n, littleEndian);
        this.pointer += 4;
    };
    BinBuffer.prototype.writeUInt16 = function (n, littleEndian) {
        this.view.setUint16(this.pointer, n, littleEndian);
        this.pointer += 2;
    };
    BinBuffer.prototype.writeByte = function (n) {
        this.view.setUint8(this.pointer, n);
        this.pointer++;
    };
    BinBuffer.prototype.readString = function (size) {
        var res = '';
        for (var i = 0; i < size; i++) {
            res += String.fromCharCode(this.view.getUint8(this.pointer + i));
        }
        this.pointer += size;
        return res;
    };
    BinBuffer.prototype.readNTString = function () {
        var res = '';
        var size = 0;
        var uint8;
        while ((uint8 = this.view.getUint8(this.pointer + size)) !== 0) {
            res += String.fromCharCode(uint8);
            size++;
        }
        this.pointer += ++size;
        return res;
    };
    BinBuffer.prototype.readByte = function () {
        var res = this.view.getUint8(this.pointer);
        this.pointer++;
        return res;
    };
    BinBuffer.prototype.readByteAt = function (pos) {
        return this.view.getUint8(pos);
    };
    BinBuffer.prototype.readBytes = function (n) {
        var res = [];
        for (var i = 0; i < n; i++) {
            res.push(this.readByte());
        }
        return res;
    };
    BinBuffer.prototype.readBytesToArray = function (arr, off, length) {
        var readed = 0;
        for (var i = 0; i < length; i++) {
            var pos = i + off;
            if (this.pointer < this.view.byteLength - 1) {
                arr[pos] = this.readByte();
                readed++;
            }
        }
        return readed;
    };
    BinBuffer.prototype.readBytesToArray_2 = function (arr) {
        return this.readBytesToArray(arr, 0, arr.length);
    };
    BinBuffer.prototype.readUInt32 = function (littleEndian) {
        var data = this.view.getUint32(this.pointer, littleEndian);
        this.pointer += 4;
        return data;
    };
    BinBuffer.prototype.readUInt16 = function (littleEndian) {
        var data = this.view.getUint16(this.pointer, littleEndian);
        this.pointer += 2;
        return data;
    };
    BinBuffer.prototype.skip = function (n) {
        this.pointer += n;
        return n;
    };
    return BinBuffer;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/CRC16.ts
var CRC16 = (function () {
    function CRC16() {
    }
    CRC16.prototype.CRC16 = function () {
        this.crc = 0;
    };
    CRC16.prototype.update = function (b) {
        this.crc = CRC16.CRC_TABLE[(this.crc ^ b) & 0xFF] ^ (this.crc >>> CRC16.CHAR_BIT);
    };
    CRC16.prototype.update_2 = function (b, off, len) {
        while (len-- > 0) {
            this.crc = CRC16.CRC_TABLE[(this.crc ^ b[off++]) & 0xFF] ^ (this.crc >>> CRC16.CHAR_BIT);
        }
    };
    CRC16.prototype.getValue = function () {
        return this.crc & 0xFFFF;
    };
    CRC16.prototype.reset = function () {
        this.crc = 0;
    };
    CRC16.CHAR_BIT = 8;
    CRC16.CRC_TABLE = [
        0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0,
        0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01,
        0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40,
        0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81,
        0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1,
        0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100,
        0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
        0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81,
        0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1,
        0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01,
        0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541,
        0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080,
        0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1,
        0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01,
        0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
        0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80,
        0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1,
        0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, 0x5000,
        0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741,
        0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81,
        0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0,
        0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01,
        0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
        0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
    ];
    return CRC16;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhaEntry.ts
var LhaEntry = (function () {
    function LhaEntry() {
        this.fcrc = false;
        this.offset = -1;
    }
    LhaEntry.prototype.setMethod = function (method) {
        if ([
            LhaEntry.METHOD_SIG_LHD,
            LhaEntry.METHOD_SIG_LH0,
            LhaEntry.METHOD_SIG_LH1,
            LhaEntry.METHOD_SIG_LH2,
            LhaEntry.METHOD_SIG_LH3,
            LhaEntry.METHOD_SIG_LH4,
            LhaEntry.METHOD_SIG_LH5,
            LhaEntry.METHOD_SIG_LH6,
            LhaEntry.METHOD_SIG_LH7,
            LhaEntry.METHOD_SIG_LZS,
            LhaEntry.METHOD_SIG_LZ4,
            LhaEntry.METHOD_SIG_LZ5
        ].indexOf(method) === -1)
            throw (new Error("Invalid lzh entry method " + method));
        this.method = method;
    };
    LhaEntry.prototype.getMethod = function () {
        return this.method;
    };
    LhaEntry.prototype.setCompressedSize = function (compressedSize) {
        if (compressedSize < 0 || compressedSize > 0xFFFFFFFF)
            throw (new Error("Invalid lzh entry compressed data size"));
        this.compressedSize = compressedSize;
    };
    LhaEntry.prototype.getCompressedSize = function () {
        return this.compressedSize;
    };
    LhaEntry.prototype.setOriginalSize = function (originalSize) {
        if (originalSize < 0 || originalSize > 0xFFFFFFFF)
            throw (new Error("Invalid lha entry original data size"));
        this.originalSize = originalSize;
    };
    LhaEntry.prototype.getOriginalSize = function () {
        return this.originalSize;
    };
    LhaEntry.prototype.setTimeStamp = function (timeStamp) {
        this.timeStamp = timeStamp;
    };
    LhaEntry.prototype.getTimeStamp = function () {
        return new Date(this.timeStamp.getTime());
    };
    LhaEntry.prototype.setDosTimeStamp = function (tstamp) {
        this.timeStamp = new Date(LhaEntry.dosToJavaTime(tstamp));
    };
    LhaEntry.prototype.getDosTimeStamp = function () {
        return (LhaEntry.javaToDosTime(this.timeStamp.getTime()));
    };
    LhaEntry.prototype.setHeaderTimeStamp = function (tstamp) {
        this.timeStamp = new Date(tstamp * 1000);
    };
    LhaEntry.prototype.getHeaderTimeStamp = function () {
        if (this.timeStamp === null)
            return -1;
        return (this.timeStamp.getTime());
    };
    LhaEntry.prototype.setFile = function (f) {
        this.file = f;
    };
    LhaEntry.prototype.getFile = function () {
        return this.file;
    };
    LhaEntry.prototype.setCRC = function (crc) {
        this.fcrc = true;
        this.crc = crc;
    };
    LhaEntry.prototype.getCRC = function () {
        return this.crc;
    };
    LhaEntry.prototype.hasCRC = function () {
        return this.fcrc;
    };
    LhaEntry.prototype.setOS = function (os) {
        this.os = os;
    };
    LhaEntry.prototype.getOS = function () {
        return this.os;
    };
    LhaEntry.prototype.setOffset = function (offset) {
        if (offset < 0 || offset > 0xFFFFFFFF)
            throw (new Error("Invalid lzh entry offset"));
        this.offset = offset;
    };
    LhaEntry.prototype.getOffset = function () {
        return this.offset;
    };
    LhaEntry.dosToJavaTime = function (dtime) {
        var d = new Date();
        d.setFullYear((((dtime >> 25) & 0x7f) + 1980));
        d.setMonth((((dtime >> 21) & 0x0f) - 1));
        d.setDate(((dtime >> 16) & 0x1f));
        d.setHours(((dtime >> 11) & 0x1f));
        d.setMinutes(((dtime >> 5) & 0x3f));
        d.setSeconds(((dtime << 1) & 0x3e));
        return d.getTime();
    };
    LhaEntry.javaToDosTime = function (time) {
        var c = new Date(time);
        var year = c.getFullYear() + 1900;
        if (year < 1980) {
            return (1 << 21) | (1 << 16);
        }
        return (((year - 1980) << 25) |
            ((c.getMonth() + 1) << 21) |
            (c.getDate() << 16) |
            (c.getHours() << 11) |
            ((c.getMinutes()) << 5) |
            (c.getSeconds() >> 1));
    };
    LhaEntry.HD_STR_ENCODING = "MS932";
    LhaEntry.METHOD_SIG_LHD = "-lhd-";
    LhaEntry.METHOD_SIG_LH0 = "-lh0-";
    LhaEntry.METHOD_SIG_LH1 = "-lh1-";
    LhaEntry.METHOD_SIG_LH2 = "-lh2-";
    LhaEntry.METHOD_SIG_LH3 = "-lh3-";
    LhaEntry.METHOD_SIG_LH4 = "-lh4-";
    LhaEntry.METHOD_SIG_LH5 = "-lh5-";
    LhaEntry.METHOD_SIG_LH6 = "-lh6-";
    LhaEntry.METHOD_SIG_LH7 = "-lh7-";
    LhaEntry.METHOD_SIG_LZS = "-lzs-";
    LhaEntry.METHOD_SIG_LZ4 = "-lz4-";
    LhaEntry.METHOD_SIG_LZ5 = "-lz5-";
    LhaEntry.OSID_SIG_GENERIC = 0x00;
    LhaEntry.OSID_SIG_MSDOS = 0x4D;
    LhaEntry.OSID_SIG_OS2 = 0x32;
    LhaEntry.OSID_SIG_OS9 = 0x39;
    LhaEntry.OSID_SIG_OS68K = 0x4B;
    LhaEntry.OSID_SIG_OS386 = 0x33;
    LhaEntry.OSID_SIG_HUMAN = 0x48;
    LhaEntry.OSID_SIG_UNIX = 0x55;
    LhaEntry.OSID_SIG_CPM = 0x43;
    LhaEntry.OSID_SIG_FLEX = 0x46;
    LhaEntry.OSID_SIG_MAC = 0x6D;
    LhaEntry.OSID_SIG_RUNSER = 0x52;
    LhaEntry.OSID_SIG_JAVA = 0x4A;
    LhaEntry.OSID_SIG_WIN32 = 0x77;
    LhaEntry.OSID_SIG_WINNT = 0x57;
    LhaEntry.EXHDR_SIG_COMMON = 0x00;
    LhaEntry.EXHDR_SIG_FILENAME = 0x01;
    LhaEntry.EXHDR_SIG_DIRNAME = 0x02;
    LhaEntry.EXHDR_SIG_COMMENT = 0x3f;
    LhaEntry.EXHDR_SIG_DOSATTR = 0x40;
    LhaEntry.EXHDR_SIG_DOSTIMES = 0x41;
    LhaEntry.EXHDR_SIG_UNIXPERM = 0x50;
    LhaEntry.EXHDR_SIG_UNIXID = 0x51;
    LhaEntry.EXHDR_SIG_UNIXGROUPNAME = 0x52;
    LhaEntry.EXHDR_SIG_UNIXUSERNAME = 0x53;
    LhaEntry.EXHDR_SIG_UNIXLMTIME = 0x54;
    return LhaEntry;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/utils.ts
var utils_arr = function (n) {
    var array = new Array(n);
    for (var i = 0; i < n; i++) {
        array[i] = 0;
    }
    return array;
};
var arraycopy = function (src, srcPos, dest, destPos, length) {
    for (var i = 0; i < length; i++) {
        dest[destPos + i] = src[srcPos + i];
    }
};

// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhaException.ts

var lhaException_LhaException = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(LhaException, _super);
    function LhaException(m) {
        return _super.call(this, m) || this;
    }
    return LhaException;
}(Error));


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/sum.ts
var Sum = (function () {
    function Sum() {
        this.sum = 0;
    }
    Sum.prototype.update = function (b) {
        this.sum += b;
    };
    Sum.prototype.update_2 = function (b, off, len) {
        while (len-- > 0) {
            this.sum += b[off++];
        }
    };
    Sum.prototype.getValue = function () {
        return this.sum & 0xFF;
    };
    Sum.prototype.reset = function () {
        this.sum = 0;
    };
    return Sum;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhaEntryReader.ts





var lhaEntryReader_LhaEntryReader = (function () {
    function LhaEntryReader(encoding) {
        this.fileName = "";
        this.dirName = "";
        this.encoding = encoding;
        this.calcSum = new Sum();
        this.calcCRC = new CRC16();
    }
    LhaEntryReader.prototype.readHeader = function () {
        var base = utils_arr(LhaEntryReader.HDRU_SIZE);
        this.calcSum.reset();
        this.calcCRC.reset();
        this.flagSum = false;
        this.flagCRC = false;
        this.fileName = "";
        this.dirName = "";
        var n = this._read(base);
        if ((n <= 0) || ((n === 1) && (base[LhaEntryReader.HDRU_OFF_HEADERSIZE] === 0))) {
            return null;
        }
        else if (n !== LhaEntryReader.HDRU_SIZE) {
            throw (new lhaException_LhaException("header is broken (header size does'nt match)"));
        }
        var e;
        switch (base[LhaEntryReader.HDRU_OFF_LVL]) {
            case LhaEntryReader.HDR_SIG_LVL0:
                e = this.readHeader_Lv0(base);
                break;
            case LhaEntryReader.HDR_SIG_LVL1:
                e = this.readHeader_Lv1(base);
                break;
            case LhaEntryReader.HDR_SIG_LVL2:
                e = this.readHeader_Lv2(base);
                break;
            default:
                throw (new lhaException_LhaException("Unsupported Lha header level: " + base[LhaEntryReader.HDRU_OFF_LVL]));
        }
        if (this.flagSum && (this.srcSum !== this.calcSum.getValue())) {
            throw (new lhaException_LhaException("Lha header is broken (header check sum doesn't match)"));
        }
        if (this.flagCRC && (this.srcCRC !== this.calcCRC.getValue())) {
            throw (new lhaException_LhaException("Lha header is broken (header crc doesn't match"));
        }
        return (e);
    };
    LhaEntryReader._strFromChars = function (array, from, length) {
        var res = '';
        for (var i = 0; i < length; i++) {
            var code = array[i + from];
            res += String.fromCharCode(code);
        }
        return res;
    };
    LhaEntryReader.prototype.readHeader_Lv0 = function (base) {
        var e = new LhaEntry();
        this.flagSum = true;
        var headerSize = base[LhaEntryReader.HDRU_OFF_HEADERSIZE];
        this.srcSum = base[LhaEntryReader.HDR0_OFF_SUM];
        if (this.srcSum < 0) {
            this.srcSum += 256;
        }
        e.setMethod(LhaEntryReader._strFromChars(base, LhaEntryReader.HDR0_OFF_METHOD, 5));
        e.setCompressedSize(LhaEntryReader.get32(base, LhaEntryReader.HDR0_OFF_COMPSIZE));
        e.setOriginalSize(LhaEntryReader.get32(base, LhaEntryReader.HDR0_OFF_ORIGSIZE));
        e.setDosTimeStamp(LhaEntryReader.get32(base, LhaEntryReader.HDR0_OFF_TIMESTAMP));
        this.calcSum.update_2(base, 2, base.length - 2);
        var buf = utils_arr(1);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (header size does'nt match)"));
        }
        var nameSize = buf[0];
        this.calcSum.update_2(buf, 0, buf.length);
        buf = utils_arr(nameSize);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read name)"));
        }
        var name = String.fromCharCode.apply(String, buf);
        this.calcSum.update_2(buf, 0, buf.length);
        var diff = headerSize - nameSize;
        if ((diff !== 20) && (diff !== 22) && (diff < 23)) {
            throw (new lhaException_LhaException("Lha header is broken (header size does'nt match)"));
        }
        e.setOS(LhaEntry.OSID_SIG_GENERIC);
        if (diff >= 22) {
            buf = utils_arr(2);
            if (this._read(buf) !== buf.length) {
                throw (new lhaException_LhaException("Lha header is broken (cannot read crc value)"));
            }
            e.setCRC(LhaEntryReader.get16(buf, 0));
            this.calcSum.update_2(buf, 0, buf.length);
        }
        if (diff >= 23) {
            buf = utils_arr(1);
            if (this._read(buf) !== buf.length) {
                throw (new lhaException_LhaException("Lha header is broken (cannot read os signature)"));
            }
            e.setOS(buf[0]);
            this.calcSum.update_2(buf, 0, buf.length);
        }
        if (diff > 23) {
            buf = utils_arr(diff - 24);
            if (this._read(buf) !== buf.length) {
                throw (new lhaException_LhaException("Lha header is broken (cannot read ext)"));
            }
            this.calcSum.update_2(buf, 0, buf.length);
        }
        e.setFile(this.convertFilePath(name, e.getOS()));
        return (e);
    };
    LhaEntryReader.prototype.readHeader_Lv1 = function (base) {
        var e = new LhaEntry();
        this.flagSum = true;
        this.srcSum = base[LhaEntryReader.HDR1_OFF_SUM];
        if (this.srcSum < 0) {
            this.srcSum += 256;
        }
        e.setMethod(LhaEntryReader._strFromChars(base, LhaEntryReader.HDR1_OFF_METHOD, 5));
        e.setOriginalSize(LhaEntryReader.get32(base, LhaEntryReader.HDR1_OFF_ORIGSIZE));
        e.setDosTimeStamp(LhaEntryReader.get32(base, LhaEntryReader.HDR1_OFF_TIMESTAMP));
        if (base[LhaEntryReader.HDR1_OFF_19] !== 0x20) {
            throw (new lhaException_LhaException("Lha header is broken (offset 19 is not 0x20)"));
        }
        this.calcSum.update_2(base, 2, base.length - 2);
        this.calcCRC.update_2(base, 0, base.length);
        var buf = utils_arr(1);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read name size)"));
        }
        var nameSize = buf[0];
        this.calcSum.update_2(buf, 0, buf.length);
        this.calcCRC.update_2(buf, 0, buf.length);
        var name = "";
        if (nameSize > 0) {
            buf = utils_arr(nameSize);
            if (this._read(buf) !== buf.length) {
                throw (new lhaException_LhaException("Lha header is broken (cannot read name)"));
            }
            name = String.fromCharCode.apply(String, buf);
            this.calcSum.update_2(buf, 0, buf.length);
            this.calcCRC.update_2(buf, 0, buf.length);
        }
        buf = utils_arr(2);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read crc value)"));
        }
        e.setCRC(LhaEntryReader.get16(buf, 0));
        this.calcSum.update_2(buf, 0, buf.length);
        this.calcCRC.update_2(buf, 0, buf.length);
        buf = utils_arr(1);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read os signature)"));
        }
        e.setOS(buf[0]);
        this.calcSum.update_2(buf, 0, buf.length);
        this.calcCRC.update_2(buf, 0, buf.length);
        var extSize = 0;
        buf = utils_arr(2);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read ext)"));
        }
        this.calcSum.update_2(buf, 0, buf.length);
        this.calcCRC.update_2(buf, 0, buf.length);
        for (var next = LhaEntryReader.get16(buf, 0); next > 0; next = this.readExHeader(e, next)) {
            extSize += next;
        }
        e.setCompressedSize(LhaEntryReader.get32(base, LhaEntryReader.HDR0_OFF_COMPSIZE) - extSize);
        if (this.fileName.length > 0) {
            name = this.dirName + this.fileName;
        }
        else {
            name = this.convertFilePath(name, e.getOS());
        }
        e.setFile(name);
        return (e);
    };
    LhaEntryReader.prototype.readHeader_Lv2 = function (base) {
        var e = new LhaEntry();
        e.setMethod(LhaEntryReader._strFromChars(base, LhaEntryReader.HDR2_OFF_METHOD, 5));
        e.setCompressedSize(LhaEntryReader.get32(base, LhaEntryReader.HDR2_OFF_COMPSIZE));
        e.setOriginalSize(LhaEntryReader.get32(base, LhaEntryReader.HDR2_OFF_ORIGSIZE));
        e.setHeaderTimeStamp(LhaEntryReader.get32(base, LhaEntryReader.HDR2_OFF_TIMESTAMP));
        this.calcCRC.update_2(base, 0, base.length);
        var buf = utils_arr(2);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read crc value)"));
        }
        e.setCRC(LhaEntryReader.get16(buf, 0));
        this.calcCRC.update_2(buf, 0, buf.length);
        buf = utils_arr(1);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read os signature)"));
        }
        e.setOS(buf[0]);
        this.calcCRC.update_2(buf, 0, buf.length);
        buf = utils_arr(2);
        if (this._read(buf) !== buf.length) {
            throw (new lhaException_LhaException("Lha header is broken (cannot read ext)"));
        }
        this.calcCRC.update_2(buf, 0, buf.length);
        for (var next = LhaEntryReader.get16(buf, 0); next > 0; next = this.readExHeader(e, next))
            ;
        e.setFile(this.dirName + this.fileName);
        return (e);
    };
    LhaEntryReader.prototype.readExHeader = function (e, size) {
        var buf = utils_arr(size);
        if (this._read(buf) !== buf.length)
            throw (new lhaException_LhaException("header is broken"));
        switch (buf[0]) {
            case LhaEntry.EXHDR_SIG_COMMON:
                this.flagCRC = true;
                this.srcCRC = LhaEntryReader.get16(buf, 1);
                buf[1] = 0x00;
                buf[2] = 0x00;
                break;
            case LhaEntry.EXHDR_SIG_FILENAME:
                this.fileName = LhaEntryReader._strFromChars(buf, 1, size - 3);
                break;
            case LhaEntry.EXHDR_SIG_DIRNAME:
                var dname = '';
                var pi = 0;
                for (var i = 1; i <= (size - 3); ++i) {
                    if (buf[i] === LhaEntryReader.HD_CHR_DELIM_EXTRA) {
                        dname += LhaEntryReader._strFromChars(buf, pi + 1, i - pi - 1);
                        dname += '/';
                        pi = i;
                    }
                }
                dname += LhaEntryReader._strFromChars(buf, pi + 1, size - 3 - pi);
                this.dirName = dname;
                break;
            case LhaEntry.EXHDR_SIG_COMMENT:
                break;
            case LhaEntry.EXHDR_SIG_DOSATTR:
                break;
            case LhaEntry.EXHDR_SIG_DOSTIMES:
                break;
            case LhaEntry.EXHDR_SIG_UNIXPERM:
                break;
            case LhaEntry.EXHDR_SIG_UNIXID:
                break;
            case LhaEntry.EXHDR_SIG_UNIXGROUPNAME:
                break;
            case LhaEntry.EXHDR_SIG_UNIXUSERNAME:
                break;
            case LhaEntry.EXHDR_SIG_UNIXLMTIME:
                break;
            default:
                break;
        }
        this.calcCRC.update_2(buf, 0, buf.length);
        return (LhaEntryReader.get16(buf, size - 2));
    };
    LhaEntryReader.prototype.convertFilePath = function (s, os) {
        var delim;
        switch (os) {
            case LhaEntry.OSID_SIG_GENERIC:
            case LhaEntry.OSID_SIG_MSDOS:
            case LhaEntry.OSID_SIG_WIN32:
            case LhaEntry.OSID_SIG_WINNT:
                delim = LhaEntryReader.HD_CHR_DELIM_MSDOS;
                break;
            case LhaEntry.OSID_SIG_MAC:
                delim = LhaEntryReader.HD_CHR_DELIM_MAC;
                break;
            default:
                delim = LhaEntryReader.HD_CHR_DELIM_UNIX;
                break;
        }
        var c = s.split('');
        for (var i = 0; i < c.length; ++i) {
            if (c[i] === delim)
                c[i] = '/';
            else if (c[i] === '/')
                c[i] = delim;
        }
        return c.join('');
    };
    LhaEntryReader.get16 = function (b, off) {
        return ((b[off] & 0xFF) | ((b[off + 1] & 0xFF) << 8));
    };
    LhaEntryReader.get32 = function (b, off) {
        return (LhaEntryReader.get16(b, off) | (LhaEntryReader.get16(b, off + 2) << 16));
    };
    LhaEntryReader.HD_CHR_DELIM_MSDOS = '\\';
    LhaEntryReader.HD_CHR_DELIM_UNIX = '/';
    LhaEntryReader.HD_CHR_DELIM_MAC = ':';
    LhaEntryReader.HD_CHR_DELIM_EXTRA = 0xFF;
    LhaEntryReader.HDRU_SIZE = 21;
    LhaEntryReader.HDRU_OFF_HEADERSIZE = 0;
    LhaEntryReader.HDRU_OFF_LVL = 20;
    LhaEntryReader.HDR0_OFF_SUM = 1;
    LhaEntryReader.HDR0_OFF_METHOD = 2;
    LhaEntryReader.HDR0_OFF_COMPSIZE = 7;
    LhaEntryReader.HDR0_OFF_ORIGSIZE = 11;
    LhaEntryReader.HDR0_OFF_TIMESTAMP = 15;
    LhaEntryReader.HDR0_OFF_FILEATTR = 19;
    LhaEntryReader.HDR1_OFF_SUM = 1;
    LhaEntryReader.HDR1_OFF_METHOD = 2;
    LhaEntryReader.HDR1_OFF_SKIPSIZE = 7;
    LhaEntryReader.HDR1_OFF_ORIGSIZE = 11;
    LhaEntryReader.HDR1_OFF_TIMESTAMP = 15;
    LhaEntryReader.HDR1_OFF_19 = 19;
    LhaEntryReader.HDR2_OFF_METHOD = 2;
    LhaEntryReader.HDR2_OFF_COMPSIZE = 7;
    LhaEntryReader.HDR2_OFF_ORIGSIZE = 11;
    LhaEntryReader.HDR2_OFF_TIMESTAMP = 15;
    LhaEntryReader.HDR2_OFF_RESERVED = 19;
    LhaEntryReader.HDR_SIG_LVL0 = 0x00;
    LhaEntryReader.HDR_SIG_LVL1 = 0x01;
    LhaEntryReader.HDR_SIG_LVL2 = 0x02;
    LhaEntryReader.HD_STR_METHOD_ENCODING = "US-ASCII";
    return LhaEntryReader;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/slidingDicDecoder.ts

var slidingDicDecoder_SlidingDicDecoder = (function () {
    function SlidingDicDecoder(_in, originalSize, dictionaryBit, positionAdjust) {
        this._in = _in;
        this.originalSize = originalSize;
        this.decodeCount = 0;
        this.positionAdjust = positionAdjust;
        this.dictionarySize = 1 << dictionaryBit;
        this.dictionaryMask = this.dictionarySize - 1;
        this.dictionaryBuffer = utils_arr(this.dictionarySize);
        this.bufferPointerBegin = 0;
        this.bufferPointerEnd = 0;
        this.bitBuffer = 0;
        this.subBitBuffer = 0;
        this.bitCount = 0;
        this.needInitialRead = true;
    }
    SlidingDicDecoder.prototype.close = function () {
    };
    SlidingDicDecoder.prototype.read = function (b, off, len) {
        if (this.needInitialRead) {
            this.initRead();
            this.needInitialRead = false;
        }
        var sl = len;
        var rs = this.bufferPointerEnd - this.bufferPointerBegin;
        if (rs < 0) {
            var bl = this.dictionarySize - this.bufferPointerBegin;
            if (bl >= len) {
                arraycopy(this.dictionaryBuffer, this.bufferPointerBegin, b, off, len);
                this.bufferPointerBegin += len;
                if (this.bufferPointerBegin === this.dictionarySize) {
                    this.bufferPointerBegin = 0;
                }
                return (sl);
            }
            else {
                arraycopy(this.dictionaryBuffer, this.bufferPointerBegin, b, off, bl);
                off += bl;
                len -= bl;
                this.bufferPointerBegin = 0;
                if (this.bufferPointerEnd >= len) {
                    arraycopy(this.dictionaryBuffer, 0, b, off, len);
                    this.bufferPointerBegin = len;
                    return (sl);
                }
                else if (this.bufferPointerEnd !== 0) {
                    arraycopy(this.dictionaryBuffer, 0, b, off, this.bufferPointerEnd);
                    off += this.bufferPointerEnd;
                    len -= this.bufferPointerEnd;
                    this.bufferPointerBegin = this.bufferPointerEnd;
                }
            }
        }
        else if (rs >= len) {
            arraycopy(this.dictionaryBuffer, this.bufferPointerBegin, b, off, len);
            this.bufferPointerBegin += len;
            return (sl);
        }
        else if (rs !== 0) {
            arraycopy(this.dictionaryBuffer, this.bufferPointerBegin, b, off, rs);
            off += rs;
            len -= rs;
            this.bufferPointerBegin = this.bufferPointerEnd;
        }
        if (this.originalSize <= this.decodeCount) {
            var l = sl - len;
            return l > 0 ? l : -1;
        }
        while ((this.decodeCount < this.originalSize) && (len > 0)) {
            var c = this.decodeCode();
            if (c <= SlidingDicDecoder.UNSINGED_CHAR_MAX) {
                ++this.decodeCount;
                --len;
                ++this.bufferPointerBegin;
                this.dictionaryBuffer[this.bufferPointerEnd++] = b[off++] = c;
                if (this.bufferPointerEnd === this.dictionarySize) {
                    this.bufferPointerBegin = this.bufferPointerEnd = 0;
                }
            }
            else {
                var matchLength = c - this.positionAdjust;
                var matchOffset = this.decodePosition();
                var matchPosition = (this.bufferPointerEnd - matchOffset - 1) & this.dictionaryMask;
                this.decodeCount += matchLength;
                for (var k = 0; k < matchLength; ++k) {
                    var t = this.dictionaryBuffer[(matchPosition + k) & this.dictionaryMask] & 0xFF;
                    this.dictionaryBuffer[this.bufferPointerEnd++] = t;
                    if (len > 0) {
                        --len;
                        ++this.bufferPointerBegin;
                        if (this.bufferPointerBegin === this.dictionarySize) {
                            this.bufferPointerBegin = 0;
                        }
                        b[off++] = t;
                    }
                    if (this.bufferPointerEnd === this.dictionarySize) {
                        this.bufferPointerEnd = 0;
                    }
                }
            }
        }
        return (sl - len);
    };
    SlidingDicDecoder.prototype.fillBitBuffer = function (n) {
        while (n > this.bitCount) {
            n -= this.bitCount;
            this.bitBuffer = (this.bitBuffer << this.bitCount)
                + (this.subBitBuffer >>> (SlidingDicDecoder.CHAR_BIT - this.bitCount));
            var c = this._in.read();
            this.subBitBuffer = (c > 0) ? c : 0;
            this.bitCount = SlidingDicDecoder.CHAR_BIT;
        }
        this.bitCount -= n;
        this.bitBuffer = ((this.bitBuffer << n) + (this.subBitBuffer >>> (SlidingDicDecoder.CHAR_BIT - n))) & 0xFFFF;
        this.subBitBuffer = (this.subBitBuffer << n) & 0x00FF;
    };
    SlidingDicDecoder.prototype.getBits = function (n) {
        var x = this.bitBuffer >>> (2 * SlidingDicDecoder.CHAR_BIT - n);
        this.fillBitBuffer(n);
        return (x);
    };
    SlidingDicDecoder.OFFSET = 0x100 - 3;
    SlidingDicDecoder.UNSINGED_CHAR_MAX = 255;
    SlidingDicDecoder.CHAR_BIT = 8;
    SlidingDicDecoder.THRESHOLD = 3;
    SlidingDicDecoder.MAX_MATCH = 256;
    return SlidingDicDecoder;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhDecoder.ts




var lhDecoder_LhDecoder = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(LhDecoder, _super);
    function LhDecoder(_in, originalSize, dictionaryBit, positionAdjust) {
        var _this = _super.call(this, _in, originalSize, dictionaryBit, positionAdjust) || this;
        _this.treeLeft = utils_arr(2 * LhDecoder.NC - 1);
        _this.treeRight = utils_arr(2 * LhDecoder.NC - 1);
        _this.positionTable = utils_arr(LhDecoder.POSITION_TABLE_SIZE);
        _this.positionLength = utils_arr(LhDecoder.NPT);
        return _this;
    }
    LhDecoder.prototype.makeTable = function (nchar, bitLength, tableBits, table) {
        var countTable = utils_arr(17);
        var weightTable = utils_arr(17);
        var startTable = utils_arr(17);
        var total;
        var j, k, m;
        for (var i = 1; i <= 16; ++i) {
            countTable[i] = 0;
            weightTable[i] = 1 << (16 - i);
        }
        for (var i = 0; i < nchar; ++i) {
            if (bitLength[i] > 16) {
                throw (new lhaException_LhaException("Bad table."));
            }
            ++countTable[bitLength[i]];
        }
        total = 0;
        for (var i = 1; i <= 16; ++i) {
            startTable[i] = total;
            total += weightTable[i] * countTable[i];
        }
        if (((total & 0xffff) !== 0) || (tableBits > 16)) {
            throw (new lhaException_LhaException("Bad table."));
        }
        m = 16 - tableBits;
        for (var i = 1; i <= tableBits; ++i) {
            startTable[i] >>>= m;
            weightTable[i] >>>= m;
        }
        j = startTable[tableBits + 1] >>> m;
        k = 1 << tableBits;
        if (k > 4096) {
            k = 4096;
        }
        if (j !== 0) {
            for (var i = j; i < k; ++i) {
                table[i] = 0;
            }
        }
        var avail = nchar;
        for (j = 0; j < nchar; ++j) {
            k = bitLength[j];
            if (k === 0) {
                continue;
            }
            var l = startTable[k] + weightTable[k];
            if (k <= tableBits) {
                if (l > 4096) {
                    l = 4096;
                }
                for (var i = startTable[k]; i < l; ++i) {
                    table[i] = j;
                }
            }
            else {
                var t = table;
                var start = startTable[k];
                var p = start >>> m;
                if (p > 4096) {
                    throw (new lhaException_LhaException("Bad table."));
                }
                start <<= tableBits;
                for (var n = k - tableBits; n > 0; --n) {
                    if (t[p] === 0) {
                        this.treeRight[avail] = this.treeLeft[avail] = 0;
                        t[p] = avail++;
                    }
                    p = t[p];
                    if ((start & 0x8000) !== 0) {
                        t = this.treeRight;
                    }
                    else {
                        t = this.treeLeft;
                    }
                    start <<= 1;
                }
                t[p] = j;
            }
            startTable[k] = l;
        }
    };
    LhDecoder.NPT = 0x80;
    LhDecoder.NC = slidingDicDecoder_SlidingDicDecoder.UNSINGED_CHAR_MAX + slidingDicDecoder_SlidingDicDecoder.MAX_MATCH + 2 - slidingDicDecoder_SlidingDicDecoder.THRESHOLD;
    LhDecoder.POSITION_TABLE_SIZE = 256;
    return LhDecoder;
}(slidingDicDecoder_SlidingDicDecoder));


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lh1Decoder.ts




var lh1Decoder_Lh1Decoder = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Lh1Decoder, _super);
    function Lh1Decoder(_in, originalSize) {
        return _super.call(this, _in, originalSize, 12, slidingDicDecoder_SlidingDicDecoder.OFFSET) || this;
    }
    Lh1Decoder.prototype.decodeCode = function () {
        throw new lhaException_LhaException("not realized yet");
    };
    Lh1Decoder.prototype.decodePosition = function () {
        throw new lhaException_LhaException("not realized yet");
    };
    Lh1Decoder.prototype.initRead = function () {
        throw new lhaException_LhaException("not realized yet");
    };
    return Lh1Decoder;
}(lhDecoder_LhDecoder));


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lh4Decoder.ts



var lh4Decoder_Lh4Decoder = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Lh4Decoder, _super);
    function Lh4Decoder(_in, originalSize, dictionaryBit, np, positionBit) {
        var _this = _super.call(this, _in, originalSize, dictionaryBit, Lh4Decoder.OFFSET) || this;
        _this.codeLength = utils_arr(Lh4Decoder.NC);
        _this.codeTable = utils_arr(Lh4Decoder.CODE_TABLE_SIZE);
        _this.np = np;
        _this.positionBit = positionBit;
        _this.blockSize = 0;
        return _this;
    }
    Lh4Decoder.prototype.initRead = function () {
        this.fillBitBuffer(2 * Lh4Decoder.CHAR_BIT);
    };
    Lh4Decoder.prototype.decodeCode = function () {
        if (this.blockSize === 0) {
            this.blockSize = this.getBits(16);
            this.readPositionLength(Lh4Decoder.NT, Lh4Decoder.TBIT, 3);
            this.readCodeLength();
            this.readPositionLength(this.np, this.positionBit, -1);
        }
        --this.blockSize;
        var j = this.codeTable[this.bitBuffer >>> (16 - 12)];
        if (j < Lh4Decoder.NC) {
            this.fillBitBuffer(this.codeLength[j]);
        }
        else {
            this.fillBitBuffer(12);
            var mask = 1 << (16 - 1);
            do {
                if ((this.bitBuffer & mask) !== 0) {
                    j = this.treeRight[j];
                }
                else {
                    j = this.treeLeft[j];
                }
                mask >>>= 1;
            } while ((j >= Lh4Decoder.NC) && ((mask !== 0) || (j !== this.treeLeft[j])));
            this.fillBitBuffer(this.codeLength[j] - 12);
        }
        return (j);
    };
    Lh4Decoder.prototype.decodePosition = function () {
        var j = this.positionTable[this.bitBuffer >>> (16 - 8)];
        if (j < this.np) {
            this.fillBitBuffer(this.positionLength[j]);
        }
        else {
            this.fillBitBuffer(8);
            var mask = 1 << (16 - 1);
            do {
                if ((this.bitBuffer & mask) !== 0) {
                    j = this.treeRight[j];
                }
                else {
                    j = this.treeLeft[j];
                }
                mask >>>= 1;
            } while ((j >= this.np) && ((mask !== 0) || (j !== this.treeLeft[j])));
            this.fillBitBuffer(this.positionLength[j] - 8);
        }
        if (j !== 0) {
            j = ((1 << (j - 1)) + this.getBits(j - 1));
        }
        return (j);
    };
    Lh4Decoder.prototype.readPositionLength = function (nn, nbit, i_special) {
        var n = this.getBits(nbit);
        if (n === 0) {
            var c = this.getBits(nbit);
            for (var i = 0; i < nn; ++i) {
                this.positionLength[i] = 0;
            }
            for (var i = 0; i < Lh4Decoder.POSITION_TABLE_SIZE; ++i) {
                this.positionTable[i] = c;
            }
        }
        else {
            var i = 0;
            var max = n < Lh4Decoder.NPT ? n : Lh4Decoder.NPT;
            while (i < max) {
                var c = this.bitBuffer >>> (16 - 3);
                if (c !== 7) {
                    this.fillBitBuffer(3);
                }
                else {
                    var mask = 1 << (16 - 4);
                    while ((mask & this.bitBuffer) !== 0) {
                        mask >>>= 1;
                        ++c;
                    }
                    this.fillBitBuffer(c - 3);
                }
                this.positionLength[i++] = c;
                if (i === i_special) {
                    c = this.getBits(2);
                    while ((--c >= 0) && (i < Lh4Decoder.NPT)) {
                        this.positionLength[i++] = 0;
                    }
                }
            }
            while (i < nn) {
                this.positionLength[i++] = 0;
            }
            this.makeTable(nn, this.positionLength, 8, this.positionTable);
        }
    };
    Lh4Decoder.prototype.readCodeLength = function () {
        var n = this.getBits(Lh4Decoder.CBIT);
        if (n === 0) {
            var c = this.getBits(Lh4Decoder.CBIT);
            for (var i = 0; i < Lh4Decoder.NC; ++i) {
                this.codeLength[i] = 0;
            }
            for (var i = 0; i < Lh4Decoder.CODE_TABLE_SIZE; ++i) {
                this.codeTable[i] = c;
            }
        }
        else {
            var i = 0;
            var max = n < Lh4Decoder.NC ? n : Lh4Decoder.NC;
            while (i < max) {
                var c = this.positionTable[this.bitBuffer >>> (16 - 8)];
                if (c >= Lh4Decoder.NT) {
                    var mask = 1 << (16 - 9);
                    do {
                        if ((this.bitBuffer & mask) !== 0) {
                            c = this.treeRight[c];
                        }
                        else {
                            c = this.treeLeft[c];
                        }
                        mask >>>= 1;
                    } while ((c >= Lh4Decoder.NT) && ((mask !== 0) || (c !== this.treeLeft[c])));
                }
                this.fillBitBuffer(this.positionLength[c]);
                if (c <= 2) {
                    if (c === 0) {
                        c = 1;
                    }
                    else if (c === 1) {
                        c = this.getBits(4) + 3;
                    }
                    else {
                        c = this.getBits(Lh4Decoder.CBIT) + 20;
                    }
                    while (--c >= 0) {
                        this.codeLength[i++] = 0;
                    }
                }
                else {
                    this.codeLength[i++] = c - 2;
                }
            }
            while (i < Lh4Decoder.NC) {
                this.codeLength[i++] = 0;
            }
            this.makeTable(Lh4Decoder.NC, this.codeLength, 12, this.codeTable);
        }
    };
    Lh4Decoder.UNSIGNED_SHORT_BIT = 16;
    Lh4Decoder.NT = Lh4Decoder.UNSIGNED_SHORT_BIT + 3;
    Lh4Decoder.TBIT = 5;
    Lh4Decoder.CBIT = 9;
    Lh4Decoder.CODE_TABLE_SIZE = 4096;
    return Lh4Decoder;
}(lhDecoder_LhDecoder));


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhdDecoder.ts
var LhdDecoder = (function () {
    function LhdDecoder() {
    }
    LhdDecoder.prototype.read = function (b, off, len) {
        return (-1);
    };
    LhdDecoder.prototype.close = function () {
    };
    return LhdDecoder;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/nocompressDecoder.ts
var NocompressDecoder = (function () {
    function NocompressDecoder(_in, originalSize) {
        this._in = _in;
        this.originalSize = originalSize;
    }
    NocompressDecoder.prototype.read = function (b, off, len) {
        if (len <= 0) {
            return (0);
        }
        if (this.originalSize <= 0) {
            return (-1);
        }
        var sl = len;
        while ((this.originalSize > 0) && (len > 0)) {
            b[off++] = this._in.read();
            --this.originalSize;
            --len;
        }
        return (sl - len);
    };
    NocompressDecoder.prototype.close = function () {
        this._in = null;
    };
    return NocompressDecoder;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lzsDecoder.ts


var lzsDecoder_LzsDecoder = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(LzsDecoder, _super);
    function LzsDecoder(_in, originalSize) {
        var _this = _super.call(this, _in, originalSize, 11, 256 - 2) || this;
        _this.matchPosition = 0;
        return _this;
    }
    LzsDecoder.prototype.decodeCode = function () {
        var b = this.getBits(1);
        if (b !== 0) {
            return (this.getBits(8));
        }
        else {
            this.matchPosition = this.getBits(11);
            return (this.getBits(4) + 0x100);
        }
    };
    LzsDecoder.prototype.decodePosition = function () {
        return ((this.bufferPointerEnd - this.matchPosition - LzsDecoder.MAGIC) & this.dictionaryMask);
    };
    LzsDecoder.prototype.initRead = function () {
        this.fillBitBuffer(2 * LzsDecoder.CHAR_BIT);
    };
    LzsDecoder.MAGIC = 18;
    return LzsDecoder;
}(slidingDicDecoder_SlidingDicDecoder));


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lz5Decoder.ts


var lz5Decoder_Lz5Decoder = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(Lz5Decoder, _super);
    function Lz5Decoder(_in, originalSize) {
        var _this = _super.call(this, _in, originalSize, 12, Lz5Decoder.OFFSET) || this;
        _this.MAGIC = 19;
        _this.flag = 0;
        _this.flagCount = 0;
        _this.matchPosition = 0;
        return _this;
    }
    Lz5Decoder.prototype.decodeCode = function () {
        if (this.flagCount === 0) {
            this.flagCount = 8;
            this.flag = this._in.read();
        }
        --this.flagCount;
        var c = this._in.read();
        if ((this.flag & 0x0001) === 0) {
            this.matchPosition = c;
            c = this._in.read();
            this.matchPosition += (c & 0x00F0) << 4;
            c &= 0x000F;
            c |= 0x0100;
        }
        this.flag >>>= 1;
        return (c);
    };
    Lz5Decoder.prototype.decodePosition = function () {
        return ((this.bufferPointerEnd - this.matchPosition - this.MAGIC) & this.dictionaryMask);
    };
    Lz5Decoder.prototype.initRead = function () {
        this.flagCount = 0;
        for (var i = 0; i < 256; ++i) {
            for (var j = 0; j < 13; ++j) {
                this.dictionaryBuffer[i * 13 + 18 + j] = i;
            }
            this.dictionaryBuffer[256 * 13 + 18 + i] = i;
            this.dictionaryBuffer[256 * 13 + 256 + 18 + i] = (255 - i);
        }
        for (var i = 0; i < 128; ++i) {
            this.dictionaryBuffer[256 * 13 + 512 + 18] = 0;
        }
        for (var i = 0; i < (128 - 18); ++i) {
            this.dictionaryBuffer[256 * 13 + 512 + 128 + 18] = 0x20;
        }
    };
    return Lz5Decoder;
}(slidingDicDecoder_SlidingDicDecoder));


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhaDecoderInputStream.ts










var lhaDecoderInputStream_LhaDecoderInputStream = (function () {
    function LhaDecoderInputStream(_in, entry) {
        this.entry = entry;
        this.crc = new CRC16();
        this.skipBuffer = utils_arr(LhaDecoderInputStream.SIZE_SKIP_BUFFER);
        this.entryCount = entry.getOriginalSize();
        this.decoder = LhaDecoderInputStream.createDecorder(_in, this.entryCount, entry.getMethod());
        this.crc.reset();
    }
    LhaDecoderInputStream.prototype.getChecksum = function () {
        return (this.crc);
    };
    LhaDecoderInputStream.prototype.available = function () {
        if (this.decoder === null) {
            return 0;
        }
        return (this.entryCount > 0 ? 1 : 0);
    };
    LhaDecoderInputStream.prototype.read = function () {
        if (this.decoder === null) {
            return -1;
        }
        var b = utils_arr(1);
        var n = this.decoder.read(b, 0, 1);
        if (n > 0) {
            this.crc.update(b[0]);
            --this.entryCount;
        }
        return (b[0]);
    };
    LhaDecoderInputStream.prototype.toArray = function () {
        var res = [];
        while (this.available())
            res.push(this.read());
        return res;
    };
    LhaDecoderInputStream.prototype.read_2 = function (b, off, len) {
        if (this.decoder === null) {
            return (-1);
        }
        var n = this.decoder.read(b, off, len);
        if (n > 0) {
            this.crc.update_2(b, off, n);
            this.entryCount -= n;
        }
        return (n);
    };
    LhaDecoderInputStream.prototype.skip = function (n) {
        if (n <= 0) {
            return (0);
        }
        if (n > Number.MAX_VALUE) {
            n = Number.MAX_VALUE;
        }
        var total = 0;
        while (total < n) {
            var len = n - total;
            if (len > this.skipBuffer.length) {
                len = this.skipBuffer.length;
            }
            len = this.read_2(this.skipBuffer, 0, len);
            if (len === -1) {
                break;
            }
            else {
                this.crc.update_2(this.skipBuffer, 0, len);
            }
            total += len;
        }
        this.entryCount -= total;
        return (total);
    };
    LhaDecoderInputStream.prototype.close = function () {
        if (this.decoder !== null) {
            this.decoder.close();
            this.decoder = null;
            this.entry = null;
            this.crc = null;
        }
    };
    LhaDecoderInputStream.prototype.closeEntry = function () {
        var skipCount = this.skip(this.entryCount);
        if (this.entryCount !== skipCount) {
            throw new lhaException_LhaException("Data length not matched");
        }
        if ((this.entry.hasCRC()) && (this.entry.getCRC() !== this.crc.getValue())) {
            throw new lhaException_LhaException("Data crc is not matched");
        }
        this.close();
    };
    LhaDecoderInputStream.createDecorder = function (_in, originalSize, method) {
        if (method === (LhaEntry.METHOD_SIG_LHD)) {
            return (new LhdDecoder());
        }
        else if (method === LhaEntry.METHOD_SIG_LH0) {
            return (new NocompressDecoder(_in, originalSize));
        }
        else if (method === LhaEntry.METHOD_SIG_LH1) {
            return (new lh1Decoder_Lh1Decoder(_in, originalSize));
        }
        else if (method === LhaEntry.METHOD_SIG_LH2) {
            throw (new lhaException_LhaException("Unsupported method: " + method));
        }
        else if (method === LhaEntry.METHOD_SIG_LH3) {
            throw (new lhaException_LhaException("Unsupported method: " + method));
        }
        else if (method === LhaEntry.METHOD_SIG_LH4) {
            return (new lh4Decoder_Lh4Decoder(_in, originalSize, 12, 14, 4));
        }
        else if (method === LhaEntry.METHOD_SIG_LH5) {
            return (new lh4Decoder_Lh4Decoder(_in, originalSize, 13, 14, 4));
        }
        else if (method === LhaEntry.METHOD_SIG_LH6) {
            return (new lh4Decoder_Lh4Decoder(_in, originalSize, 15, 16, 5));
        }
        else if (method === LhaEntry.METHOD_SIG_LH7) {
            return (new lh4Decoder_Lh4Decoder(_in, originalSize, 16, 17, 5));
        }
        else if (method === LhaEntry.METHOD_SIG_LZS) {
            return (new lzsDecoder_LzsDecoder(_in, originalSize));
        }
        else if (method === LhaEntry.METHOD_SIG_LZ4) {
            return (new NocompressDecoder(_in, originalSize));
        }
        else if (method === LhaEntry.METHOD_SIG_LZ5) {
            return (new lz5Decoder_Lz5Decoder(_in, originalSize));
        }
        throw (new lhaException_LhaException("Unknown method: " + method));
    };
    LhaDecoderInputStream.SIZE_SKIP_BUFFER = 512;
    return LhaDecoderInputStream;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/lha/lhaFile.ts




var lhaFile_LhaFile = (function () {
    function LhaFile(_in) {
        this.entryList = [];
        this.entryMap = {};
        this.raf = _in;
        this.name = name;
        this.entryList = [];
        this.entryMap = {};
        this.makeEntryMap();
    }
    LhaFile.prototype.getEntryByName = function (name) {
        return this.entryMap[name];
    };
    LhaFile.prototype.getEntryByIndex = function (index) {
        return this.entryList[index];
    };
    LhaFile.prototype.getInputStream = function (entry) {
        return (new lhaDecoderInputStream_LhaDecoderInputStream(new lhaFile_LhaFileInputStream(this, entry), entry));
    };
    LhaFile.prototype.getInputStreamByIndex = function (index) {
        return this.getInputStream(this.getEntryByIndex(index));
    };
    LhaFile.prototype.getName = function () {
        return name;
    };
    LhaFile.prototype.read = function (pos, b, off, len) {
        if (pos !== this.pos)
            this.raf.setPointer(pos);
        var n = this.raf.readBytesToArray(b, off, len);
        if (n > 0)
            this.pos = pos + n;
        return (n);
    };
    LhaFile.prototype.read_2 = function (pos) {
        if (pos !== this.pos)
            this.raf.setPointer(pos);
        var n = this.raf.readByte();
        if (n > 0)
            this.pos = pos + 1;
        return (n);
    };
    LhaFile.prototype.getSize = function () {
        return this.size;
    };
    LhaFile.prototype.close = function () {
    };
    LhaFile.prototype.makeEntryMap = function () {
        var raf = this.raf;
        var hr = new (function (_super) {
            Object(tslib_es6["c" /* __extends */])(class_1, _super);
            function class_1() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            class_1.prototype._read = function (b) {
                return (raf.readBytesToArray_2(b));
            };
            return class_1;
        }(lhaEntryReader_LhaEntryReader))(this.encoding);
        this.size = 0;
        while (true) {
            var e = hr.readHeader();
            if (e === null)
                break;
            e.setOffset(raf.getPointer());
            this.entryList.push(e);
            this.entryMap[e.getFile()] = e;
            ++this.size;
            var skipSize = e.getCompressedSize();
            if (raf.skip(skipSize) !== skipSize)
                throw (new lhaException_LhaException("Lha header is broken"));
        }
    };
    return LhaFile;
}());

var lhaFile_LhaFileInputStream = (function () {
    function LhaFileInputStream(file, entry) {
        if ((file === null) || (entry === null))
            throw (new Error('NullPointerException'));
        this.file = file;
        this.pos = entry.getOffset();
        this.count = entry.getCompressedSize();
    }
    LhaFileInputStream.prototype.read_2 = function (b, off, len) {
        if (this.count === 0)
            return (-1);
        if (len > this.count) {
            if (Number.MAX_VALUE < this.count) {
                len = Number.MAX_VALUE;
            }
            else {
                len = this.count;
            }
        }
        len = this.file.read(this.pos, b, off, len);
        if (len === -1)
            throw (new lhaException_LhaException("premature EOF"));
        this.pos += len;
        this.count -= len;
        return (len);
    };
    LhaFileInputStream.prototype.read = function () {
        if (this.count === 0)
            return (-1);
        var n = this.file.read_2(this.pos);
        if (n === -1)
            throw (new lhaException_LhaException("premature EOF"));
        ++this.pos;
        --this.count;
        return (n);
    };
    return LhaFileInputStream;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/internal/wav.ts

var wav_Wave = (function () {
    function Wave() {
    }
    Wave.encodeWAV = function (samples, sampleRate) {
        var binBuffer = new binBuffer_BinBuffer(44 + samples.length * 2);
        binBuffer.writeString('RIFF');
        binBuffer.writeUInt32(32 + samples.length * 2, true);
        binBuffer.writeString('WAVE');
        binBuffer.writeString('fmt ');
        binBuffer.writeUInt32(16, true);
        binBuffer.writeUInt16(1, true);
        binBuffer.writeUInt16(2, true);
        binBuffer.writeUInt32(sampleRate, true);
        binBuffer.writeUInt32(sampleRate * 4, true);
        binBuffer.writeUInt16(4, true);
        binBuffer.writeUInt16(16, true);
        binBuffer.writeString('data');
        binBuffer.writeUInt32(samples.length * 2, true);
        for (var i = 0; i < samples.length; i++) {
            var s = samples[i];
            binBuffer.writeUInt16(s, true);
        }
        return new Blob([binBuffer.getView()], { type: 'audio/wav' });
    };
    return Wave;
}());


// CONCATENATED MODULE: ./demo/pix32/ym-player/ym.ts



var LEONARD = '!LeOnArD!';
var END = 'End!';
var ym_Ym = (function () {
    function Ym(arr) {
        this.frames = [];
        this.currentFrameNumber = 0;
        this.periodA = 0;
        this.periodB = 0;
        this.periodC = 0;
        this.periodNoise = 0;
        this.volumeA = 0;
        this.envA = false;
        this.volumeB = 0;
        this.envB = false;
        this.volumeC = 0;
        this.envC = false;
        this.periodEnv = 0;
        this.attack = 0;
        this.hold = 0;
        this.alternate = 0;
        this.envStep = 0;
        this.countEnv = 0;
        this.holding = 0;
        this.volumeEnv = 0;
        this.divide = 15;
        this.countA = 0;
        this.outputA = 0;
        this.countB = 0;
        this.outputB = 0;
        this.countC = 0;
        this.outputC = 0;
        this.countNoise = 0;
        this.random = 1;
        this.outputNoise = 1;
        this.cA = 0;
        this.cB = 0;
        this.cC = 0;
        this.outA = 0;
        this.outB = 0;
        this.outC = 0;
        this.amplitudes = [0, 1, 2, 3, 4, 5, 6, 8, 10, 16, 22, 28, 36, 45, 53, 63];
        this.sampleRate = 44100;
        var bb = new binBuffer_BinBuffer(arr);
        if (bb.readString(2) === 'YM') {
            this.read(bb.getArray());
        }
        else {
            bb.resetPointer();
            var lhaFile = new lhaFile_LhaFile(bb);
            var body = lhaFile.getInputStreamByIndex(0).toArray();
            this.read(body);
        }
        this.readFrames();
    }
    Ym.prototype.read = function (arr) {
        this.buffer = new binBuffer_BinBuffer(arr);
        var format = this.buffer.readString(3);
        if (['YM6', 'YM5'].indexOf(format) === -1)
            throw new Error("unsupported format:" + format);
        if (this.buffer.readString(LEONARD.length) !== LEONARD)
            throw new Error("bad header: expected \"" + LEONARD + "\" magic string");
        this.numOfFrames = this.buffer.readUInt32();
        var attrs = this.buffer.readUInt32();
        this.interleavedOrder = binBuffer_BinBuffer.isBitSet(0, attrs);
        var numOfDigiDrums = this.buffer.readUInt16();
        this.masterClock = this.buffer.readUInt32();
        if (this.masterClock < 100000 || this.masterClock > 100000000)
            throw new Error("wrong master clock frequency (" + this.masterClock + ")");
        this.frameFreq = this.buffer.readUInt16();
        this.buffer.skip(4);
        this.buffer.readUInt16();
        for (var i = 0; i < numOfDigiDrums; i++) {
            var sampleSize = this.buffer.readUInt32();
            this.buffer.skip(sampleSize);
        }
        this.songName = this.buffer.readNTString();
        this.authorName = this.buffer.readNTString();
        this.songComment = this.buffer.readNTString();
        this.rawFrames = this.buffer.readBytes(this.numOfFrames * 16);
        var terminator = this.buffer.readString(4);
        if (terminator !== END)
            throw new Error("unexpected file terminator: " + terminator);
    };
    Ym.prototype.readFrames = function () {
        if (!this.interleavedOrder)
            throw new Error("non interleaved frames are not supported");
        for (var i = 0; i < this.numOfFrames; i++) {
            this.frames[i] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        }
        var cnt = 0;
        for (var r = 0; r < 16; r++) {
            for (var i = 0; i < this.numOfFrames; i++) {
                this.frames[i][r] = this.rawFrames[cnt++];
            }
        }
        if (cnt !== this.rawFrames.length)
            throw new Error("frame reading error,expected to read " + this.rawFrames.length + ", but " + cnt + " is read");
    };
    Ym.prototype.setCurrentFrame = function (frameNumber) {
        var oldCurrentFrameNumber = this.currentFrameNumber;
        this.currentFrameNumber = frameNumber;
        var frame = this.frames[frameNumber];
        this.periodA = (frame[1] & 0xF) << 8 | frame[0];
        this.periodB = (frame[3] & 0xF) << 8 | frame[2];
        this.periodC = (frame[5] & 0xF) << 8 | frame[4];
        this.periodNoise = (frame[6] & 0x1F) * 2;
        this.volumeA = frame[8] & 0xF;
        this.envA = ((frame[8] & 0x10) !== 0);
        this.volumeB = frame[9] & 0xF;
        this.envB = ((frame[9] & 0x10) !== 0);
        this.volumeC = frame[10] & 0xF;
        this.envC = ((frame[10] & 0x10) !== 0);
        this.periodEnv = (frame[12] << 8 | frame[11]) << 1;
        this.attack = ((frame[13] & 0x4) === 0) ? 0 : 15;
        if ((frame[13] & 0x8) === 0) {
            this.hold = 1;
            this.alternate = this.attack;
        }
        else {
            this.hold = frame[13] & 0x1;
            this.alternate = frame[13] & 0x2;
        }
        this.volumeEnv = this.attack ^ 0xF;
    };
    Ym.prototype.cycle = function () {
        var frame = this.frames[this.currentFrameNumber];
        if (this.divide === 0) {
            this.divide = 7;
            if (++this.countA >= this.periodA) {
                this.countA = 0;
                this.outputA ^= 0x1;
            }
            if (++this.countB >= this.periodB) {
                this.countB = 0;
                this.outputB ^= 0x1;
            }
            if (++this.countC >= this.periodC) {
                this.countC = 0;
                this.outputC ^= 0x1;
            }
            if (++this.countNoise >= this.periodNoise) {
                this.countNoise = 0;
                if ((this.random + 1 & 0x2) !== 0)
                    this.outputNoise ^= 0x1;
                if ((this.random & 0x1) !== 0)
                    this.random ^= 0x24000;
                this.random >>= 1;
            }
            var enable = frame[7];
            var enableA = (this.outputA | enable & 0x1) & (this.outputNoise | enable >> 3 & 0x1);
            var enableB = (this.outputB | enable >> 1 & 0x1) & (this.outputNoise | enable >> 4 & 0x1);
            var enableC = (this.outputC | enable >> 2 & 0x1) & (this.outputNoise | enable >> 5 & 0x1);
            if (this.holding === 0 && ++this.countEnv >= this.periodEnv) {
                this.countEnv = 0;
                if (this.envStep === 0) {
                    if (this.hold !== 0) {
                        if (this.alternate !== 0)
                            this.attack ^= 0xF;
                        this.holding = 1;
                    }
                    else {
                        if (this.alternate !== 0)
                            this.attack ^= 0xF;
                        this.envStep = 15;
                    }
                }
                else {
                    this.envStep--;
                }
            }
            this.volumeEnv = this.envStep ^ this.attack;
            this.cA = enableA * (this.envA ? this.volumeEnv : this.volumeA);
            this.cB = enableB * (this.envB ? this.volumeEnv : this.volumeB);
            this.cC = enableC * (this.envC ? this.volumeEnv : this.volumeC);
            this.outA = this.amplitudes[this.cA];
            this.outB = this.amplitudes[this.cB];
            this.outC = this.amplitudes[this.cC];
            this.outB = ~~(this.outB * 0.75);
        }
        else {
            this.divide--;
        }
    };
    Ym.prototype.getFrameSnapshotByTimeSec = function (timeSec) {
        var timeForOneFrame = 1000 / this.frameFreq;
        var index = (~~(timeSec * 1000 / timeForOneFrame)) % this.frames.length;
        if (this.frames[index])
            return this.frames[index];
        else
            return undefined;
    };
    Ym.prototype.renderToBlob = function () {
        var pcmSamples = [];
        var samplesInFrame = this.sampleRate / this.frameFreq;
        var cyclesForOneSample = this.masterClock / this.sampleRate;
        for (var i = 0; i < this.frames.length; i++) {
            this.setCurrentFrame(i);
            for (var j = 0; j < samplesInFrame; j++) {
                for (var k = 0; k < cyclesForOneSample; k++)
                    this.cycle();
                pcmSamples.push(~~((this.outA + this.outB) * 128 - 8192));
                pcmSamples.push((~~(this.outB + this.outC) * 128 - 8192));
            }
        }
        return wav_Wave.encodeWAV(pcmSamples, this.sampleRate);
    };
    Ym.prototype.renderToArrayBuffer = function () {
        var blob = this.renderToBlob();
        if (blob.arrayBuffer !== undefined)
            return blob.arrayBuffer();
        else
            return new Promise(function (resolve) {
                var fr = new FileReader();
                fr.onload = function () {
                    resolve(fr.result);
                };
                fr.readAsArrayBuffer(blob);
            });
    };
    return Ym;
}());


// CONCATENATED MODULE: ./engine/media/sound.ts

var sound_Sound = (function () {
    function Sound(game) {
        this.game = game;
        this.type = 'Sound';
        this.feedbackDelay = {
            delayTime: 0,
            gain: 0.8
        };
        this._loop = false;
        this._gain = 1;
        this._velocity = 1;
        this._stereoPan = 0.5;
    }
    Object.defineProperty(Sound.prototype, "loop", {
        get: function () {
            return this._loop;
        },
        set: function (value) {
            this._loop = value;
            this.game.getAudioPlayer().loop(this);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sound.prototype, "gain", {
        get: function () {
            return this._gain;
        },
        set: function (value) {
            this._gain = value;
            this.game.getAudioPlayer().setGain(this);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sound.prototype, "velocity", {
        get: function () {
            return this._velocity;
        },
        set: function (value) {
            this._velocity = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sound.prototype, "stereoPan", {
        get: function () {
            return this._stereoPan;
        },
        set: function (value) {
            this._stereoPan = value;
        },
        enumerable: false,
        configurable: true
    });
    Sound.prototype.getCurrentTimeSec = function () {
        var node = this.game.getAudioPlayer().getNodeBySound(this);
        if (node === undefined)
            return -1;
        return node.getCurrentTimeSec();
    };
    Sound.prototype.revalidate = function () {
        if (!this.getResourceLink())
            throw new debugError_DebugError("can not play sound: resource link is not set");
    };
    Sound.prototype.play = function () {
        this.game.getAudioPlayer().play(this);
    };
    Sound.prototype.stop = function () {
        this.game.getAudioPlayer().stop(this);
    };
    Sound.prototype.pause = function () {
        throw new debugError_DebugError('not implemented');
    };
    Sound.prototype.setResourceLink = function (link) {
        this._resourceLink = link;
    };
    Sound.prototype.getResourceLink = function () {
        return this._resourceLink;
    };
    return Sound;
}());


// CONCATENATED MODULE: ./demo/pix32/scenes/gameOverScene.ts






var gameOverScene_GameOverScene = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(GameOverScene, _super);
    function GameOverScene() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.score = 23440;
        return _this;
    }
    GameOverScene.prototype.onPreloading = function () {
        var _this = this;
        _super.prototype.onPreloading.call(this);
        var binLink = this.resourceLoader.loadBinary('pix32/resources/music/intro.ym');
        this.resourceLoader.addNextTask((function () {
            var ym = new ym_Ym(binLink.getTarget());
            _this.themeAudioLink = loadSound(_this.game, ym);
            _this.ym = ym;
        }));
    };
    GameOverScene.prototype.onReady = function () {
        var _this = this;
        _super.prototype.onReady.call(this);
        var sound = new sound_Sound(this.game);
        sound.setResourceLink(this.themeAudioLink);
        sound.loop = true;
        sound.play();
        this.oscilloscope.listen(sound, this.ym);
        (function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.print("!Game Over! Your score: " + this.score, 12000, true)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        }); })();
        this.on(KEYBOARD_EVENTS.keyPressed, function (_) {
            sound.stop();
            _this.game.runScene(new getReadyScene_GetReadyScene(_this.game));
        });
    };
    return GameOverScene;
}(basePix32Scene_BasePix32Scene));


// CONCATENATED MODULE: ./demo/pix32/scenes/gameScene.ts













var XOR = function (a, b) {
    return (a || b) && !(a && b);
};
var gameScene_r1 = new rect_Rect();
var gameScene_r2 = new rect_Rect();
var Car = (function () {
    function Car() {
        this.CAR_VELOCITY_INITIAL = 0.05;
        this.carVelocity = this.CAR_VELOCITY_INITIAL;
        this.CAR_VELOCITY_MAX = 1.0;
        this.carCollideRect = {
            x: 0, y: 3, width: 10, height: 3
        };
        this.minCarY = 5;
        this.maxCarY = 18;
        this.isBlinking = false;
        this.health = 32;
    }
    Car.prototype.blink = function () {
        var _this = this;
        var cnt = 0;
        if (this.isBlinking)
            return;
        this.isBlinking = true;
        var timer = this.carModel.setInterval(function () {
            cnt++;
            _this.carModel.visible = !_this.carModel.visible;
            if (cnt === 10) {
                timer.kill();
                _this.isBlinking = false;
                _this.carModel.visible = true;
            }
        }, 200);
    };
    return Car;
}());
var gameScene_GameScene = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(GameScene, _super);
    function GameScene() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.moveableObjects = [];
        _this.opponents = [];
        _this.step = 0;
        _this.lap = 1;
        _this.car = new Car();
        return _this;
    }
    GameScene.prototype.onPreloading = function () {
        var _this = this;
        _super.prototype.onPreloading.call(this);
        var binLink = this.resourceLoader.loadBinary('pix32/resources/music/Androids.ym');
        this.resourceLoader.addNextTask((function () {
            var ym = new ym_Ym(binLink.getTarget());
            _this.themeAudioLink = loadSound(_this.game, ym);
            _this.ym = ym;
        }));
        this.resourceLoader.addNextTask(function () {
            _this.carLink = _this.resourceLoader.loadTexture("./pix32/resources/images/car.png");
        });
        this.resourceLoader.addNextTask(function () {
            _this.hillLink = _this.resourceLoader.loadTexture("./pix32/resources/images/hill.png");
        });
        this.resourceLoader.addNextTask(function () {
            _this.lifeLink = _this.resourceLoader.loadTexture("./pix32/resources/images/life.png");
        });
        this.resourceLoader.addNextTask(function () {
            _this.stopSignLink = _this.resourceLoader.loadTexture("./pix32/resources/images/stopSign.png");
        });
    };
    GameScene.prototype.onReady = function () {
        var _this = this;
        _super.prototype.onReady.call(this);
        (function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            var sound;
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.print("get ready", 3000)];
                    case 1:
                        _a.sent();
                        sound = new sound_Sound(this.game);
                        sound.setResourceLink(this.themeAudioLink);
                        sound.loop = true;
                        sound.play();
                        this.sound = sound;
                        this.oscilloscope.listen(sound, this.ym);
                        this.createHills();
                        this.createRoadParticles();
                        this.createLives();
                        this.createCar();
                        this.listenKeyboard();
                        this.createOpponents();
                        this.createStopSigns();
                        this.createHealthBar();
                        return [4, waitFor(this.game, 1000)];
                    case 2:
                        _a.sent();
                        this.addTween(new tween_Tween({
                            target: this.car.carModel.pos,
                            time: 300,
                            to: { x: -7 }
                        }));
                        return [2];
                }
            });
        }); })();
    };
    GameScene.prototype.onUpdate = function () {
        this.moveObjects();
    };
    GameScene.prototype.createCar = function () {
        var car = new image_Image(this.game);
        car.setResourceLink(this.carLink);
        car.pos.setXY(4, 5);
        this.screen.appendChild(car);
        this.car.carModel = car;
    };
    GameScene.prototype.createOpponents = function () {
        var _this = this;
        for (var i = 0; i < 6; i++) {
            (function () {
                var img = new image_Image(_this.game);
                img.setResourceLink(_this.carLink);
                img.pos.setXY(mathEx_MathEx.random(100, 1000), mathEx_MathEx.random(10, 18));
                _this.screen.appendChild(img);
                var isOvertakenPrev = false;
                var isOvertaken = false;
                _this.moveableObjects.push({
                    model: img,
                    velocity: 0.1,
                    onDisappear: function (_) {
                    },
                    onMove: function (_) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
                        return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    isOvertakenPrev = isOvertaken;
                                    isOvertaken = img.pos.x < this.car.carModel.pos.x;
                                    if (!XOR(isOvertakenPrev, isOvertaken)) return [3, 2];
                                    return [4, this.print(this.calcMyPosition().toString(), 5000)];
                                case 1:
                                    _a.sent();
                                    _a.label = 2;
                                case 2: return [2];
                            }
                        });
                    }); },
                    collisionRect: {
                        x: 0, y: 3, width: 10, height: 3
                    },
                    onCollided: function (_) {
                        if (!_this.car.isBlinking) {
                            _this.car.carVelocity = _this.car.CAR_VELOCITY_INITIAL;
                            _this.car.blink();
                            _this.updateHealthBar(-3);
                        }
                    }
                });
                _this.opponents.push(img);
            })();
        }
    };
    GameScene.prototype.createRoadParticles = function () {
        for (var i = 0; i < 12; i++) {
            var p = new rectangle_Rectangle(this.game);
            p.size.setWH(1);
            p.lineWidth = 0;
            p.fillColor = color_Color.fromCssLiteral("#acabab");
            p.pos.setXY(mathEx_MathEx.random(0, 32), mathEx_MathEx.random(0, 32));
            this.screen.appendChild(p);
            this.moveableObjects.push({ model: p, velocity: 0, onDisappear: GameScene.onDisappearCommon });
        }
    };
    GameScene.prototype.createLives = function () {
        var _this = this;
        var _loop_1 = function (i) {
            var img = new image_Image(this_1.game);
            img.setResourceLink(this_1.lifeLink);
            var disappear = function () {
                img.pos.setXY(mathEx_MathEx.random(100, 1000), mathEx_MathEx.random(15, 22));
            };
            disappear();
            this_1.screen.appendChild(img);
            this_1.moveableObjects.push({
                model: img,
                velocity: 0,
                onDisappear: function (_) {
                    disappear();
                },
                onCollided: function (_) {
                    disappear();
                    _this.updateHealthBar(1);
                }
            });
        };
        var this_1 = this;
        for (var i = 0; i < 2; i++) {
            _loop_1(i);
        }
    };
    GameScene.prototype.createStopSigns = function () {
        var _this = this;
        var _loop_2 = function (i) {
            var img = new image_Image(this_2.game);
            img.setResourceLink(this_2.stopSignLink);
            img.pos.setXY(mathEx_MathEx.random(100, 1000), mathEx_MathEx.random(8, 24));
            this_2.screen.appendChild(img);
            this_2.moveableObjects.push({
                model: img,
                velocity: 0,
                onCollided: function (_) {
                    if (!_this.car.isBlinking) {
                        _this.car.carVelocity = _this.car.CAR_VELOCITY_INITIAL;
                        _this.car.blink();
                        _this.updateHealthBar(-5);
                    }
                },
                onDisappear: function (_) {
                    img.pos.setXY(mathEx_MathEx.random(100, 1000), mathEx_MathEx.random(8, 24));
                }
            });
        };
        var this_2 = this;
        for (var i = 0; i < 5; i++) {
            _loop_2(i);
        }
    };
    GameScene.prototype.createHealthBar = function () {
        var rect = new rectangle_Rectangle(this.game);
        rect.lineWidth = 0;
        rect.size.setWH(32, 1);
        rect.pos.setXY(0, 0);
        this.screen.appendChild(rect);
        this.healthRect = rect;
    };
    GameScene.prototype.updateHealthBar = function (val) {
        var _this = this;
        this.car.health += val;
        if (this.car.health < 0) {
            this.healthRect.visible = false;
            var scene_1 = new gameOverScene_GameOverScene(this.game);
            scene_1.score = this.step;
            this.sound.stop();
            this.setTimeout(function () { return _this.game.runScene(scene_1); }, 1000);
        }
        else {
            this.healthRect.size.width = this.car.health;
        }
    };
    GameScene.prototype.createHills = function () {
        for (var i = 0; i < 10; i++) {
            var img = new image_Image(this.game);
            img.setResourceLink(this.hillLink);
            img.pos.setXY(mathEx_MathEx.random(0, 32), mathEx_MathEx.random(0, 5));
            this.screen.appendChild(img);
            this.moveableObjects.push({ model: img, velocity: 0, onDisappear: GameScene.onDisappearCommon });
        }
        for (var i = 0; i < 10; i++) {
            var img = new image_Image(this.game);
            img.setResourceLink(this.hillLink);
            img.pos.setXY(mathEx_MathEx.random(0, 32), mathEx_MathEx.random(25, 30));
            this.screen.appendChild(img);
            this.moveableObjects.push({ model: img, velocity: 0, onDisappear: GameScene.onDisappearCommon });
        }
    };
    GameScene.prototype.moveObjects = function () {
        var _this = this;
        if ((this.step++ % 5000) === 0)
            this.print("Lap " + (this.lap++), 3000);
        this.car.carVelocity += 0.001;
        if (this.car.carVelocity > this.car.CAR_VELOCITY_MAX)
            this.car.carVelocity = this.car.CAR_VELOCITY_MAX;
        this.moveableObjects.forEach(function (obj) {
            obj.model.pos.x -= _this.car.carVelocity - obj.velocity;
            if (obj.onMove)
                obj.onMove(obj.model);
            if (obj.model.pos.x < -10)
                obj.onDisappear(obj.model);
            gameScene_r1.setXYWH(_this.car.carModel.pos.x + _this.car.carCollideRect.x, _this.car.carModel.pos.y + _this.car.carCollideRect.y, _this.car.carCollideRect.width, _this.car.carCollideRect.height);
            gameScene_r2.setXYWH(obj.model.getDestRect().x, obj.model.getDestRect().y, obj.model.getDestRect().width, obj.model.getDestRect().height);
            if (obj.collisionRect) {
                gameScene_r2.x += obj.collisionRect.x;
                gameScene_r2.y += obj.collisionRect.y;
                gameScene_r2.width = obj.collisionRect.width;
                gameScene_r2.height = obj.collisionRect.height;
            }
            if (obj.onCollided && mathEx_MathEx.overlapTest(gameScene_r1, gameScene_r2)) {
                obj.onCollided(obj.model);
            }
        });
    };
    GameScene.prototype.calcMyPosition = function () {
        var _this = this;
        var myPos = 1;
        this.opponents.forEach(function (o) {
            if (o.pos.x > _this.car.carModel.pos.x)
                myPos++;
        });
        return myPos;
    };
    GameScene.prototype.listenKeyboard = function () {
        var _this = this;
        var moveUp = function () {
            _this.car.carModel.pos.y -= 1;
            if (_this.car.carModel.pos.y < _this.car.minCarY)
                _this.car.carModel.pos.y = _this.car.minCarY;
        };
        var moveDown = function () {
            _this.car.carModel.pos.y += 1;
            if (_this.car.carModel.pos.y > _this.car.maxCarY)
                _this.car.carModel.pos.y = _this.car.maxCarY;
        };
        var speedDown = function () {
            _this.car.carVelocity -= 0.05;
            if (_this.car.carVelocity < 0)
                _this.car.carVelocity = 0;
        };
        this.on(KEYBOARD_EVENTS.keyPressed, function (e) {
            switch (e.key) {
                case KEYBOARD_KEY.UP: {
                    moveUp();
                    if (_this.timer) {
                        _this.timer.kill();
                    }
                    _this.timer = _this.setInterval(moveUp, 100);
                    break;
                }
                case KEYBOARD_KEY.DOWN: {
                    moveDown();
                    if (_this.timer) {
                        _this.timer.kill();
                    }
                    _this.timer = _this.setInterval(moveDown, 100);
                    break;
                }
                case KEYBOARD_KEY.LEFT: {
                    speedDown();
                    if (_this.timer) {
                        _this.timer.kill();
                    }
                    _this.timer = _this.setInterval(speedDown, 100);
                    break;
                }
                case KEYBOARD_KEY.RIGHT: {
                    break;
                }
            }
        });
        this.on(KEYBOARD_EVENTS.keyReleased, function (e) {
            if (_this.timer) {
                _this.timer.kill();
                _this.timer = undefined;
            }
        });
    };
    GameScene.onDisappearCommon = function (obj) {
        if (obj.pos.x < -10)
            obj.pos.x = mathEx_MathEx.random(32, 64);
    };
    return GameScene;
}(basePix32Scene_BasePix32Scene));


// CONCATENATED MODULE: ./demo/pix32/scenes/getReadyScene.ts





var getReadyScene_GetReadyScene = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(GetReadyScene, _super);
    function GetReadyScene() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    GetReadyScene.prototype.onReady = function () {
        var _this = this;
        _super.prototype.onReady.call(this);
        var getReady = new image_Image(this.game);
        getReady.setResourceLink(this.flagLink);
        getReady.pos.setXY(-12);
        this.screen.appendChild(getReady);
        getReady.transformPoint.setToCenter();
        this.addTween(new tween_Tween({
            target: getReady.scale,
            from: { x: 1, y: 1 },
            to: { x: 0.3, y: 0.3 },
            time: 2000,
            loop: true,
            numOfLoops: 3,
            yoyo: true,
            complete: function () {
                _this.game.runScene(new gameScene_GameScene(_this.game));
            },
        }));
    };
    GetReadyScene.prototype.onPreloading = function () {
        var _this = this;
        _super.prototype.onPreloading.call(this);
        this
            .
                resourceLoader.addNextTask(function () {
            _this.flagLink = _this.resourceLoader.loadTexture("./pix32/resources/images/flag.png");
        });
    };
    return GetReadyScene;
}(basePix32Scene_BasePix32Scene));


// CONCATENATED MODULE: ./demo/pix32/scenes/introScene.ts









var introScene_IntroScene = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(IntroScene, _super);
    function IntroScene() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    IntroScene.prototype.onPreloading = function () {
        var _this = this;
        _super.prototype.onPreloading.call(this);
        var binLink = this.resourceLoader.loadBinary('pix32/resources/music/theme.ym');
        this.resourceLoader.addNextTask((function () {
            _this.ym = new ym_Ym(binLink.getTarget());
            _this.themeAudioLink = loadSound(_this.game, _this.ym);
        }));
    };
    IntroScene.prototype.onReady = function () {
        var _this = this;
        _super.prototype.onReady.call(this);
        var sound = new sound_Sound(this.game);
        sound.setResourceLink(this.themeAudioLink);
        sound.loop = true;
        sound.play();
        var box = new rectangle_Rectangle(this.game);
        box.fillColor = color_Color.fromCssLiteral('#46e502');
        box.pos.setXY(8, 30);
        box.size.setWH(16, 4);
        var kernelBurnAccumulative = new kernelBurnAccumulativeFilter_KernelBurnAccumulativeFilter(this.game);
        kernelBurnAccumulative.setNoiseIntensity(1.2);
        box.filters = [kernelBurnAccumulative];
        this.screen.appendChild(box);
        this.oscilloscope.listen(sound, this.ym);
        this.on(KEYBOARD_EVENTS.keyPressed, function (_) {
            sound.stop();
            _this.game.runScene(new getReadyScene_GetReadyScene(_this.game));
        });
        (function () { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.print("-=... Special for IGDC. 32x32 ...=-", 9000)];
                    case 1:
                        _a.sent();
                        return [4, this.print("-=... made with vEngine ...=-", 8000)];
                    case 2:
                        _a.sent();
                        return [4, this.print("-=... Pixel Craft 32 competition ...=-", 10000)];
                    case 3:
                        _a.sent();
                        return [4, this.print("-=... Press any key to start ...=-", 10000, true)];
                    case 4:
                        _a.sent();
                        return [2];
                }
            });
        }); })();
    };
    return IntroScene;
}(basePix32Scene_BasePix32Scene));


// CONCATENATED MODULE: ./engine/media/context/basicAudioContext.ts

var basicAudioContext_BasicAudioContext = (function () {
    function BasicAudioContext(game, audioPlayer) {
        this.game = game;
        this.audioPlayer = audioPlayer;
        this.type = 'basicAudioContext';
        this._lastTimeId = 0;
    }
    BasicAudioContext.isAcceptable = function () {
        if (true)
            console.log('audio is not supported');
        return true;
    };
    BasicAudioContext.prototype.getLastValueId = function () {
        return this._lastTimeId;
    };
    BasicAudioContext.prototype.isCached = function (l) {
        return false;
    };
    BasicAudioContext.prototype.getAudioPlayer = function () {
        return this.audioPlayer;
    };
    BasicAudioContext.prototype.play = function (sound) {
        this.loop(sound.loop);
        this.setGain(sound.gain);
        this.setVelocity(sound.velocity);
        this.setStereoPan(sound.stereoPan);
        this.setFeedbackDelay(sound.feedbackDelay.delayTime, sound.feedbackDelay.gain);
    };
    BasicAudioContext.prototype.stop = function () { };
    BasicAudioContext.prototype.isFree = function () { return false; };
    BasicAudioContext.prototype.setGain = function (val) { };
    BasicAudioContext.prototype.setVelocity = function (val) { };
    BasicAudioContext.prototype.setStereoPan = function (val) { };
    BasicAudioContext.prototype.loop = function (val) { };
    BasicAudioContext.prototype.pause = function () { };
    BasicAudioContext.prototype.resume = function () { };
    BasicAudioContext.prototype.setFeedbackDelay = function (delayTime, gain) { };
    BasicAudioContext.prototype.load = function (buffer, link) {
        return Promise.resolve();
    };
    BasicAudioContext.prototype.clone = function () {
        return new BasicAudioContext(this.game, this.audioPlayer);
    };
    BasicAudioContext.prototype.getCurrentTimeSec = function () {
        return -1;
    };
    BasicAudioContext.prototype.setLastTimeId = function () {
        this._lastTimeId = Incrementer.getValue();
    };
    return BasicAudioContext;
}());


// CONCATENATED MODULE: ./engine/media/context/webAudioContext.ts



var WebAudioContextHolder = (function () {
    function WebAudioContextHolder() {
    }
    WebAudioContextHolder.getAudioContextClass = function () {
        return window.AudioContext ||
            window.webkitAudioContext || undefined;
    };
    WebAudioContextHolder.getNewAudioContext = function () {
        var clazz = WebAudioContextHolder.getAudioContextClass();
        if (clazz === undefined)
            return undefined;
        var c = new clazz();
        CtxHolder.fixAutoPlayPolicy(c);
        return c;
    };
    return WebAudioContextHolder;
}());

var CtxHolder = (function () {
    function CtxHolder() {
    }
    CtxHolder.getCtx = function () {
        if (CtxHolder._ctx && !CtxHolder._res) {
            CtxHolder._res = new CtxHolder._ctx();
            CtxHolder.fixAutoPlayPolicy(CtxHolder._res);
        }
        return CtxHolder._res;
    };
    CtxHolder.fixAutoPlayPolicy = function (res) {
        var listener = function () {
            res.resume();
            document.removeEventListener('click', listener);
        };
        document.addEventListener('click', listener);
    };
    CtxHolder._ctx = WebAudioContextHolder.getAudioContextClass();
    return CtxHolder;
}());
var decode = function (buffer) {
    return new Promise(function (resolve, reject) {
        CtxHolder.getCtx().decodeAudioData(buffer, function (decoded) {
            resolve(decoded);
        }, function (err) {
            reject(err.message);
        });
    });
};
var NodeChain = (function () {
    function NodeChain(root) {
        this.root = root;
        this._currentRoot = root;
    }
    NodeChain.prototype.getLastNode = function () {
        return this._currentRoot;
    };
    NodeChain.prototype.addNode = function (node) {
        node.connect(this._currentRoot);
        this._currentRoot = node;
    };
    return NodeChain;
}());
var createFeedBackDelayNodePair = function (context) {
    if (context.createDelay === undefined)
        return undefined;
    var delayNode = context.createDelay(1);
    delayNode.delayTime.value = 0;
    var gainNode = context.createGain();
    gainNode.gain.value = 0;
    delayNode.connect(gainNode);
    gainNode.connect(delayNode);
    var rootGainNode = context.createGain();
    rootGainNode.gain.value = 1;
    gainNode.connect(rootGainNode);
    return { delayNode: delayNode, gainNode: gainNode };
};
var webAudioContext_WebAudioContext = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(WebAudioContext, _super);
    function WebAudioContext(game, audioPLayer) {
        var _this = _super.call(this, game, audioPLayer) || this;
        _this.game = game;
        _this.audioPLayer = audioPLayer;
        _this._free = true;
        _this.type = 'webAudioContext';
        _this._ctx = CtxHolder.getCtx();
        _this._nodeChain = new NodeChain(_this._ctx.destination);
        _this._gainNode = _this._ctx.createGain();
        _this._nodeChain.addNode(_this._gainNode);
        if (_this._ctx.createStereoPanner) {
            _this._stereoPanNode = _this._ctx.createStereoPanner();
            _this._stereoPanNode.pan.value = 0.5;
            _this._nodeChain.addNode(_this._stereoPanNode);
        }
        _this._feedBackDelayNodePair = createFeedBackDelayNodePair(_this._ctx);
        if (_this._feedBackDelayNodePair !== undefined)
            _this._nodeChain.addNode(_this._feedBackDelayNodePair.gainNode);
        return _this;
    }
    WebAudioContext.isAcceptable = function () {
        return !!(window && CtxHolder.getCtx());
    };
    WebAudioContext.getContext = function () {
        return CtxHolder.getCtx();
    };
    WebAudioContext.prototype.load = function (buffer, link) {
        return Object(tslib_es6["b" /* __awaiter */])(this, void 0, Promise, function () {
            var _a, _b;
            return Object(tslib_es6["d" /* __generator */])(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (audioPlayer_AudioPlayer.cache[link.getUrl()]) {
                            return [2, undefined];
                        }
                        _a = audioPlayer_AudioPlayer.cache;
                        _b = link.getUrl();
                        return [4, decode(buffer)];
                    case 1:
                        _a[_b] = _c.sent();
                        return [2];
                }
            });
        });
    };
    WebAudioContext.prototype.isCached = function (l) {
        return !!audioPlayer_AudioPlayer.cache[l.getUrl()];
    };
    WebAudioContext.prototype.isFree = function () {
        return this._free;
    };
    WebAudioContext.prototype.play = function (sound) {
        var _this = this;
        this.setLastTimeId();
        this._free = false;
        this.startedTime = this._ctx.currentTime;
        var currSource = this._ctx.createBufferSource();
        currSource.buffer = audioPlayer_AudioPlayer.cache[sound.getResourceLink().getUrl()];
        currSource.connect(this._nodeChain.getLastNode());
        currSource.start(0, sound.offset, sound.duration);
        this._currSource = currSource;
        currSource.onended = function () {
            _this.stop();
        };
        _super.prototype.play.call(this, sound);
    };
    WebAudioContext.prototype.getCurrentTimeSec = function () {
        return this._ctx.currentTime - this.startedTime;
    };
    WebAudioContext.prototype.stop = function () {
        var currSource = this._currSource;
        if (currSource !== undefined) {
            currSource.stop();
            currSource.disconnect(this._nodeChain.getLastNode());
            currSource.onended = null;
        }
        this._currSource = undefined;
        this._free = true;
    };
    WebAudioContext.prototype.setGain = function (val) {
        this._gainNode.gain.value = val;
    };
    WebAudioContext.prototype.setFeedbackDelay = function (delayTime, gain) {
        if (this._feedBackDelayNodePair !== undefined) {
            this._feedBackDelayNodePair.delayNode.delayTime.value = delayTime;
            this._feedBackDelayNodePair.gainNode.gain.value = gain;
        }
    };
    WebAudioContext.prototype.setVelocity = function (val) {
        this._currSource.playbackRate.value = val;
    };
    WebAudioContext.prototype.setStereoPan = function (val) {
        if (this._stereoPanNode !== undefined)
            this._stereoPanNode.pan.value = val;
    };
    WebAudioContext.prototype.loop = function (val) {
        this._currSource.loop = val;
    };
    WebAudioContext.prototype.pause = function () {
        this._ctx.suspend();
    };
    WebAudioContext.prototype.resume = function () {
        this._ctx.resume();
    };
    WebAudioContext.prototype.clone = function () {
        return new WebAudioContext(this.game, this.audioPLayer);
    };
    return WebAudioContext;
}(basicAudioContext_BasicAudioContext));


// CONCATENATED MODULE: ./engine/media/context/htmlAudioContext.ts




var htmlAudioContext_CtxHolder = (function () {
    function CtxHolder() {
    }
    CtxHolder.getCtx = function () {
        var Ctx = window && window.Audio;
        return new Ctx();
    };
    return CtxHolder;
}());
var htmlAudioContext_HtmlAudioContext = (function (_super) {
    Object(tslib_es6["c" /* __extends */])(HtmlAudioContext, _super);
    function HtmlAudioContext(game, audioPlayer) {
        var _this = _super.call(this, game, audioPlayer) || this;
        _this.game = game;
        _this.audioPlayer = audioPlayer;
        _this.type = 'htmlAudioContext';
        _this.free = true;
        _this._ctx = htmlAudioContext_CtxHolder.getCtx();
        return _this;
    }
    HtmlAudioContext.isAcceptable = function () {
        return !!(window && window.Audio);
    };
    HtmlAudioContext.prototype.load = function (buffer, link) {
        var _a;
        return Object(tslib_es6["b" /* __awaiter */])(this, void 0, Promise, function () {
            var url, type, canPlayType;
            return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
                url = link.getUrl();
                if (true) {
                    type = (_a = url.split('.').pop()) !== null && _a !== void 0 ? _a : '';
                    if (type === '')
                        throw new debugError_DebugError("Can not define audio type from url: " + url);
                    canPlayType = this._ctx.canPlayType("audio/" + type);
                    if (canPlayType === '')
                        throw new debugError_DebugError("Can not play this audio type: " + type);
                }
                audioPlayer_AudioPlayer.cache[url] = url;
                return [2];
            });
        });
    };
    HtmlAudioContext.prototype.isFree = function () {
        return this.free;
    };
    HtmlAudioContext.prototype.play = function (sound) {
        var _this = this;
        var _a;
        this.setLastTimeId();
        var url = audioPlayer_AudioPlayer.cache[sound.getResourceLink().getUrl()];
        if ( true && !url)
            throw new debugError_DebugError("can not retrieve audio from cache (link id=" + sound.getResourceLink().getUrl() + ")");
        this.free = false;
        this._ctx.src = url;
        (_a = this._ctx.play()) === null || _a === void 0 ? void 0 : _a.catch(function (e) { });
        this.loop(sound.loop);
        this.setGain(sound.gain);
        this._ctx.onended = function () {
            _this.stop();
        };
        _super.prototype.play.call(this, sound);
    };
    HtmlAudioContext.prototype.getCurrentTimeSec = function () {
        return this._ctx.currentTime;
    };
    HtmlAudioContext.prototype.stop = function () {
        this.free = true;
        this._ctx.onended = null;
    };
    HtmlAudioContext.prototype.setGain = function (val) {
        this._ctx.volume = val;
    };
    HtmlAudioContext.prototype.loop = function (val) {
        this._ctx.loop = val;
    };
    HtmlAudioContext.prototype.pause = function () {
        this._ctx.pause();
    };
    HtmlAudioContext.prototype.resume = function () {
        if (true)
            throw new Error("not implemented for now");
    };
    HtmlAudioContext.prototype.clone = function () {
        return new HtmlAudioContext(this.game, this.audioPlayer);
    };
    return HtmlAudioContext;
}(basicAudioContext_BasicAudioContext));


// CONCATENATED MODULE: ./engine/media/audioNode.ts
var AudioNode = (function () {
    function AudioNode(context) {
        this.context = context;
    }
    AudioNode.prototype.play = function (sound) {
        this.stop();
        this.context.play(sound);
        this._currSound = sound;
        this._lastPlayedUrl = sound.getResourceLink().url;
    };
    AudioNode.prototype.stop = function () {
        this.context.stop();
        this._currSound = undefined;
    };
    AudioNode.prototype.setGain = function (val) {
        this.context.setGain(val);
    };
    AudioNode.prototype.setStereoPan = function (val) {
        this.context.setStereoPan(val);
    };
    AudioNode.prototype.setVelocity = function (val) {
        this.context.setVelocity(val);
    };
    AudioNode.prototype.pause = function () {
        this.context.pause();
    };
    AudioNode.prototype.loop = function (val) {
        this.context.loop(val);
    };
    AudioNode.prototype.resume = function () {
        this.context.resume();
    };
    AudioNode.prototype.isFree = function () {
        return this.context.isFree();
    };
    AudioNode.prototype.getLastPlayedUrl = function () {
        return this._lastPlayedUrl;
    };
    AudioNode.prototype.isLooped = function () {
        if (this._currSound === undefined)
            return false;
        return this._currSound.loop;
    };
    AudioNode.prototype.getCurrSound = function () {
        return this._currSound;
    };
    AudioNode.prototype.getCurrentTimeSec = function () {
        return this.context.getCurrentTimeSec();
    };
    return AudioNode;
}());


// CONCATENATED MODULE: ./engine/media/interface/iAudioPlayer.ts
var FREE_AUDIO_NODE_SEARCH_STRATEGY;
(function (FREE_AUDIO_NODE_SEARCH_STRATEGY) {
    FREE_AUDIO_NODE_SEARCH_STRATEGY[FREE_AUDIO_NODE_SEARCH_STRATEGY["GET_OLDEST"] = 0] = "GET_OLDEST";
    FREE_AUDIO_NODE_SEARCH_STRATEGY[FREE_AUDIO_NODE_SEARCH_STRATEGY["GET_OLDEST_NOT_LOOP"] = 1] = "GET_OLDEST_NOT_LOOP";
    FREE_AUDIO_NODE_SEARCH_STRATEGY[FREE_AUDIO_NODE_SEARCH_STRATEGY["SKIP_IF_NOT_FREE"] = 2] = "SKIP_IF_NOT_FREE";
})(FREE_AUDIO_NODE_SEARCH_STRATEGY || (FREE_AUDIO_NODE_SEARCH_STRATEGY = {}));

// CONCATENATED MODULE: ./engine/media/audioNodeSet.ts



var nodeComparator = function (a, b) {
    return a.context.getLastValueId() > b.context.getLastValueId() ? 1 : -1;
};
var audioNodeSet_AudioNodeSet = (function () {
    function AudioNodeSet(game, context, numOfNodes) {
        this.context = context;
        this.numOfNodes = numOfNodes;
        this.nodes = [];
        for (var i = 0; i < numOfNodes; i++) {
            this.nodes.push(new AudioNode(context.clone()));
        }
    }
    AudioNodeSet.prototype.getFreeNode = function (url) {
        var possibleFreeNode;
        for (var i = 0; i < this.numOfNodes; i++) {
            var node = this.nodes[i];
            if (node.isFree()) {
                possibleFreeNode = node;
                if (possibleFreeNode.getLastPlayedUrl() === url)
                    return node;
            }
        }
        if (possibleFreeNode !== undefined)
            return possibleFreeNode;
        switch (this.context.getAudioPlayer().freeNodeSearchStrategy) {
            case FREE_AUDIO_NODE_SEARCH_STRATEGY.GET_OLDEST:
                return this.nodes.sort(nodeComparator)[0];
            case FREE_AUDIO_NODE_SEARCH_STRATEGY.GET_OLDEST_NOT_LOOP:
                return this.nodes.filter(function (it) { return !it.isLooped(); }).sort(nodeComparator)[0];
            case FREE_AUDIO_NODE_SEARCH_STRATEGY.SKIP_IF_NOT_FREE:
                return undefined;
            default:
                if (true) {
                    throw new debugError_DebugError("undefined freeNodeSearchStrategy");
                }
                return undefined;
        }
    };
    AudioNodeSet.prototype.stopAll = function () {
        for (var i = 0; i < this.numOfNodes; i++) {
            this.nodes[i].stop();
        }
    };
    AudioNodeSet.prototype.pauseAll = function () {
        for (var i = 0; i < this.numOfNodes; i++) {
            this.nodes[i].pause();
        }
    };
    AudioNodeSet.prototype.resumeAll = function () {
        for (var i = 0; i < this.numOfNodes; i++) {
            this.nodes[i].resume();
        }
    };
    AudioNodeSet.prototype.getNodeBySound = function (sound) {
        for (var i = 0; i < this.numOfNodes; i++) {
            if (this.nodes[i].getCurrSound() === sound)
                return this.nodes[i];
        }
        return undefined;
    };
    return AudioNodeSet;
}());


// CONCATENATED MODULE: ./engine/media/audioPlayer.ts






var audioPlayer_AudioPlayer = (function () {
    function AudioPlayer(game) {
        this.game = game;
        this.freeNodeSearchStrategy = FREE_AUDIO_NODE_SEARCH_STRATEGY.GET_OLDEST;
        if (webAudioContext_WebAudioContext.isAcceptable()) {
            this._audioContext = new webAudioContext_WebAudioContext(game, this);
        }
        else if (htmlAudioContext_HtmlAudioContext.isAcceptable()) {
            this._audioContext = new htmlAudioContext_HtmlAudioContext(game, this);
        }
        else {
            this._audioContext = new basicAudioContext_BasicAudioContext(game, this);
        }
        this._audioNodeSet = new audioNodeSet_AudioNodeSet(game, this._audioContext, AudioPlayer.DEFAULT_AUDIO_NODES_COUNT);
    }
    AudioPlayer.prototype.loadSound = function (buffer, link) {
        return Object(tslib_es6["b" /* __awaiter */])(this, void 0, Promise, function () {
            return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this._audioContext.load(buffer, link)];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    AudioPlayer.prototype.isCached = function (link) {
        return this._audioContext.isCached(link);
    };
    AudioPlayer.prototype.play = function (sound) {
        if (true)
            sound.revalidate();
        var node = this._audioNodeSet.getFreeNode(sound.getResourceLink().url);
        if (node === undefined) {
            if (true) {
                console.log('no free node to play sound');
            }
            return;
        }
        node.play(sound);
    };
    AudioPlayer.prototype.stop = function (sound) {
        var node = this._audioNodeSet.getNodeBySound(sound);
        if (node === undefined)
            return;
        node.stop();
    };
    AudioPlayer.prototype.loop = function (sound) {
        var node = this._audioNodeSet.getNodeBySound(sound);
        if (node === undefined)
            return;
        node.loop(sound.loop);
    };
    AudioPlayer.prototype.getContext = function () {
        return this._audioContext;
    };
    AudioPlayer.prototype.setGain = function (sound) {
        var node = this._audioNodeSet.getNodeBySound(sound);
        if (node === undefined)
            return;
        node.setGain(sound.velocity);
    };
    AudioPlayer.prototype.setStereoPan = function (sound) {
        var node = this._audioNodeSet.getNodeBySound(sound);
        if (node === undefined)
            return;
        node.setStereoPan(sound.stereoPan);
    };
    AudioPlayer.prototype.stopAll = function () {
        this._audioNodeSet.stopAll();
    };
    AudioPlayer.prototype.pauseAll = function () {
        this._audioNodeSet.pauseAll();
    };
    AudioPlayer.prototype.resumeAll = function () {
        this._audioNodeSet.resumeAll();
    };
    AudioPlayer.prototype.getNodeBySound = function (sound) {
        return this._audioNodeSet.getNodeBySound(sound);
    };
    AudioPlayer.prototype.update = function (time, delta) {
    };
    AudioPlayer.cache = {};
    AudioPlayer.DEFAULT_AUDIO_NODES_COUNT = 6;
    return AudioPlayer;
}());


// CONCATENATED MODULE: ./demo/pix32/index.ts





var pix32_game = new game_Game({ width: 600, height: 460 });
var pix32_scene = new introScene_IntroScene(pix32_game);
pix32_game.setRenderer(webGlRenderer_WebGlRenderer);
pix32_game.setAudioPLayer(audioPlayer_AudioPlayer);
pix32_game.getRenderer().setPixelPerfect(true);
pix32_game.addControl(keyboardControl_KeyboardControl);
pix32_game.runScene(pix32_scene);


/***/ })
/******/ ]);