Commit 0cd23568 authored by rockyl's avatar rockyl

remove alienlib

parent e147c002
/**
* Created by rockyl on 16/3/29.
*/
import {IAnimation} from "./IAnimation";
export class Fade implements IAnimation {
private _tween: egret.Tween;
private _target: any;
private _targetAlpha: number;
private _duration: number;
constructor(target: any) {
this._target = target;
}
fadeIn(duration: number = 200): void {
this._duration = duration;
this._targetAlpha = 1;
this._target.alpha = 0;
this._target.visible = true;
this.play();
}
fadeOut(duration: number = 200): void {
this._duration = duration;
this._targetAlpha = 0;
this._target.alpha = 1;
this.play();
}
play(): void {
this._tween = egret.Tween.get(this._target).to({alpha: this._targetAlpha}, this._duration).set({visible: this._targetAlpha > 0});
}
stop(): void {
if (this._tween) {
egret.Tween.removeTweens(this._target);
}
}
}
/**
* Created by rockyl on 16/3/9.
*/
export interface IAnimation {
play(): void;
stop(): void;
}
/**
* Created by rockyl on 16/3/29.
*/
export class Shake {
private _tween: egret.Tween;
private _target: any;
private _callback;
private _size;
private _perDuration;
private _count = 0;
private _oldPos: any = {};
constructor(target: any) {
this._target = target;
}
play(callback, count = 1, size = 10, duration = 300): void {
this._callback = callback;
this._size = size;
this._perDuration = duration / 8;
this._count = count;
this._playOnce()
}
_playOnce() {
let {x, y} = this._target;
this._oldPos = {x, y};
let s = this._size;
let offsets = [
[0, -s],
[s, -s],
[s, 0],
[0, 0],
[-s, 0],
[-s, s],
[0, s],
[0, 0],
];
let tween = this._tween = egret.Tween.get(this._target, null, null, true);
offsets.forEach(offset => {
tween.to({x: x + offset[0], y: y + offset[1]}, this._perDuration)
});
tween.call(() => {
if (this._count > 0) {
this._count--;
this._playOnce();
} else {
this._onFinished();
}
});
}
_onFinished() {
if (this._callback) {
this._callback();
}
}
stop(): void {
if (this._tween) {
egret.Tween.get(this._target, null, null, true)
.to(this._oldPos, 10);
}
}
}
/**
* Created by rockyl on 2018/1/5.
*
* 闪烁图片
*/
import {Wave} from "./Wave";
export class TwinkleImage extends eui.Image {
private _autoPlay = true;
private _duration = 1000;
private _max = 1;
private _min = 0;
private _loop = 0;
private _wave;
protected childrenCreated(): void {
super.childrenCreated();
this.resetWave();
if (this._autoPlay) {
this.play();
}
}
private resetWave() {
if (this._wave) {
this._wave.stop();
}
this._wave = new Wave(this, this._duration, this.wave.bind(null, this._max, this._min), this._loop, false);
}
private wave(max, min, t) {
return {
alpha: (Math.sin(t) / 2 + 0.5) * (max - min) + min
}
}
play() {
this._wave.play();
}
stop() {
this._wave.stop();
}
public get autoPlay() {
return this._autoPlay;
}
public set autoPlay(value) {
if (this._autoPlay != value) {
this._autoPlay = value;
this.resetWave();
}
}
public get duration() {
return this._duration;
}
public set duration(value) {
if (this._duration != value) {
this._duration = value;
this.resetWave();
}
}
public get max() {
return this._max;
}
public set max(value) {
if (this._max != value) {
this._max = value;
this.resetWave();
}
}
public get min() {
return this._min;
}
public set min(value) {
if (this._min != value) {
this._min = value;
this.resetWave();
}
}
public get loop() {
return this._loop;
}
public set loop(value) {
if (this._loop != value) {
this._loop = value;
this.resetWave();
}
}
}
/**
* Created by rockyl on 16/3/9.
*/
import {IAnimation} from "./IAnimation";
export class Wave implements IAnimation {
static round: Function = function (h: number, t: number): any {
return {x: Math.cos(t) * h, y: Math.sin(t) * h};
};
static cos: Function = function (h: number, t: number): any {
return {x: Math.cos(t) * h, y: 0};
};
static sin: Function = function (h: number, t: number): any {
h = h || 1;
return {x: 0, y: Math.sin(t) * h};
};
static rotate: Function = function (t: number): any {
return {r: 360 * t / Math.PI / 2};
};
static shake: Function = function (angle: number, count: number, t: number): any {
return {r: Math.sin(t * count) * angle};
};
static breath: Function = function (scale: number, t: number): any {
return {sx: Math.sin(t) * scale + 1, sy: -Math.sin(t + Math.PI / 4) * scale + 1};
};
static zoom: Function = function (scale: number, t: number): any {
scale = scale || 0.1;
return {sx: Math.sin(t) * scale + 1, sy: Math.sin(t) * scale + 1};
};
static fade: Function = function (base, t: number): any {
return {alpha: (Math.sin(t) + 1) * 0.5 + base};
};
_tween: egret.Tween;
target: any;
duration: number;
delay: number;
offset: number;
loop: number;
reverse: boolean;
private _calProps;
private _oldProperties: any = {};
private _count;
constructor(target: any, duration: number, calProps: Function = null, loop: number = 0, autoPlay: boolean = true, reverse: boolean = false, delay: number = 0, offset: number = 0) {
this.target = target;
this._calProps = calProps ? calProps : Wave.round;
this.duration = duration;
this.loop = loop;
this.reverse = reverse;
this.delay = delay;
this.offset = offset;
this.updateRegisterPos();
if (autoPlay) {
this.play();
}
}
updateRegisterPos(): void {
this._oldProperties.x = this.target.x;
this._oldProperties.y = this.target.y;
this._oldProperties.scaleX = this.target.scaleX;
this._oldProperties.scaleY = this.target.scaleY;
this._oldProperties.skewX = this.target.skewX;
this._oldProperties.skewY = this.target.skewY;
this._oldProperties.rotation = this.target.rotation;
this._oldProperties.alpha = this.target.alpha;
}
play() {
if (this._tween) {
return this._tween;
}
this._count = 0;
return this._playStep();
}
_playStep() {
if (this.loop > 0 && this._count >= this.loop) {
this.stop();
return;
}
this._count++;
this.t = this.reverse ? Math.PI * 2 : 0;
this._tween = egret.Tween.get(this);
this._tween.wait(this.delay).to({t: this.reverse ? 0 : Math.PI * 2}, this.duration).call(this._playStep, this);
return this._tween;
}
private _t: number = 0;
private get t(): number {
return this._t;
}
private set t(value: number) {
if (!this.target.stage) {
return;
}
this._t = value;
let props: any = this._calProps.call(this, this._t + this.offset);
if (props.hasOwnProperty('x')) {
this.target.x = (props.x || 0) + this._oldProperties.x;
}
if (props.hasOwnProperty('y')) {
this.target.y = (props.y || 0) + this._oldProperties.y;
}
if (props.hasOwnProperty('sx')) {
this.target.scaleX = props.sx;
}
if (props.hasOwnProperty('sy')) {
this.target.scaleY = props.sy;
}
if (props.hasOwnProperty('skewX')) {
this.target.skewX = props.skewX;
}
if (props.hasOwnProperty('skewY')) {
this.target.skewY = props.skewY;
}
if (props.hasOwnProperty('r')) {
this.target.rotation = props.r;
}
if (props.hasOwnProperty('alpha')) {
this.target.alpha = props.alpha;
}
}
stop(recovery: boolean = false, animation: boolean = false, duration: number = 1000): void {
if (!this._tween) {
return;
}
egret.Tween.removeTweens(this);
if (recovery) {
egret.Tween.get(this.target).to(this._oldProperties, duration);
}
this._tween = null;
}
get playing(): boolean {
return this._tween != null;
}
}
/**
* Created by rockyl on 2018/9/12.
*/
export {
}
/**
* Created by rockyl on 2017/12/5.
*
* 自填充组件
*/
export class FullChild extends eui.Group {
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedFromStage, this);
}
protected onAddedToStage(event: egret.Event): void {
this.addEventListener(egret.Event.RESIZE, this.onResize, this);
}
protected onRemovedFromStage(event: egret.Event): void {
this.removeEventListener(egret.Event.RESIZE, this.onResize, this);
}
private onResize(event: egret.Event): void {
if (this.numChildren > 0) {
this.updateChild(this.getChildAt(0))
}
}
private updateChild(child) {
let scale;
if (this.width / this.height > child.width / child.height) {
scale = this.width / child.width;
} else {
scale = this.height / child.height;
}
child.scaleX = child.scaleY = scale;
}
}
/**
* Convert the text in html format to the object that can be assigned to the egret.TextField#textFlow property
* @see http://edn.egret.com/cn/docs/page/146 Text mixed in a variety of style
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/text/HtmlTextParser.ts
* @language en_US
*/
/**
* 将html格式文本转换为可赋值给 egret.TextField#textFlow 属性的对象
* @see http://edn.egret.com/cn/docs/page/146 多种样式文本混合
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/text/HtmlTextParser.ts
* @language zh_CN
*/
export class HtmlTextParser {
/**
* @version Egret 2.4
* @platform Web,Native
*/
constructor() {
this.initReplaceArr();
this.initPreReplaceArr();
}
private replaceArr: any[] = [];
private initReplaceArr(): void {
const arr = this.replaceArr = [];
arr.push([/&lt;/g, "<"]);
arr.push([/&gt;/g, ">"]);
arr.push([/&amp;/g, "&"]);
arr.push([/&quot;/g, "\""]);
arr.push([/&apos;/g, "\'"]);
}
private preReplaceArr: any[] = [];
private initPreReplaceArr() {
const arr = this.preReplaceArr = [];
arr.push([/\\\"/g, "\""]);
arr.push([/<br>/g, "\n"]);
}
/**
* @private
*
* @param value
* @returns
*/
private replaceSpecial(value: string): string {
for (let i = 0; i < this.replaceArr.length; i++) {
let k = this.replaceArr[i][0];
let v = this.replaceArr[i][1];
value = value.replace(k, v);
}
return value;
}
/**
* @private
*/
private resutlArr: Array<egret.ITextElement> = [];
/**
* Convert the text in html format to the object that can be assigned to the egret.TextField#textFlow property
* @param htmltext {string} Text in html
* @returns {Array<egret.ITextElement>} 可赋值给 egret.TextField#textFlow Object that can be assigned to the egret.TextField#textFlow property
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将html格式文本转换为可赋值给 egret.TextField#textFlow 属性的对象
* @param htmltext {string} html文本
* @returns {Array<egret.ITextElement>} 可赋值给 egret.TextField#textFlow 属性的对象
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public parse(htmltext: string): egret.ITextElement[] {
this.preReplaceArr.forEach(p => {
htmltext = htmltext.replace(p[0], p[1]);
});
this.stackArray = [];
this.resutlArr = [];
let firstIdx = 0;//文本段开始位置
let length: number = htmltext.length;
while (firstIdx < length) {
let starIdx: number = htmltext.indexOf("<", firstIdx);
if (starIdx < 0) {
this.addToResultArr(htmltext.substring(firstIdx));
firstIdx = length;
}
else {
this.addToResultArr(htmltext.substring(firstIdx, starIdx));
let fontEnd = htmltext.indexOf(">", starIdx);
if (fontEnd == -1) {
egret.$error(1038);
fontEnd = starIdx;
}
else if (htmltext.charAt(starIdx + 1) == "\/") {//关闭
this.stackArray.pop();
}
else {
this.addToArray(htmltext.substring(starIdx + 1, fontEnd));
}
firstIdx = fontEnd + 1;
}
}
return this.resutlArr;
}
public parser(htmltext: string): Array<egret.ITextElement> {
return this.parse(htmltext);
}
/**
* @private
*
* @param value
*/
private addToResultArr(value: string): void {
if (value == "") {
return;
}
value = this.replaceSpecial(value);
if (this.stackArray.length > 0) {
this.resutlArr.push({text: value, style: this.stackArray[this.stackArray.length - 1]})
}
else {
this.resutlArr.push(<egret.ITextElement>{text: value});
}
}
//将字符数据转成Json数据
private changeStringToObject(str: string): egret.ITextStyle {
str = this.replaceSpecial(str.trim());
let info: any = {};
let header = [];
if (str.charAt(0) == "i" || str.charAt(0) == "b" || str.charAt(0) == "u") {
this.addProperty(info, str, "true");
}
else if (header = str.match(/^(font|a)\s/)) {
str = str.substring(header[0].length).trim();
let next: number = 0;
let titles;
while (titles = str.match(this.getHeadReg())) {
let title = titles[0];
let value = "";
str = str.substring(title.length).trim();
if (str.charAt(0) == "\"") {
next = str.indexOf("\"", 1);
value = str.substring(1, next);
next += 1;
}
else if (str.charAt(0) == "\'") {
next = str.indexOf("\'", 1);
value = str.substring(1, next);
next += 1;
}
else {
value = str.match(/(\S)+/)[0];
next = value.length;
}
this.addProperty(info, title.substring(0, title.length - 1).trim(), value.trim());
str = str.substring(next).trim();
}
}
return info;
}
/**
* @private
*
* @returns
*/
private getHeadReg(): RegExp {
return /^(color|textcolor|strokecolor|stroke|b|bold|i|italic|u|size|fontfamily|href|target)(\s)*=/;
}
/**
* @private
*
* @param info
* @param head
* @param value
*/
private addProperty(info: egret.ITextStyle, head: string, value: string): void {
switch (head.toLowerCase()) {
case "color":
case "textcolor":
value = value.replace(/#/, "0x");
info.textColor = parseInt(value);
break;
case "strokecolor":
value = value.replace(/#/, "0x");
info.strokeColor = parseInt(value);
break;
case "stroke":
info.stroke = parseInt(value);
break;
case "b":
case "bold":
info.bold = value == "true";
break;
case "u":
info.underline = value == "true";
break;
case "i":
case "italic":
info.italic = value == "true";
break;
case "size":
info.size = parseInt(value);
break;
case "fontfamily":
info.fontFamily = value;
break;
case "href":
info.href = this.replaceSpecial(value);
break;
case "target":
info.target = this.replaceSpecial(value);
break;
}
}
/**
* @private
*/
private stackArray: Array<egret.ITextStyle>;
/**
* @private
*
* @param infoStr
*/
private addToArray(infoStr: string): void {
let info: egret.ITextStyle = this.changeStringToObject(infoStr);
if (this.stackArray.length == 0) {
this.stackArray.push(info);
}
else {
let lastInfo: Object = this.stackArray[this.stackArray.length - 1];
for (let key in lastInfo) {
if (info[key] == null) {
info[key] = lastInfo[key];
}
}
this.stackArray.push(info);
}
}
}
/**
* Created by rockyl on 2018/8/16.
*
* 滚动式背景图
*/
export enum LOOP_DIRECTION {
LEFT,
RIGHT,
UP,
DOWN,
}
export class LoopComponent extends egret.DisplayObjectContainer {
_direction: LOOP_DIRECTION;
_sizeField: string;
_posField: string;
_moveSign;
_lastPos = 0;
_onceDistance;
_loopDistance;
_distance = 0;
_scrollRect: egret.Rectangle;
constructor(direction: LOOP_DIRECTION, width, height) {
super();
this._scrollRect = new egret.Rectangle(0, 0, width, height);
this._direction = direction;
this._sizeField = direction < 2 ? 'width' : 'height';
this._posField = direction < 2 ? 'x' : 'y';
this._moveSign = direction % 2 == 0 ? 1 : -1;
}
private setup(parts) {
let distance = 0;
for (let item of parts) {
let part;
if (typeof item == 'string') {
part = new egret.Bitmap(RES.getRes(item));
} else if (item instanceof egret.Texture) {
part = new egret.Bitmap(item);
} else {
part = item;
}
if(this._moveSign < 0){
this._lastPos = part[this._posField] = this.numChildren == 0 ? 0 : this._lastPos - part[this._sizeField];
}else{
part[this._posField] = this.numChildren == 0 ? 0 : this._lastPos;
this._lastPos += part[this._sizeField];
}
distance += part[this._sizeField];
this.addChild(part);
}
return distance;
}
setupOnce(resArr) {
this._distance = this._onceDistance = this.setup(resArr);
this.update();
}
setupLoop(resArr) {
this._loopDistance = this.setup(resArr);
this._distance = this._onceDistance + this._loopDistance - (this._moveSign < 0);
this.setup(resArr);
this.update();
}
setViewport(pos) {
let nPos;
if (pos < this._distance) {
nPos = this._moveSign * pos
} else {
nPos = this._moveSign * (pos - this._distance) % this._loopDistance + this._onceDistance - (this._moveSign < 0 ? this._onceDistance * 2 : 0)
}
this._scrollRect[this._posField] = nPos;
this.update();
}
update() {
this.scrollRect = this._scrollRect;
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/3/16.
*/
import {checkNeedLoad, loadResGroups} from "../tools/ResGroupsLoader";
let watchPromise;
export function load(resGroupNames, onProgress, onBeginLoadResGroups, onEndLoadResGroups) {
let p: Promise<any>;
let loading = true;
if (resGroupNames && resGroupNames.length > 0 && checkNeedLoad(resGroupNames)) {
onBeginLoadResGroups(true);
p = loadResGroups(resGroupNames, onProgress).then(() => {
loading = false;
onEndLoadResGroups();
});
} else {
onBeginLoadResGroups(false);
loading = false;
onEndLoadResGroups();
p = Promise.resolve();
}
return p.then(() => {
watchPromise && watchPromise();
});
}
export function watchLoaded() {
return new Promise(resolve => {
watchPromise = resolve;
})
}
\ No newline at end of file
/**
* Created by rockyl on 2018/9/12.
*/
import * as ResourceLoader from './ResourceLoader'
export {
ResourceLoader,
}
/**
* Created by rockyl on 2018/9/11.
*/
import * as animation from './animation'
import * as egret from './egret'
import * as navigator from './navigator'
import * as popup from './popup'
import * as support from './support'
import * as tools from './tools'
import * as ui from './ui'
export {
animation,
egret,
navigator,
popup,
support,
tools,
ui,
}
/**
* Created by rocky.l on 2017/1/19.
*
* 场景导航器
*/
import {INavigatorDelegate, NavigatorAction, StackNavigator} from "./StackNavigator";
export interface INavigatorViewBase {
onAddView(): boolean;
onWillMount(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillUnMount(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillEnter(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidEnter(last: string, action: NavigatorAction, parameters: any): void;
onWillLeave(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidLeave(next: string, action: NavigatorAction, parameters: any): void;
}
export class Navigator extends egret.EventDispatcher implements INavigatorDelegate {
static VIEW_WILL_ENTER: string = 'VIEW_WILL_ENTER';
static VIEW_DID_ENTER: string = 'VIEW_DID_ENTER';
static VIEW_WILL_LEAVE: string = 'VIEW_WILL_LEAVE';
static VIEW_DID_LEAVE: string = 'VIEW_DID_LEAVE';
public static log = false;
stack: StackNavigator;
protected _classDic: any;
protected _instanceDic: any;
protected _currentName: string;
protected _currentView: INavigatorViewBase;
constructor() {
super();
this._classDic = {};
this._instanceDic = {};
this.stack = new StackNavigator(this);
}
register(name: string, clazz: any): void {
this._classDic[name] = clazz;
}
push(name: string, parameters: any = null) {
this.stack.push(name, parameters);
}
pop(parameters: any = null) {
this.stack.pop(parameters);
}
popToBottom(parameters: any = null) {
this.stack.popTo(0, null, parameters);
}
popAll(name: string, parameters: any = null) {
this.stack.popAll(name, parameters);
}
replace(name: string, parameters: any = null) {
this.stack.replace(name, parameters);
}
jump(name: string, parameters: any = null) {
this.stack.jump(name, parameters);
}
get currentView(): INavigatorViewBase {
return this._currentView;
}
get currentName(): string {
return this._currentName;
}
protected newView(name: string): INavigatorViewBase {
return new this._classDic[name]();
}
protected getViewInstanceByName(name: string): INavigatorViewBase {
let view: INavigatorViewBase = this._instanceDic[name];
if (!view) {
view = this._instanceDic[name] = this.newView(name);
}
return view;
}
protected addView(view: INavigatorViewBase, addToBottom) {
}
/**
* 栈入实现
* @param name
* @param last
* @param action
* @param parameters
* @returns {Promise<void>}
*/
async onEnter(name: string, last: string, action: NavigatorAction, parameters: any) {
let view: INavigatorViewBase = this.getViewInstanceByName(name);
this._currentView = view;
this._currentName = name;
await view.onWillMount(last, action, parameters);
let addToBottom = view.onAddView();
this.addView(view, addToBottom);
if (Navigator.log) console.log(name + ' will enter.');
this.dispatchEventWith(Navigator.VIEW_WILL_ENTER, false, {name, last, action, parameters});
await view.onWillEnter(last, action, parameters);
if (Navigator.log) console.log(name + ' did enter.');
this.dispatchEventWith(Navigator.VIEW_DID_ENTER, false, {name, last, action, parameters});
view.onDidEnter(last, action, parameters);
}
/**
* 栈出实现
* @param name
* @param next
* @param action
* @param parameters
* @returns {Promise<void>}
*/
async onLeave(name: string, next: string, action: NavigatorAction, parameters: any) {
let view: INavigatorViewBase = this.getViewInstanceByName(name);
await view.onWillUnMount(name, action, parameters);
if (Navigator.log) console.log(name + ' will leave.');
this.dispatchEventWith(Navigator.VIEW_WILL_LEAVE, false, {name, next, action, parameters});
await view.onWillLeave(next, action, parameters);
if (Navigator.log) console.log(name + ' did leave.');
this.dispatchEventWith(Navigator.VIEW_DID_LEAVE, false, {name, next, action, parameters});
view.onDidLeave(next, action, parameters);
}
/**
* 当收到错误实现
* @param error
*/
onError(error: Error) {
}
}
/**
* Created by rocky.l on 2017/1/17.
*
* 堆栈导航器
*/
export enum NavigatorAction {Push, Pop, Replace, Jump}
export interface INavigatorDelegate {
onEnter(name: string, last: string, action: NavigatorAction, parameters: any);
onLeave(name: string, next: string, action: NavigatorAction, parameters: any);
onError(error: Error);
}
export class StackNavigator {
private _stack: string[];
private _delegate: INavigatorDelegate;
constructor(delegate: INavigatorDelegate) {
this._stack = [];
this._delegate = delegate;
}
private catchPromise(p: Promise<any>) {
if (p) {
p.catch((e => {
this._delegate.onError(e);
}))
}
}
push(name: string, parameters: any = null) {
let last: string = this.getTopSceneName();
if (last) {
if (last == name) {
return;
}
this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Push, parameters));
}
this._stack.push(name);
this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Push, parameters));
}
popTo(index, name?: string, parameters: any = null) {
if (this._stack.length > 0 && this._stack.length < (index + 1)) {
return;
}
let last: string = this.getTopSceneName();
this._stack.splice(Math.max(index + 1, 0));
let next: string = this._stack[index];
if (!next) {
this._stack.push(next = name);
}
if (last) {
this.catchPromise(this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters));
}
this.catchPromise(this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters));
}
pop(parameters: any = null) {
this.popTo(this._stack.length - 2, null, parameters);
}
popAll(name: string, parameters: any = null) {
this.popTo(-1, name, parameters);
}
replace(name: string, parameters: any = null) {
let last: string = this._stack.pop();
this._stack.push(name);
this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Replace, parameters));
this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Replace, parameters));
}
jump(name: string, parameters: any = null) {
if (this._stack.length < 2) {
this.push(name, parameters);
return;
}
let last: string = this._stack.pop();
this._stack.splice(1);
let next: string = name;
this._stack.push(next);
this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters);
this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters);
}
private getTopSceneName(): string {
return this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
}
private getBottomSceneName(): string {
return this._stack.length > 0 ? this._stack[0] : null;
}
}
/**
* Created by rockyl on 2018/9/12.
*/
import {Navigator} from './Navigator'
import {StackNavigator} from './StackNavigator'
export {
Navigator,
StackNavigator,
}
\ No newline at end of file
/**
* Created by rockyl on 16/3/9.
*/
import {StageProxy} from "../support";
import {IDialogEffect, None} from "./PopupEffect";
import {combineProp} from "../tools/Utils";
import {enumChildren} from "../tools/EgretUtils";
const defaultModalConfig: any = {
color: 0,
alpha: 0.7,
duration: 200,
};
const POPUP_SHOW: string = 'POPUP_SHOW';
const POPUP_HIDE: string = 'POPUP_HIDE';
let _modalMask: eui.Rect;
let _pupUpStack: Array<any> = [];
let _popLayer: eui.Group;
let _modalConfig: any;
export function init(popLayer: eui.Group) {
_popLayer = popLayer;
_popLayer.width = StageProxy.getWidth();
_popLayer.height = StageProxy.getHeight();
StageProxy.getStage().addEventListener(egret.Event.RESIZE, onStageResize, this);
}
function onStageResize(event: egret.Event = null): void {
if (_modalMask) {
_modalMask.width = StageProxy.getWidth();
_modalMask.height = StageProxy.getHeight();
}
}
export function addPopUp(target: eui.Component, effectClazz: any = null, effectParams: any = null, modalTouchFun: Function = null, modal: boolean = true, modalConfig: any = null): void {
if (target.parent) {
return;
}
let dispatchPopUpShow = _pupUpStack.length == 0;
let top = getTopPupUp();
if (top && top['inactive']) {
top['inactive']();
}
_modalConfig = combineProp(defaultModalConfig, modalConfig);
_pupUpStack.unshift({target: target, modalTouchFun: modalTouchFun, modal: modal});
updateModalMask(_pupUpStack[0]);
let effect: IDialogEffect = createEffectInstance(effectClazz);
effect.show(target, _popLayer, function (): void {
if (target['active']) {
target['active']();
}
}, this, effectParams);
if (dispatchPopUpShow) {
//dispatchEventWith(PopUpManager.POPUP_SHOW);
}
}
export function removePopUp(target: eui.Component, effectClazz: any = null, effectParams: any = null): void {
if (!target.parent) {
return;
}
if (!getInStack(target, true)) {
return;
}
let aimItem: any;
_pupUpStack.some(function (item: any): boolean {
if (item.modal) {
aimItem = item;
return true;
}
});
if (aimItem) {
updateModalMask(aimItem);
} else {
setModalMaskVisible(false);
}
let effect: IDialogEffect = createEffectInstance(effectClazz);
effect.hide(target, _popLayer, function (): void {
if (target['inactive']) {
target['inactive']();
}
let top = getTopPupUp();
if (top && top['active']) {
top['active']();
}
}, this, effectParams);
let dispatchPopUpHide = _pupUpStack.length == 0;
if (dispatchPopUpHide) {
//dispatchEventWith(PopUpManager.POPUP_HIDE);
}
}
function getTopPupUp() {
if (_pupUpStack.length > 0) {
return _pupUpStack[_pupUpStack.length - 1];
} else {
return null;
}
}
export function removeTopPupUp(): boolean {
let top = getTopPupUp();
if (top) {
if (top['close']) {
top['close']();
}
return true;
}
return false;
}
export function removeAllPupUp(): void {
enumChildren(_popLayer, (popup: any) => {
if (popup != _modalMask) {
popup['close']();
}
});
}
function getInStack(target: egret.DisplayObjectContainer, del: boolean = false): any {
let data: any;
_pupUpStack.some(function (item: any, index: number): boolean {
if (item.target == target) {
data = {item: item, index: index};
return true;
}
});
if (data && del) {
_pupUpStack.splice(data.index, 1);
}
return data;
}
function createEffectInstance(effectClazz: any = null): IDialogEffect {
let effect: IDialogEffect;
if (effectClazz) {
effect = new effectClazz();
} else {
effect = new None();
}
return effect;
}
function onModalMaskTap(event: egret.TouchEvent): void {
let item: any = _pupUpStack[0];
if (item && item.modal && item.modalTouchFun) {
item.modalTouchFun();
}
}
function updateModalMask(item: any): void {
let maskIndex: number = _popLayer.getChildIndex(_modalMask);
let index: number = _popLayer.getChildIndex(item.target);
if (maskIndex != index - 1) {
setModalMaskVisible(item.modal, index);
}
}
function setModalMaskVisible(visible: boolean, index: number = -1): void {
const modalMask = getModalMask();
if (visible) {
modalMask.fillColor = _modalConfig.color;
modalMask.fillAlpha = _modalConfig.alpha;
if (index >= 0) {
setModalMaskVisible(true);
_popLayer.addChildAt(modalMask, index);
} else {
_popLayer.addChild(modalMask);
}
egret.Tween.get(modalMask, null, null, true).to({alpha: 1}, _modalConfig.duration);
} else {
if (modalMask.parent) {
egret.Tween.get(modalMask, null, null, true).to({alpha: 0}, _modalConfig.duration).call(function (modalMask: eui.Rect): void {
_popLayer.removeChild(modalMask);
}, this, [modalMask]);
}
}
}
function getModalMask(): eui.Rect {
if (!_modalMask) {
_modalMask = new eui.Rect();
_modalMask.width = StageProxy.getWidth();
_modalMask.height = StageProxy.getHeight();
_modalMask.addEventListener(egret.TouchEvent.TOUCH_TAP, onModalMaskTap, this);
}
return _modalMask;
}
/**
* Created by rockyl on 16/3/9.
*/
import {None} from "./PopupEffect";
import {addPopUp, removePopUp} from "./PopUpManager";
import {checkNeedLoad, loadResGroups} from "../tools/ResGroupsLoader";
import {EventComponent} from "../support/EventComponent";
export class PopupBase extends EventComponent {
protected showEffect: any;
protected showEffectParams: any;
protected closeEffect: any;
protected closeEffectParams: any;
protected popupShowBanner: boolean;
protected _callback: Function;
protected _excludeActionsClose: string[] = [];
constructor(showEffect: any = null, showEffectParams: any = null, closeEffect: any = null, closeEffectParams: any = null, popupShowBanner: boolean = false) {
super();
this.showEffect = showEffect || None;
this.showEffectParams = showEffectParams;
this.closeEffect = closeEffect || None;
this.closeEffectParams = closeEffectParams;
this.popupShowBanner = popupShowBanner;
this._excludeActionsClose = [];
this.init();
}
protected init(): void {
}
protected getResGroupNames(): string[] {
return null;
}
protected onBeginLoadResGroups() {
}
protected onEndLoadResGroups() {
}
protected getSkinName(): any {
return null;
}
/**
* 添加不用关闭的动作
* @param actions
*/
addExcludeForClose(actions: string[]): void {
this._excludeActionsClose = this._excludeActionsClose.concat(actions);
}
dealAction = (action: string = null, data: any = null) => {
if (this._callback) {
this._callback(action || 'close', data);
}
if (this._excludeActionsClose.indexOf(action) < 0) {
this.close();
this._callback = null;
}
};
async popup(modalTouchFun: Function = null, modal: boolean = true, modalConfig: any = null) {
let resGroupNames = this.getResGroupNames();
if (resGroupNames && resGroupNames.length > 0 && checkNeedLoad(resGroupNames)) {
this.onBeginLoadResGroups();
await loadResGroups(resGroupNames);
this.onEndLoadResGroups();
} else {
this.onEndLoadResGroups();
}
if (!this.skinName) {
let skinName = this.getSkinName();
if (skinName) {
this.skinName = skinName;
}
}
this._popup(modalTouchFun, modal, modalConfig);
}
private _popup(modalTouchFun: Function = null, modal: boolean = true, modalConfig: any = null) {
addPopUp(this, this.showEffect, this.showEffectParams, modalTouchFun, modal, modalConfig);
}
close(): void {
removePopUp(this, this.closeEffect, this.closeEffectParams);
}
active() {
this.enableEvents();
}
inactive() {
this.disableEvents();
}
}
/**
* Created by rockyl on 16/3/9.
*/
/*
* Blind 刷出来
* Bounce 跳动
* Clip 横向收缩
* Scale 纵向收缩
* Drop 单向收缩+fade
* Slide 单向收缩
* Explode 八方向爆炸
* Fade 渐进
* Fold 抽屉收缩
* Puff 放大+Fade
* Pulsate 闪烁
* Shake 抖动
* */
import {StageProxy} from "../support";
export class Utils {
static centerPopUp(popUp: eui.Component): void {
popUp.horizontalCenter = popUp.verticalCenter = 0;
}
static centerHorizontal(popUp: eui.Component): void {
popUp.horizontalCenter = 0;
}
static centerVertical(popUp: eui.Component): void {
popUp.verticalCenter = 0;
}
static notCenterPopUp(popUp: eui.Component): void {
popUp.horizontalCenter = popUp.verticalCenter = NaN;
}
static getCenterPos(popUp: eui.Component): any {
let x: number = 0;
let y: number = 0;
let parent: egret.DisplayObjectContainer = popUp.parent;
if (parent) {
x = (parent.width - popUp.width) * 0.5;
y = (parent.height - popUp.height) * 0.5;
}
return {x: x, y: y};
}
static transDirection(dStr: string): number {
let d: number;
switch (dStr) {
case "up":
d = 0;
break;
case "right":
d = 1;
break;
case "bottom":
d = 2;
break;
case "left":
d = 3;
break;
}
return d;
}
}
export interface IDialogEffect {
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void;
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void;
}
export class None implements IDialogEffect {
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
target.scaleX = target.scaleY = target.alpha = 1;
parent.addChild(target);
Utils.centerPopUp(target);
callback.call(thisObj);
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
parent.removeChild(target);
callback.call(thisObj);
}
}
/***
* 渐进渐出
*/
export class Fade implements IDialogEffect {
static DEFAULT_DURATION: number = 200;
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
target.alpha = 0;
parent.addChild(target);
Utils.centerPopUp(target);
let duration: number = (params && params.duration) || Fade.DEFAULT_DURATION;
egret.Tween.get(target).to({alpha: 1}, duration).call(callback, thisObj);
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let duration: number = (params && params.duration) || Fade.DEFAULT_DURATION;
egret.Tween.get(target).to({alpha: 0}, duration).call(function (): void {
parent.removeChild(target);
callback.call(thisObj);
}, this);
}
}
/**
* 飞入
* duration: 时间
* direction: 方向(up, bottom, left, right)
* withFade: 是否伴随渐进渐出
* startPos:
* endPos:
*/
export class Flew implements IDialogEffect {
static DEFAULT_DURATION: number = 300;
static outPos: Array<any>;
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
if (!Flew.outPos) {
Flew.outPos = [
{x: 0, y: -StageProxy.getHeight()},
{x: StageProxy.getWidth(), y: 0},
{x: 0, y: StageProxy.getHeight()},
{x: -StageProxy.getWidth(), y: 0}
];
}
parent.addChild(target);
Utils.notCenterPopUp(target);
let startPos: any = params.startPos || Flew.outPos[Utils.transDirection(params.direction)];
let endPos: any = params.endPos || Utils.getCenterPos(target);
target.x = startPos.x || endPos.x;
target.y = startPos.y || endPos.y;
let duration: number = (params && params.duration) || Flew.DEFAULT_DURATION;
let state: any = {x: endPos.x, y: endPos.y};
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(callback, thisObj);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 1}, duration);
}
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let defaultPos: any = Flew.outPos[Utils.transDirection(params.direction)];
let endPos: any = params.endPos || Utils.getCenterPos(target);
let duration: number = (params && params.duration) || Flew.DEFAULT_DURATION;
let state: any = {x: defaultPos.x || endPos.x, y: defaultPos.y || endPos.y};
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(function (): void {
parent.removeChild(target);
Utils.centerPopUp(target);
callback.call(thisObj);
}, this);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 0}, duration);
}
}
}
/***
* 缩放
* duration: 时间
* withFade: 是否伴随渐进渐出
*/
export class Scale implements IDialogEffect {
static DEFAULT_DURATION: number = 200;
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let duration: number = (params && params.duration) || Scale.DEFAULT_DURATION;
target.scaleX = target.scaleY = 0;
let state: any = {scaleX: 1, scaleY: 1};
parent.addChild(target);
Utils.centerPopUp(target);
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(callback, thisObj);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 1}, duration);
}
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let duration: number = (params && params.duration) || Scale.DEFAULT_DURATION;
target.scaleX = target.scaleY = 1;
let state: any = {scaleX: 0, scaleY: 0};
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(function (): void {
parent.removeChild(target);
target.scaleX = target.scaleY = 1;
callback.call(thisObj);
}, this);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 0}, duration);
}
}
}
/**
* Created by rockyl on 2018/9/12.
*/
import * as PopupEffect from './PopupEffect'
import * as PopUpManager from './PopUpManager'
export {
PopupEffect,
PopUpManager,
}
/**
* Created by lenovo on 2014/7/23.
*/
export class Dispatcher {
static eventDispatcher: egret.EventDispatcher;
static init(): void {
Dispatcher.eventDispatcher = new egret.EventDispatcher();
}
static dispatch(eventName: string, params: any = null): void {
if (params) {
Dispatcher.eventDispatcher.dispatchEventWith(eventName, false, params);
} else {
Dispatcher.eventDispatcher.dispatchEvent(new egret.Event(eventName));
}
}
static addEventListener(eventName: string, callback: Function, thisObj: any): void {
Dispatcher.eventDispatcher.addEventListener(eventName, callback, thisObj);
}
static removeEventListener(eventName: string, callback: Function, thisObj: any): void {
Dispatcher.eventDispatcher.removeEventListener(eventName, callback, thisObj);
}
}
/**
* Created by admin on 2017/6/23.
*/
import {eventManager} from "./";
export class EventComponent extends eui.Component {
private get eventGroupName() {
return this['__class__'] + '_' + this.hashCode;
}
registerEvent(target: any, eventName: any, callback: Function, thisObj: any, priority: number = 0): void {
eventManager.register(this.eventGroupName, target, eventName, callback, thisObj, priority);
}
enableEvents() {
eventManager.enable(this.eventGroupName);
}
disableEvents() {
eventManager.disable(this.eventGroupName);
}
}
export class VisualEventComponent extends EventComponent {
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedFromStage, this);
}
protected onAddedToStage(event: egret.Event): void {
this.enableEvents();
}
protected onRemovedFromStage(event: egret.Event): void {
this.disableEvents();
}
}
export class VisualEventItemRenderer extends eui.ItemRenderer {
private get eventGroupName() {
return this['__class__'] + '_' + this.hashCode;
}
registerEvent(target: any, eventName: any, callback: Function, thisObj: any, priority: number = 0): void {
eventManager.register(this.eventGroupName, target, eventName, callback, thisObj, priority);
}
enableEvents() {
eventManager.enable(this.eventGroupName);
}
disableEvents() {
eventManager.disable(this.eventGroupName);
}
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedFromStage, this);
}
protected onAddedToStage(event: egret.Event): void {
this.enableEvents();
}
protected onRemovedFromStage(event: egret.Event): void {
this.disableEvents();
}
}
/**
* Created by rockyl on 16/5/19.
*
* 事件管理器
*/
import {injectProp} from "../tools/Utils";
class EventManager {
private _groups: any = {};
register(groupName: string, target: any, eventName, callback: Function, thisObj: any, priority: number = 0): void {
if (!target) {
console.error('target is empty');
}
let item: RegisterItem = new RegisterItem();
injectProp(item, {target, eventName, callback, thisObj, priority}, null, false);
let group: any = this._groups[groupName];
if (!group) {
group = this._groups[groupName] = {enable: false, items: []};
}
group.items.push(item);
if (group.enable) { //如果组已生效,添加进去的就立马生效
this.addEventListener(item);
}
}
registerOn(obj: any, target: any, eventName, callback: Function, thisObj: any, priority: number = 0): void {
this.register(obj['__class__'], target, eventName, callback, thisObj, priority);
}
enable(groupName: string): void {
let group: any = this._groups[groupName];
if (!group) {
group = this._groups[groupName] = {enable: false, items: []};
}
if (!group.enable) {
group.enable = true;
group.items.forEach(this.addEventListener);
}
}
private addEventListener(item: RegisterItem) {
item.target['addEventListener'](item.eventName, item.callback, item.thisObj, false, item.priority);
}
enableOn(obj: any): void {
this.enable(obj['__class__']);
}
disable(groupName: string): void {
let group: any = this._groups[groupName];
if (group && group.enable) {
group.enable = false;
group.items.forEach(this.removeEventListener);
}
}
private removeEventListener(item: RegisterItem) {
item.target['removeEventListener'](item.eventName, item.callback, item.thisObj);
}
disableOn(obj: any): void {
this.disable(obj['__class__']);
}
dump(groupName: string = null): void {
for (let key in this._groups) {
let group: any = this._groups[key];
console.log(key + '[' + group.items.length + ']: ' + (group.enable ? '● enable' : '○ disable'));
console.log(group.items.map((item: RegisterItem) => {
return item.eventName;
}).join(','));
}
}
}
class RegisterItem {
target: any;
eventName: string;
callback: Function;
thisObj: any;
priority: number;
}
const eventManager:EventManager = new EventManager();
export default eventManager;
/**
* Created by Rocky.L on 2015/4/22.
*/
let _ID: string;
export function init(ID: string): void {
_ID = ID;
}
export function getName(key: string, prefix: string = null): string {
return (prefix || !_ID || _ID == '' ? prefix : _ID) + '_' + key;
}
export function getItem(key: string, prefix: string = null): string {
return egret.localStorage.getItem(getName(key, prefix));
}
export function setItem(key: string, value: string, prefix: string = null): boolean {
egret.localStorage.setItem(getName(key, prefix), value);
return true;
}
export function getItemObj(key: string, defaultObj: any = null, prefix: string = null): any {
let result: any;
try {
result = JSON.parse(getItem(key, prefix));
} catch (e) {
}
if (!result) {
result = defaultObj;
}
return result;
}
export function setItemObj(key: string, itemObj: any, prefix: string = null): boolean {
return setItem(key, JSON.stringify(itemObj), prefix);
}
/**
* Created by rockyl on 16/3/9.
*/
import {getTweenPromise} from "../tools/EgretUtils";
import {getItem, setItem} from "./LocalStorage";
let conflictPercent = 0.5;
let musicRes: string;
let musicChannel: egret.SoundChannel;
let musicPlaying: boolean;
let musicVolume: number;
export function setMusic(res: string) {
musicRes = res;
}
export function playMusic(res: string = null, {goon = false, volume = 1} = {}): void {
if (musicRes == res && !getMusicMute()) {
return;
}
let vol = goon ? musicVolume || 1 : volume;
if (!goon) {
musicRes = res;
}
if (getMusicMute()) {
return;
}
musicPlaying = true;
/*if (musicChannel) {
musicChannel.stop();
}*/
if (RES.getRes(musicRes)) {
_playMusic(RES.getRes(musicRes), vol);
} else {
RES.getResAsync(musicRes, (music: egret.Sound) => {
_playMusic(music, vol);
}, this);
}
}
async function _playMusic(music: egret.Sound, volume) {
musicVolume = volume;
if (music) {
if (musicChannel) {
await _channelFade(musicChannel, 0);
}
musicChannel = music.play();
musicChannel.volume = 0;
await _channelFade(musicChannel, volume, 2000);
}
}
async function _channelFade(channel: egret.SoundChannel, volume, duration = 500) {
if (duration == 0) {
if (volume == 0) {
egret.Tween.removeTweens(channel);
channel.stop();
}
} else {
await getTweenPromise(
egret.Tween
.get(channel, null, null, true)
.to({volume}, duration)
);
}
}
export function stopMusic(mute: boolean = false): void {
musicPlaying = false;
if (!mute) {
musicRes = null;
}
if (musicChannel) {
_channelFade(musicChannel, 0, 0);
musicChannel = null;
}
}
export function switchMusic(): void {
if (musicRes) {
if (getMusicMute()) {
stopMusic(true)
} else {
if (!musicPlaying) {
playMusic(null, {goon: true, volume: musicVolume});
}
}
}
}
export function getMusicMute(): boolean {
return false;
//return !dataCenterService.getSettingItem('music');
}
export function setMusicMute(value: boolean) {
//dataCenterService.setSettingItem('music', !value);
}
let effectRes: string;
let effectChannelMap: any = {};
export function playEffect(res: string = null, {loop = 1, conflict = false, force = false} = {}) {
if (res) {
effectRes = res;
}
if (!force && getEffectMute()) {
return Promise.resolve();
//return Promise.reject('effect mute');
}
let callback;
let p = new Promise((resolve => {
callback = resolve;
}));
if (RES.getRes(res)) {
_playEffect(res, RES.getRes(res), loop, conflict, callback);
} else {
RES.getResAsync(res, (music: egret.Sound) => {
_playEffect(res, music, loop, conflict, callback);
}, this);
}
return p;
}
function _playEffect(res, effect, loop, conflict, callback) {
if (effect) {
//console.log('playEffect', res);
effect.type = egret.Sound.EFFECT;
let effectChannel = effect.play(0, loop);
effectChannelMap[res] = effectChannel;
effectChannel.once(egret.Event.SOUND_COMPLETE, (event) => {
onEffectComplete({res, conflict});
callback();
}, this);
} else {
//reject('can\'t loaded ' + res);
callback();
}
}
export function stopEffect(res, {fade = false} = {}) {
let channel = effectChannelMap[res];
if (channel) {
if (fade) {
return new Promise(resolve => {
egret.Tween
.get(channel, null, null, true)
.to({volume: 0.1}, 300)
.call(() => {
_stopEffect(res);
resolve();
});
});
} else {
_stopEffect(res);
return Promise.resolve();
}
} else {
return Promise.resolve();
//return Promise.reject(`${res} is not on channel`)
}
}
function _stopEffect(res) {
let channel = effectChannelMap[res];
if (channel) {
channel.stop();
}
delete effectChannelMap[res];
}
function onEffectComplete({res, conflict}): void {
if (conflict && musicChannel && !getMusicMute()) {
egret.Tween
.get(musicChannel, null, null, true)
.to({volume: musicVolume}, 200);
//musicChannel.volume = 1;
}
delete effectChannelMap[res];
}
export function switchEffect(): void {
if (getEffectMute()) {
for (let res in effectChannelMap) {
let channel = effectChannelMap[res];
channel.stop();
}
}
}
export function getEffectMute(): boolean {
return false
//return !dataCenterService.getSettingItem('effect');
}
export function setEffectMute(value: boolean) {
//dataCenterService.setSettingItem('effect', !value);
}
export function getAllMute(): boolean {
return getMusicMute();
}
export function switchAll(): void {
switchEffect();
switchMusic();
}
/**
* 震动
*/
export function vibrate(): void {
if (getVibrateMute()) {
return;
}
//Native.instance.vibrate();
}
export function getVibrateMute(): boolean {
let mm: string = getItem('vibrateMute');
return mm ? mm == '1' : false;
}
export function setVibrateMute(value: boolean) {
setItem('vibrateMute', value ? '1' : '0');
}
export function switchVibrate(): void {
setVibrateMute(!getVibrateMute());
}
/**
* Created by rockyl on 16/3/9.
*/
let _stage: egret.Stage;
let _root: egret.DisplayObjectContainer;
let lastTouchPos: any = {};
let autoAdjustTargets: egret.DisplayObject[];
export function init(stage: egret.Stage, root: egret.DisplayObjectContainer): void {
_stage = stage;
_root = root;
stage.addEventListener(egret.TouchEvent.TOUCH_END, function (event: egret.TouchEvent): void {
lastTouchPos.x = event.stageX;
lastTouchPos.y = event.stageY;
}, this);
autoAdjustTargets = [];
stage.addEventListener(egret.Event.RESIZE, onStageResize, this);
}
function onStageResize(event: egret.Event = null): void {
const {width, height} = getSize();
//console.log(`resize stage: (${width}, ${height})`);
autoAdjustTargets.forEach((child: egret.DisplayObject) => {
child.width = width;
child.height = height;
});
}
export function getStage() {
return _stage;
}
export function getWidth(): number {
return _stage.stageWidth;
}
export function getHeight(): number {
return _stage.stageHeight;
}
export function getSize(): any {
return {
width: getWidth(),
height: getHeight(),
};
}
export function getCenter(): any {
const {width, height} = getSize();
return {
x: width / 2,
y: height / 2
}
}
export function registerAutoAdjust(target: egret.DisplayObject): void {
let index = autoAdjustTargets.indexOf(target);
if (index < 0) {
autoAdjustTargets.push(target);
}
onStageResize();
}
export function unregisterAutoAdjust(target: egret.DisplayObject): void {
let index = autoAdjustTargets.indexOf(target);
if (index >= 0) {
autoAdjustTargets.splice(index, 1);
}
}
/**
* Created by Rocky.L on 2015/5/21.
*
* Ticker管理类
*/
let _playing: boolean = false;
let _interval: number = 1;
let _intervalCount: number;
let _all: ITicker[] = [];
export function register(ticker: ITicker): void {
if (_all.indexOf(ticker) < 0) {
_all.push(ticker);
}
}
export function unregister(ticker: ITicker): void {
let index = _all.indexOf(ticker);
if (index >= 0) {
_all.splice(index, 1);
}
}
export function activate(): void {
_intervalCount = 0;
if (!_playing) {
_playing = true;
egret.startTick(onTicker, this);
}
}
export function sleep(): void {
if (_playing) {
_playing = false;
egret.stopTick(onTicker, this);
}
}
/**
* 时钟回调
*/
function onTicker(timeStamp: number): boolean {
_intervalCount++;
if (_intervalCount < _interval) {
return;
}
_intervalCount = 0;
_all.forEach(function (ticker: ITicker): void {
ticker.update();
});
}
/**
* 始终接口
*/
export interface ITicker {
update(): void;
}
/**
* Created by admin on 2017/6/14.
*/
import {disable, enable, register} from "../EventManager";
import {getStage} from "../StageProxy";
export class Gesture extends egret.EventDispatcher {
static ID_INK = 0;
protected _target: egret.DisplayObject;
protected _configuration: any;
protected _id;
protected _touchPoints = [];
protected _centerPoint;
protected _beginDistance;
constructor(target: egret.DisplayObject, configuration: any = {}) {
super();
this._target = target;
this._configuration = configuration;
this.setup();
}
protected setup() {
this._id = 'Gesture_' + (Gesture.ID_INK++);
register(this._id, this._target, egret.TouchEvent.TOUCH_BEGIN, this._onTouchBegin, this);
register(this._id, this._target, egret.TouchEvent.TOUCH_TAP, this._onTouchTap, this);
register(this._id, getStage(), egret.TouchEvent.TOUCH_MOVE, this._onTouchMove, this);
register(this._id, getStage(), egret.TouchEvent.TOUCH_END, this._onTouchEnd, this);
}
protected getTouchPoint(id) {
let result = null;
this._touchPoints.some(touchPoint => {
if (touchPoint.id == id) {
result = touchPoint;
return true;
}
});
return result;
}
protected addTouchPoint(event): any {
let touchPoint = {
id: event.touchPointID,
beginPoint: {
x: event.stageX,
y: event.stageY,
},
point: {
x: event.stageX,
y: event.stageY,
},
delta: {
x: 0,
y: 0,
time: 0,
},
lastTime: Date.now(),
};
this._touchPoints.push(touchPoint);
return touchPoint;
}
protected removeTouchPoint(id) {
this._touchPoints.some((touchPoint, index) => {
if (touchPoint.id == id) {
this._touchPoints.splice(index, 1);
return true;
}
});
}
private _onTouchBegin(event: egret.TouchEvent): void {
this.onTouchBegin(this.addTouchPoint(event), event);
}
protected onTouchBegin(touchPoint, event): void {
}
private _onTouchTap(event: egret.TouchEvent): void {
this.onTouchTap(this.getTouchPoint(event.touchPointID), event);
}
protected onTouchTap(touchPoint, event): void {
}
private _onTouchMove(event: egret.TouchEvent): void {
let touchPoint = this.getTouchPoint(event.touchPointID);
if (!touchPoint) {
return;
}
touchPoint.point.x = event.stageX;
touchPoint.point.y = event.stageY;
this.updateDelta(touchPoint, event);
this.onTouchMove(touchPoint, event);
}
protected onTouchMove(touchPoint, event): void {
}
private _onTouchEnd(event: egret.TouchEvent): void {
let touchPoint = this.getTouchPoint(event.touchPointID);
if (!touchPoint) {
return;
}
this.updateDelta(touchPoint, event);
this.onTouchEnd(touchPoint, event);
this.removeTouchPoint(event.touchPointID);
}
protected onTouchEnd(touchPoint, event) {
}
private updateDelta(touchPoint, event) {
touchPoint.delta.x = event.stageX - touchPoint.beginPoint.x;
touchPoint.delta.y = event.stageY - touchPoint.beginPoint.y;
touchPoint.delta.time = Date.now() - touchPoint.lastTime;
touchPoint.lastTime = Date.now();
}
get target(): egret.DisplayObject {
return this._target;
}
active() {
enable(this._id);
}
inactive() {
disable(this._id);
}
cancel() {
this._touchPoints.splice(0);
}
}
/**
* 滑动手势
*/
import {Gesture} from "./Gesture";
import {sign} from "../../tools/MathUtils";
export class SlideGesture extends Gesture {
static SLIDE: string = 'SLIDE';
private touchMoved;
private downTarget: egret.DisplayObject;
protected onTouchBegin(touchPoint, event): void {
this.downTarget = event.target;
}
protected onTouchMove(touchPoint, event): void {
if (!this._configuration.dispatchCancelEvent) {
return;
}
if (event.isDefaultPrevented()) {
return;
}
if (!this.touchMoved) {
this.touchMoved = true;
this.dispatchCancelEvent(event);
}
event.preventDefault();
}
protected onTouchEnd(touchPoint, event) {
this.touchMoved = false;
let {threshold = 300} = this._configuration;
let delta = Math.abs(touchPoint.delta.x);
if ((touchPoint.delta.time < 30 && delta > 50) || delta > threshold) {
let dir = sign(touchPoint.delta.x);
this.dispatchEventWith(SlideGesture.SLIDE, false, {dir});
}
}
private dispatchCancelEvent(event: egret.TouchEvent) {
let cancelEvent = egret.Event.create(egret.TouchEvent, egret.TouchEvent.TOUCH_CANCEL, event.bubbles, event.cancelable);
cancelEvent.$initTo(event.$stageX, event.$stageY, event.touchPointID);
let target: egret.DisplayObject = this.downTarget;
cancelEvent.$setTarget(target);
let list = this._target.$getPropagationList(target);
let length = list.length;
let targetIndex = list.length * 0.5;
let startIndex = -1;
for (let i = 0; i < length; i++) {
if (list[i] === this._target) {
startIndex = i;
break;
}
}
list.splice(0, startIndex + 1 - 2);
list.splice(list.length - 1 - startIndex + 2, startIndex + 1 - 2);
targetIndex -= startIndex + 1;
this._target.$dispatchPropagationEvent(cancelEvent, list, targetIndex);
egret.Event.release(cancelEvent);
}
}
/**
* Created by admin on 2017/8/2.
*/
import {Gesture} from "./Gesture";
import {centerPoint, distancePoint} from "../../tools/MathUtils";
export class ZoomGesture extends Gesture {
protected _beginScale = 1;
protected _scale = 1;
protected _container: egret.DisplayObject;
constructor(target: egret.DisplayObject, configuration: any = null) {
super(target, configuration);
this._container = configuration.container;
}
protected onTouchBegin(touchPoint): void {
if (this._touchPoints.length == 2) { //scale
this._beginDistance = distancePoint(this._touchPoints[0].point, this._touchPoints[1].point);
this.adjustAnchor();
}
}
protected onTouchMove(touchPoint): void {
let touchCount = this._touchPoints.length;
switch (touchCount) {
case 2: //scale
let distance = distancePoint(this._touchPoints[0].point, this._touchPoints[1].point);
this.adjustAnchor();
let offset = distance - this._beginDistance;
//this._target.scaleX = this._target.scaleY = distance / 750;
this._target.scaleX = this._target.scaleY = this._beginScale + offset * 0.001;
break;
}
}
protected onTouchEnd(touchPoint): void {
this._beginScale = this._target.scaleX;
}
private adjustAnchor() {
let target = this._target;
this._centerPoint = centerPoint(this._touchPoints[0].point, this._touchPoints[1].point);
let p = target.parent.globalToLocal(this._centerPoint.x, this._centerPoint.y);
target.x = target.anchorOffsetX = p.x * this._beginScale;
target.y = target.anchorOffsetY = p.y * this._beginScale;
console.log(this._centerPoint, p);
}
}
/**
* Created by rockyl on 2018/9/12.
*/
export {
}
\ No newline at end of file
/**
* Created by rockyl on 2018/9/12.
*/
import {Dispatcher} from './Dispatcher'
import eventManager from './EventManager'
import * as LocalStorage from './LocalStorage'
import * as SoundManager from './SoundManager'
import * as StageProxy from './StageProxy'
import * as TickerManager from './TickerManager'
import * as gesture from './gesture'
export {
Dispatcher,
eventManager,
LocalStorage,
SoundManager,
StageProxy,
TickerManager,
gesture,
}
\ No newline at end of file
/**
* Created by rockyl on 15/12/24.
*
* Ajax异步请求
*/
import {obj2query} from "./Utils";
export function callNet(url: string, params: any = null, method: string = egret.HttpMethod.GET, header: any = null, parseUrl: Function = null, parseBody: Function = null): Promise<string> {
return new Promise((resolve, reject) => {
let finalUrl: string = parseUrl ? parseUrl() : url;
let request: egret.HttpRequest = new egret.HttpRequest();
request.responseType = egret.HttpResponseType.TEXT;
request.addEventListener(egret.Event.COMPLETE, function (event: egret.Event): void {
resolve(request.response);
}, this);
request.addEventListener(egret.IOErrorEvent.IO_ERROR, function (event: egret.Event): void {
reject('request error.');
}, this);
request.open(finalUrl, method);
for (let k in header) {
request.setRequestHeader(k, header[k]);
}
let data: any = null;
if (parseBody) {
data = parseBody();
} else {
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
data = obj2query(params);
}
try {
if (data) {
request.send(data);
} else {
request.send();
}
} catch (e) {
reject(e);
}
});
}
export function GET(url: string, params: any = null, header: any = null): Promise<string> {
return this.callNet(url, params, egret.HttpMethod.GET, header, (): string => {
if (params) {
let data = obj2query(params);
url += (data.length > 0 && url.indexOf('?') < 0 ? '?' : '') + data;
}
return url;
}, () => null);
}
export function POST(url: string, params: any = null, header: any = null): Promise<string> {
return this.callNet(url, params, egret.HttpMethod.POST, header);
}
export function POSTDirectory(url: string, params: any = null, header: any = null): Promise<string> {
return this.callNet(url, params, egret.HttpMethod.POST, header, null, (): any => {
return params
});
}
/**
* Created by admin on 2017/3/17.
*/
import {valueToRgb} from "./ColorUtils";
let vertex = `
attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;
attribute vec2 aColor;
uniform vec2 projectionVector;
varying vec2 vTextureCoord;
varying vec4 vColor;
const vec2 center = vec2(-1.0, 1.0);
void main(void) {
gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);
vTextureCoord = aTextureCoord;
vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);
}`;
let fragment = `
precision lowp float;
varying vec2 vTextureCoord;
varying vec4 vColor;
uniform sampler2D uSampler;
uniform vec4 uReplace;
uniform float threshold;
void main(void) {
vec4 fg = texture2D(uSampler, vTextureCoord);
if(fg.a >= threshold){
fg = uReplace * fg.a;
}
gl_FragColor = fg * vColor;
}`;
export class ColorFilter extends egret.CustomFilter {
private _color = -1;
private _threshold = 1;
private _rgb: any = {};
constructor(color = NaN, threshold = 1) {
super(vertex, fragment, {uReplace: {}, threshold: threshold});
this.color = color;
this.threshold = threshold;
}
get color() {
return this._color
}
set color(value) {
if (value && this._color != value) {
this._color = value;
let rgb = valueToRgb(this._color).map(v => v / 255);
this._rgb.x = rgb[0];
this._rgb.y = rgb[1];
this._rgb.z = rgb[2];
this._rgb.w = 1;
this.uniforms.uReplace = this._rgb;
}
}
get threshold() {
return this._threshold
}
set threshold(value) {
if (this._threshold != value) {
this._threshold = value;
this.uniforms.threshold = this._threshold;
}
}
}
\ No newline at end of file
/**
* Created by rocky.l on 2017/1/22.
*/
export class ColorMatrix {
// ant for contrast calculations:
private static DELTA_INDEX: number[] = [
0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11,
0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24,
0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42,
0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68,
0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98,
1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54,
1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25,
2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8,
4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0,
7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8,
10.0
];
// identity matrix ant:
private static IDENTITY_MATRIX: number[] = [
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
];
private static LENGTH = ColorMatrix.IDENTITY_MATRIX.length;
private _source: number[];
// initialization:
constructor(p_matrix: number[] = null) {
this._source = [];
p_matrix = ColorMatrix.fixMatrix(p_matrix);
this.copyMatrix(((p_matrix.length == ColorMatrix.LENGTH) ? p_matrix : ColorMatrix.IDENTITY_MATRIX));
}
// public methods:
public reset(): void {
for (let i = 0; i < ColorMatrix.LENGTH; i++) {
this._source[i] = ColorMatrix.IDENTITY_MATRIX[i];
}
}
public adjustColor(p_brightness, p_contrast, p_saturation, p_hue): void {
this.adjustHue(p_hue);
this.adjustContrast(p_contrast);
this.adjustBrightness(p_brightness);
this.adjustSaturation(p_saturation);
}
public adjustBrightness(p_val): void {
p_val = ColorMatrix.cleanValue(p_val, 100);
if (p_val == 0 || isNaN(p_val)) {
return;
}
this.multiplyMatrix([
1, 0, 0, 0, p_val,
0, 1, 0, 0, p_val,
0, 0, 1, 0, p_val,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
public adjustContrast(p_val): void {
p_val = ColorMatrix.cleanValue(p_val, 100);
if (p_val == 0 || isNaN(p_val)) {
return;
}
let x;
if (p_val < 0) {
x = 127 + p_val / 100 * 127
}
else {
x = p_val % 1;
if (x == 0) {
x = ColorMatrix.DELTA_INDEX[p_val];
}
else {
//x = ColorMatrix.DELTA_INDEX[(p_val<<0)]; // this is how the IDE does it.
x = ColorMatrix.DELTA_INDEX[(p_val << 0)] * (1 - x) + ColorMatrix.DELTA_INDEX[(p_val << 0) + 1] * x; // use linear interpolation for more granularity.
}
x = x * 127 + 127;
}
this.multiplyMatrix([
x / 127, 0, 0, 0, 0.5 * (127 - x),
0, x / 127, 0, 0, 0.5 * (127 - x),
0, 0, x / 127, 0, 0.5 * (127 - x),
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
public adjustSaturation(p_val): void {
p_val = ColorMatrix.cleanValue(p_val, 100);
if (p_val == 0 || isNaN(p_val)) {
return;
}
let x = 1 + ((p_val > 0) ? 3 * p_val / 100 : p_val / 100);
let lumR = 0.3086;
let lumG = 0.6094;
let lumB = 0.0820;
this.multiplyMatrix([
lumR * (1 - x) + x, lumG * (1 - x), lumB * (1 - x), 0, 0,
lumR * (1 - x), lumG * (1 - x) + x, lumB * (1 - x), 0, 0,
lumR * (1 - x), lumG * (1 - x), lumB * (1 - x) + x, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
public adjustHue(p_val): void {
p_val = ColorMatrix.cleanValue(p_val, 180) / 180 * Math.PI;
if (p_val == 0 || isNaN(p_val)) {
return;
}
let cosVal = Math.cos(p_val);
let sinVal = Math.sin(p_val);
let lumR = 0.213;
let lumG = 0.715;
let lumB = 0.072;
this.multiplyMatrix([
lumR + cosVal * (1 - lumR) + sinVal * (-lumR), lumG + cosVal * (-lumG) + sinVal * (-lumG), lumB + cosVal * (-lumB) + sinVal * (1 - lumB), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (0.143), lumG + cosVal * (1 - lumG) + sinVal * (0.140), lumB + cosVal * (-lumB) + sinVal * (-0.283), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (-(1 - lumR)), lumG + cosVal * (-lumG) + sinVal * (lumG), lumB + cosVal * (1 - lumB) + sinVal * (lumB), 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
]);
}
public concat(p_matrix: number[]): number[] {
p_matrix = ColorMatrix.fixMatrix(p_matrix);
if (p_matrix.length != ColorMatrix.LENGTH) {
return;
}
this.multiplyMatrix(p_matrix);
return this._source;
}
public clone(): ColorMatrix {
return new ColorMatrix(this._source);
}
public toString(): string {
return "ColorMatrix [ " + this._source.join(" , ") + " ]";
}
// return a length 20 array (5x4):
public toArray(): number[] {
return this._source.slice(0, 20);
}
// private methods:
// copy the specified matrix's values to this matrix:
protected copyMatrix(p_matrix: number[]): void {
let l = ColorMatrix.LENGTH;
for (let i = 0; i < l; i++) {
this._source[i] = p_matrix[i];
}
}
// multiplies one matrix against another:
protected multiplyMatrix(p_matrix: number[]): void {
let col: number[] = [];
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
col[j] = this._source[j + i * 5];
}
for (let j = 0; j < 5; j++) {
let val = 0;
for (let k = 0; k < 5; k++) {
val += p_matrix[j + k * 5] * col[k];
}
this._source[j + i * 5] = val;
}
}
}
// make sure values are within the specified range, hue has a limit of 180, others are 100:
protected static cleanValue(p_val, p_limit) {
return Math.min(p_limit, Math.max(-p_limit, p_val));
}
// makes sure matrixes are 5x5 (25 long):
protected static fixMatrix(p_matrix: number[] = null): number[] {
let p_matrixp_matrix;
if (p_matrix == null) {
return ColorMatrix.IDENTITY_MATRIX;
}
if (p_matrix instanceof ColorMatrix
) {
p_matrixp_matrix = p_matrix.slice(0);
}
if (p_matrix.length < ColorMatrix.LENGTH) {
p_matrixp_matrix = p_matrix.slice(0, p_matrix.length).concat(ColorMatrix.IDENTITY_MATRIX.slice(p_matrix.length, ColorMatrix.LENGTH));
}
else if (p_matrix.length > ColorMatrix.LENGTH) {
p_matrixp_matrix = p_matrix.slice(0, ColorMatrix.LENGTH);
}
return p_matrix;
}
}
/**
* Created by rockyl on 2017/1/22.
*/
export function rgbToValue(r, g, b) {
return (r << 16) + (g << 8) + b;
}
export function valueToRgb(value) {
return [value >> 16, (value >> 8) % 256, value % 256];
}
export function hslToValue(h, s, l) {
return this.rgbToValue.apply(this, this.hslToRgb(h, s, l));
}
export function valueToHsl(value) {
return this.rgbToHsl.apply(this, this.valueToRgb(value));
}
export function hue2rgb(v1, v2, vh) {
if (vh < 0) vh += 1;
if (vh > 1) vh -= 1;
if (vh < 1 / 6) return v1 + (v2 - v1) * 6 * vh;
if (vh < 1 / 2) return v2;
if (vh < 2 / 3) return v1 + (v2 - v1) * (2 / 3 - vh) * 6;
return v1;
}
export function hslToRgb(h, s, l) {
let r, g, b, v1, v2;
h = h / 240;
s = s / 240;
l = l / 240;
if (s == 0) {
r = g = b = l;
} else {
if (l < 0.5) {
v2 = l * (s + 1);
} else {
v2 = (l + s) - (l * s);
}
v1 = 2 * l - v2;
r = this.hue2rgb(v1, v2, h + 1 / 3);
g = this.hue2rgb(v1, v2, h);
b = this.hue2rgb(v1, v2, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
export function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0; // achromatic
} else {
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, l];
}
/**
* Created by rockyl on 2018/8/6.
*/
export class CountingTime {
from;
to;
sign;
autoStart;
interval;
renderer;
onComplete;
timer;
counting;
constructor(from, to, options = null) {
this.from = from;
this.to = to;
this.sign = to - from > 0 ? 1 : -1;
this.autoStart = options ? options.autoStart || true : true;
this.interval = options ? options.interval || 1000 : 1000;
this.renderer = options ? options.renderer : null;
this.onComplete = options ? options.onComplete : null;
}
start(override = true, goon = false) {
if (!goon && override && this.timer) {
this.stop();
}
if (this.timer) {
return;
}
if (!goon) {
this.counting = this.from;
}
this.onTimer(true);
this.timer = setInterval(this.onTimer, this.interval);
}
stop(callOnComplete = false) {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
if (callOnComplete) {
this.onComplete && this.onComplete();
}
}
onTimer = (pure = false) => {
if (!pure) {
this.counting += this.sign;
}
let {counting, to} = this;
if (counting == to) {
this.stop(true);
return;
}
this.renderer && this.renderer(counting);
}
}
/**
* Created by rockyl on 2017/1/22.
*/
export function getTweenPromise(tween: egret.Tween): Promise<any> {
return new Promise((resolve) => {
tween.call(resolve);
});
}
export function waitPromise(duration): Promise<any> {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
export function callLater(callback, count = 1) {
count--;
egret.callLater(() => {
if (count > 0) {
this.callLater(callback, count);
} else {
callback();
}
}, this);
}
export class Bezier {
private _onUpdate;
private _posArr;
constructor(onUpdate) {
this._onUpdate = onUpdate;
}
init(posArr) {
this._posArr = posArr;
this.factor = 0;
}
public get factor(): number {
return 0;
}
public set factor(value: number) {
let p = this._posArr;
let x = (1 - value) * (1 - value) * p[0].x + 2 * value * (1 - value) * p[1].x + value * value * p[2].x;
let y = (1 - value) * (1 - value) * p[0].y + 2 * value * (1 - value) * p[1].y + value * value * p[2].y;
this._onUpdate({x, y});
}
}
export function enumChildren(container: egret.DisplayObjectContainer, callback: Function): void {
for (let i = 0, li = container.numChildren; i < li; i++) {
if (callback(container.getChildAt(i), i)) {
break;
}
}
}
export function removeChildren(container: egret.DisplayObjectContainer, callback: Function): void {
let i = 0;
while (container.numChildren > 0) {
callback(container.removeChildAt(0), i);
i++;
}
}
export function getDisplayPath(target) {
let arr = [];
let temp = target;
do {
arr.unshift(temp.parent.getChildIndex(temp));
} while ((temp = temp.parent) && temp.parent);
return arr;
}
export function getTargetByPath(root, link) {
let target: any = root;
for (let i = 0, li = link.length; i < li; i++) {
try {
target = target.getChildAt(link[i]);
} catch (e) {
return null;
}
}
return target;
}
/**
* Created by rockyl on 16/3/9.
*/
export class HashMap {
private _length: number;
private obj: any;
constructor() {
this.clear();
}
containsKey(key: any): boolean {
return key in this.obj;
}
containsValue(value: any): boolean {
for (let key in this.obj) {
if (this.obj[key] == value) {
return true;
}
}
return false;
}
put(key: any, value: any): void {
if (!this.containsKey(key)) {
this.obj[key] = value;
this._length++;
}
}
get(key: any): any {
return this.containsKey(key) ? this.obj[key] : null;
}
remove(key: any): any {
if (this.containsKey(key)) {
let value = this.obj;
delete this.obj[key];
this._length--;
return value;
}
return null;
}
foreach(callback: Function, thisOjb: any): void {
for (let key in this.obj) {
if (!callback.call(thisOjb, key, this.obj[key])) {
break;
}
}
}
randomGet(): any {
let values = this.valueSet;
return values[Math.floor(Math.random() * values.length)];
}
get keySet(): any {
let keys = [];
for (let key in this.obj) {
keys.push(key);
}
return keys;
}
get valueSet(): any {
let values = [];
for (let key in this.obj) {
values.push(this.obj[key]);
}
return values;
}
get size(): number {
return this._length;
}
clear(): void {
this._length = 0;
this.obj = {};
}
}
/**
* Created by rockyl on 16/3/9.
*/
/**
* 计算距离
* @param p1
* @param p2
* @returns {number}
*/
export function distancePoint(p1: any, p2: any): number {
return this.distance(p1.x, p1.y, p2.x, p2.y);
}
/**
* 计算距离
* @param x1
* @param y1
* @param x2
* @param y2
* @returns {number}
*/
export function distance(x1: number, y1: number, x2: number, y2: number): number {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
export function centerPoint(p1: any, p2: any) {
return {
x: Math.min(p1.x, p2.x) + Math.abs(p1.x - p2.x) / 2,
y: Math.min(p1.y, p2.y) + Math.abs(p1.y - p2.y) / 2,
}
}
/**
* 计算两点直线的弧度
* @param p1
* @param p2
* @returns {number}
*/
export function radian(p1: any, p2: any): number {
return Math.atan2(p2.y - p1.y, p2.x - p1.x);
}
/**
* 计算两点直线的角度
* @param p1
* @param p2
* @returns {number}
*/
export function angle(p1: any, p2: any): number {
return this.radiusToAngle(this.radian(p1, p2));
}
/**
* 获取一个随机整数
* @param max
* @param min
* @returns {number}
*/
export function makeRandomInt(max: number, min: number = 0): number {
return Math.floor(Math.random() * (max - min)) + min;
}
/**
* 获取一个随机浮点数
* @param max
* @param min
* @returns {number}
*/
export function makeRandomFloat(max: number, min: number = 0): number {
return Math.random() * (max - min) + min;
}
/**
* 生成一个基于value的range偏移的随机数
* @param value
* @param range
* @returns {number}
*/
export function makeRandomByRange(value: number, range: number): number {
return value + (Math.random() * range * 2 - range);
}
/**
* 生成一个随机整数数组
* @param len
* @param max
* @param min
* @returns {string}
*/
export function makeRandomIntArr(len: number, max: number, min: number = 0): number[] {
let target: number[] = [];
for (let i: number = 0; i < len; i++) {
target.push(this.makeRandomInt(max));
}
return target;
}
/**
* 生成一个范围数组
* @param to
* @param from
* @param step
* @returns {Array<number>}
*/
export function makeOrderIntArray(to: number, from: number = 0, step: number = 1): Array<number> {
let result: Array<number> = [];
for (let i: number = from; i <= to; i += step) {
result.push(i);
}
return result;
}
/**
* 打乱一个数组
* @param arr
* @returns {any}
*/
export function mixArray(arr: any): Array<any> {
for (let i: number = 0, len: number = Math.round(arr.length / 2); i < len; i++) {
let a: number = this.makeRandomInt(arr.length);
let b: number = this.makeRandomInt(arr.length);
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
return arr;
}
/**
* 打乱一个二维数组
* @param arr
* @returns {Array<Array<any>>}
*/
export function mixArray2(arr: Array<Array<any>>): Array<Array<any>> {
let cH: number = arr[0].length;
let cV: number = arr.length;
let pos0: number[];
let pos1: number[];
for (let i: number = 0, len: number = Math.round(cH * cV / 2); i < len; i++) {
pos0 = [this.makeRandomInt(cH), this.makeRandomInt(cV)];
pos1 = [this.makeRandomInt(cH), this.makeRandomInt(cV)];
let temp = arr[pos0[0]][pos0[1]];
arr[pos0[0]][pos0[1]] = arr[pos1[0]][pos1[1]];
arr[pos1[0]][pos1[1]] = temp;
}
return arr;
}
/**
* 随机从一个数组中取出一项
* @param arr
* @param del
* @returns {*}
*/
export function getRandomFromArray(arr: any, del = false): any {
let index = this.makeRandomInt(arr.length);
let item = arr[index];
if (del) {
arr.splice(index, 1);
}
return item;
}
/**
* 根据范围阻隔
* @param value
* @param lower
* @param upper
* @returns {number}
*/
export function fixRange(value: number, lower: number, upper: number): number {
if (value < lower) {
value = lower;
} else if (value > upper) {
value = upper;
}
return value;
}
/**
* 根据范围补足
* @param value
* @param max
* @param min
* @returns {number}
*/
export function roundFix(value: number, max: number, min: number = 0): number {
if (value < min) {
value += max - min;
} else if (value >= max) {
value -= max - min;
}
return value;
}
/**
* 弧度转角度
* @param radius
* @returns {number}
*/
export function radiusToAngle(radius: number): number {
return radius * 180 / Math.PI;
}
/**
* 角度转弧度
* @param angle
* @returns {number}
*/
export function angleToRadius(angle: number): number {
return angle * Math.PI / 180;
}
/**
* 数组向右旋转
* @param arr
* @returns {Array}
*/
export function turnRight(arr) {
let temp = [];
for (let t = 0, tl = arr.length; t < tl; t++) {
temp.push([]);
}
for (let i = 0, il = arr.length; i < il; i++) {
for (let j = 0, jl = arr[i].length; j < jl; j++) {
temp[i][j] = arr[jl - j - 1][i];
}
}
return temp;
}
/**
* 数组向左旋转
* @param arr
* @returns {Array}
*/
export function turnLeft(arr) {
let temp = [];
for (let t = 0, tl = arr.length; t < tl; t++) {
temp.push([]);
}
for (let i = 0, il = arr.length; i < il; i++) {
for (let j = 0, jl = arr[i].length; j < jl; j++) {
temp[i][j] = arr[j][jl - i - 1];
}
}
return temp;
}
/**
* 根据两点计算量化方向,用于手势识别
* @param x0
* @param y0
* @param x1
* @param y1
* @returns {number}
*/
export function calDir(x0: number, y0: number, x1: number, y1: number): number {
if (x0 == x1 && y0 == y1) {
return -1;
}
let r: number = Math.atan2(y1 - y0, x1 - x0);
let d: number;
if (Math.abs(r) < Math.PI / 4) {
d = 0;
} else if (Math.abs(r) > Math.PI / 4 * 3) {
d = 2;
} else if (r > 0) {
d = 1;
} else {
d = 3;
}
return d;
}
/**
* 数值正负计算
* @param num
* @returns {number}
*/
export function sign(num: number): number {
return num == 0 ? 0 : (num > 0 ? 1 : -1);
}
/**
* 把一个正整数分割成若干个整数
* @param total
* @param count
* @returns {Array}
*/
export function split(total, count) {
let result = [];
for (let i = 0; i < count; i++) {
result[i] = 0;
}
for (let i = 0; i < total; i++) {
result[this.makeRandomInt(count)]++;
}
return result;
}
/**
* 贝塞尔曲线
* @param points
* @param t
*/
export function getBezier(points, t) {
let result = {x: 0, y: 0}, temp, n = points.length - 1;
for (let i = 0; i <= n; i++) {
temp = Math.pow(1 - t, n - i) * Math.pow(t, i) * (i == 0 || i == n ? 1 : n);
result.x += points[i].x * temp;
result.y += points[i].y * temp;
}
return result;
}
export function pointInPolygon(points: any[], point: any) {
let polySides = points.length, i, j = polySides - 1;
let oddNodes = false;
let x = point.x, y = point.y;
for (i = 0; i < polySides; i++) {
let ix = points[i].x;
let iy = points[i].y;
let jx = points[j].x;
let jy = points[j].y;
if ((iy < y && jy >= y
|| jy < y && iy >= y)
&& (ix <= x || jx <= x)) {
if (ix + (y - iy) / (jy - iy) * (jx - ix) < x) {
oddNodes = !oddNodes;
}
}
j = i;
}
return oddNodes;
}
export function intersectToPolygon(points: any[], intersect: any[]) {
let aa = intersect[0];
let bb = intersect[1];
let cc, dd;
let result = false;
for (let i = 0, li = points.length; i < li; i++) {
cc = points[i];
if (i == li - 1) {
dd = points[0];
} else {
dd = points[i + 1];
}
if (this.intersectToIntersect(aa, bb, cc, dd)) {
result = true;
break;
}
}
return result;
}
export function intersectToIntersect(aa, bb, cc, dd) {
let delta = determinant(bb.x - aa.x, cc.x - dd.x, bb.y - aa.y, cc.y - dd.y);
if (delta <= (1e-6) && delta >= -(1e-6)) {
return false;
}
let namenda = determinant(cc.x - aa.x, cc.x - dd.x, cc.y - aa.y, cc.y - dd.y) / delta;
if (namenda > 1 || namenda < 0) {
return false;
}
let miu = determinant(bb.x - aa.x, cc.x - aa.x, bb.y - aa.y, cc.y - aa.y) / delta;
if (miu > 1 || miu < 0) {
return false;
}
return true;
function determinant(v1, v2, v3, v4) {
return (v1 * v3 - v2 * v4);
}
}
export function segmentsIntr(a, b, c, d) {
let area_abc = (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x);
let area_abd = (a.x - d.x) * (b.y - d.y) - (a.y - d.y) * (b.x - d.x);
if (area_abc * area_abd >= 0) {
return false;
}
let area_cda = (c.x - a.x) * (d.y - a.y) - (c.y - a.y) * (d.x - a.x);
let area_cdb = area_cda + area_abc - area_abd;
if (area_cda * area_cdb >= 0) {
return false;
}
let t = area_cda / (area_abd - area_abc);
let dx = t * (b.x - a.x),
dy = t * (b.y - a.y);
return {x: a.x + dx, y: a.y + dy};
}
export function isNullArray(arr) {
let result = true;
arr.some(item => {
if (item !== undefined && item !== null) {
result = false;
return true;
}
});
return result;
}
export function valueRange(value, min, max) {
return Math.min(Math.max(value, min), max);
}
export function lineHitTest(l0, l1) {
return l0.a < l1.b && l0.b > l1.a;
}
/**
* Created by rockyl on 16/3/9.
*/
const MAX: number = 20;
const createMethods: any = {};
const initMethods: any = {};
const pools: any = {};
export function registerPool(name: string, createMethod: Function, initMethod: Function = null): void {
createMethods[name] = createMethod;
initMethods[name] = initMethod;
pools[name] = [];
}
export function getObject(name: string, ...params): any {
let pool = pools[name];
if (!pool) {
console.warn(name + "没有注册在对象池中。");
return null;
}
let obj: any;
if (pool.length > 0) {
obj = pool.pop();
} else {
let createMethod = createMethods[name];
obj = createMethod.apply(null, params);
}
let initMethod = initMethods[name];
if (initMethod) {
params.unshift(obj);
initMethod.apply(null, params);
}
debug();
return obj;
}
export function recycleObject(name: string, obj: any): void {
if (!obj) {
return;
}
let pool = pools[name];
if (!pool) {
console.warn(name + "没有注册在对象池中。");
return;
}
if (pool.indexOf(obj) < 0 && pool.length <= MAX) {
pool.push(obj);
}
debug();
}
export function debug(): void {
let text = "";
for (let key in pools) {
let pool = pools[key];
text += key + ":" + pool.length + "\n";
}
//DebugWindow.instance.text = text;
}
/**
* Created by admin on 2017/8/23.
*/
export function validateName(str) {
return !!str.match(/^[\u4e00-\u9fa5]{2,4}$/);
}
export function has2BChar(str) {
return str.match(/[^\x00-\xff]/);
}
export function validateIdCard(str) {
let result = false;
//15位和18位身份证号码的正则表达式
let reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
//如果通过该验证,说明身份证格式正确,但准确性还需计算
if (reg.test(str)) {
if (str.length == 18) {
let strWi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //将前17位加权因子保存在数组里
let strY = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; //这是除以11后,可能产生的11位余数、验证码,也保存成数组
let strWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
for (let i = 0; i < 17; i++) {
strWiSum += str.substring(i, i + 1) * strWi[i];
}
let strMod = strWiSum % 11;//计算出校验码所在数组的位置
let strLast = str.substring(17);//得到最后一位身份证号码
//如果等于2,则说明校验码是10,身份证号码最后一位应该是X
if (strMod == 2) {
result = strLast == "X" || strLast == "x";
} else {
//用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码
result = strLast == strY[strMod];
}
}
}
return result;
}
export function filterEmoji(str) {
return str.replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g, '');
}
/**
* Created by rockyl on 2017/1/22.
*/
export function checkNeedLoad(resGroupNames: string[]): boolean {
let needLoad = false;
for (let i = 0, li = resGroupNames.length; i < li; i++) {
if (!RES.isGroupLoaded(resGroupNames[i])) {
needLoad = true;
break;
}
}
return needLoad;
}
export async function loadResGroups(resGroupNames: string[], progressCallback: Function = null): Promise<any> {
let loaded = 0;
const resLoadReporter = new ResLoadReporter(function (current, total) {
progressCallback && progressCallback(++loaded, total);
});
const total = resGroupNames.reduce((p, c) => {
return p + (RES.isGroupLoaded(c) ? 0 : RES.getGroupByName(c).length);
}, 0);
for (let i = 0, li = resGroupNames.length; i < li; i++) {
if (!RES.isGroupLoaded(resGroupNames[i])) {
await RES.loadGroup(resGroupNames[i], 0, resLoadReporter);
}
}
}
class ResLoadReporter implements RES.PromiseTaskReporter {
progressCallback;
constructor(progressCallback) {
this.progressCallback = progressCallback;
}
onProgress(current: number, total: number) {
this.progressCallback(current, total)
}
}
/**
* Created by rockyl on 16/3/9.
*/
import {makeRandomInt} from "./MathUtils";
const chars: string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
export function makeRandomString(len: number): string {
let s: string = "";
let cl: number = this.chars.length;
for (let i: number = 0; i < len; i++) {
s += this.chars.charAt(makeRandomInt(cl));
}
return s;
}
export function makeRandomIntString(len: number): string {
let s: string = "";
for (let i: number = 0; i < len; i++) {
s += makeRandomInt(10);
}
return s;
}
export function stringCut(str: string, len: number, fill: string = '...'): string {
let result: string = str;
if (str.length > len) {
result = str.substr(0, len) + fill;
}
return result;
}
export function fixed(num, count) {
let p = Math.pow(10, count);
let result = ((Math.floor(num) * p + Math.floor(num * p % p) / p * p) / p).toString();
let dotIndex = result.indexOf('.');
return result + (dotIndex < 0 ? '.00' : repeat('0', count - (result.length - dotIndex - 1)));
}
const zeros: Array<string> = [
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
"00000000",
"000000000",
"0000000000"
];
export function supplement(value: number, count: number): string {
let index = count - value.toString().length - 1;
if (index < 0) {
return value.toString();
}
return this.zeros[index] + value;
}
export function format(formatStr: string, ...params): string {
return this.formatApply(formatStr, params);
}
export function formatApply(formatStr: string, params: any[]): string {
let result: string = formatStr;
for (let i = 0, len = params.length; i < len; i++) {
let reg = new RegExp("\\{" + i + "\\}", 'g');
result = result.replace(reg, params[i]);
}
return result;
}
/**
*
* @param string
* @param cutSize
* @returns {Array}
*/
export function splitBySize(string, cutSize) {
let result = [];
for (let i = 0, li = Math.ceil(string.length / cutSize); i < li; i++) {
result.push(string.substr(i * cutSize, cutSize));
}
return result;
}
export function repeat(string, count) {
let result = '';
for (let i = 0; i < count; i++) {
result += string;
}
return result;
}
export function trim(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
}
export function join(arr, str, lineLimit = 0) {
if (arr && arr.length > 0) {
if (lineLimit > 0) {
let result = '';
for (let i = 0, li = arr.length; i < li; i++) {
result += arr[i] + (i < li - 1 ? ((i + 1) % lineLimit == 0 ? '\n' : str) : '');
}
return result;
} else {
return arr.join(str);
}
} else {
return null;
}
}
/**
* Created by admin on 2017/5/27.
*/
export class TimeCountDown {
timer = null;
onRender: Function;
onComplete: Function;
private time;
private type;
constructor(onRender, onComplete = null) {
this.onRender = onRender;
this.onComplete = onComplete;
}
startWithSecond(second) {
this.time = second;
this.type = 0;
this.start(1000);
}
startWithMillisecond(millisecond) {
this.time = millisecond;
this.type = 1;
this.start(1000 / 60);
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
private start(interval) {
this.stop();
this.timer = setInterval(() => {
this.time--;
if (this.onRender) {
this.onRender(this.time);
}
if (this.time <= 0) {
this.stop();
if (this.onComplete) {
this.onComplete();
}
}
}, this, interval);
}
}
/**
* Created by rockyl on 16/3/9.
*/
import {format, supplement} from "./StringUtils";
export function repeat(handler: any, timeout: any, repeat: number = -1, onComplete: Function = null, immediately: boolean = false, ...args: any[]) {
let c: number = 0;
if (immediately) {
c++;
handler.apply(null, args);
}
let timer = setInterval(() => {
if (repeat > 0 && c >= repeat) {
clearInterval(timer);
if (onComplete) {
onComplete();
}
return;
}
handler.apply(null, args);
c++;
}, this, timeout);
return timer;
}
const timeLang = ['sky', 'hour', 'minutes', 'second'];
export function timeFormat(second: number, formatStr: string = '{1}:{0}', placeZero: boolean = true, hideEmpty: boolean = false): string {
let ss: any = second % 60;
let mm: any = Math.floor(second / 60) % 60;
let hh: any = Math.floor(second / 3600) % 24;
let dd: any = Math.floor(second / 3600 / 24);
if (placeZero) {
ss = supplement(ss, 2);
mm = supplement(mm, 2);
hh = supplement(hh, 2);
dd = supplement(dd, 2);
}
if (hideEmpty) {
let result = '';
[dd, hh, mm, ss].forEach((item, index) => {
if (item > 0) {
//result += item + lang[this.timeLang[index]];
}
});
return result;
} else {
return format(formatStr, ss, mm, hh, dd);
}
}
export function parseFromString(str: string): Date {
return new Date(str.replace('T', ' ').replace(/-/g, '/'));
}
export function parseFromStringScope(str: string[]): Date[] {
return str.map((item) => this.parseFromString(item));
}
export function dateTimeToString(date: Date): string {
return this.dateToString(date, '{0}年{1}月{2}日') + ' ' + this.dateToTimeString(date, '{2}:{1}');
}
export function tsToDate(ts: number): Date {
let newDate: Date = new Date();
newDate.setTime(ts * 1000);
return newDate;
}
export function parseTime(str: string): number {
let t: string[] = str.split(':');
return parseInt(t[0]) * 3600 + parseInt(t[1]) * 60 + parseInt(t[2]);
}
export function tsToDateString(ts: number, format: string = '{0}/{1}/{2}'): string {
return this.dateToString(this.tsToDate(ts), format);
}
export function dateToString(date: Date, formatStr: string = '{0}/{1}/{2}'): string {
return format(formatStr, date.getFullYear(), supplement(date.getMonth() + 1, 2), supplement(date.getDate(), 2))
}
export function dateToTimeString(date: Date, formatStr: string = '{2}:{1}:{0}'): string {
return format(formatStr, supplement(date.getSeconds(), 2), supplement(date.getMinutes(), 2), supplement(date.getHours(), 2))
}
export function dateToTs(date: Date): number {
return Math.floor(date.valueOf() / 1000);
}
export function dateCut(date: Date): Date {
let h = date.getHours();
let m = date.getMinutes();
let s = date.getSeconds();
return this.tsToDate(this.dateToTs(date) - h * 3600 - m * 60 - s);
}
export function tsToMonthDayString(ts: number): string {
let date: Date = this.tsToDate(ts);
return format('{0}' + '月' + '{1}' + '日', supplement(date.getMonth() + 1, 2), supplement(date.getDate(), 2))
}
export function scopeToDateString(scope: Date[], format: string): string {
return this.dateToString(scope[0], format) + '-' +
this.dateToString(scope[1], format);
}
export function scopeToTimeString(scope: Date[], format: string): string {
let ts1 = this.dateToTimeString(scope[0], format);
let ts2 = this.dateToTimeString(scope[1], format);
return ts1 + '-' + ts2;
}
export function scopeToDateTimeString(scope: Date[], dateFormat: string, timeFormat: string, combine: boolean = false): string {
let t1 = scope[0];
let t2 = scope[1];
if (combine && t1.getDate() == t2.getDate()) {
return this.dateToString(t1, dateFormat) + ' ' +
this.dateToTimeString(t1, timeFormat) + '-' +
this.dateToTimeString(t2, timeFormat);
} else {
return this.dateTimeToString(t1) + ' - ' + this.dateTimeToString(t2);
}
}
export function remainDays(time1: any, time2: any, include = false): number {
let t1, t2;
if (time1 instanceof Date) {
t1 = this.dateToTs(time1);
} else if (typeof time1 == 'string') {
t1 = this.parseFromString(time1)
}
if (time2 instanceof Date) {
t2 = this.dateToTs(time2);
} else if (typeof time2 == 'string') {
t2 = this.parseFromString(time2)
}
return (t1 - t2 + (include ? 1 : 0)) / 24 / 3600;
}
export function compareScope(scope, time): number {
let t1 = this.dateToTs(scope[0]);
let t2 = this.dateToTs(scope[1]);
if (time < t1) {
return time - t1;
} else if (time >= t1 && time <= t2) {
return 0;
} else {
return time - t2;
}
}
export function getWeekIndex(ts: number) {
let dateObj = this.tsToDate(ts);
let firstDay = this.getFirstWeekBegDay(dateObj.getFullYear());
if (dateObj < firstDay) {
firstDay = this.getFirstWeekBegDay(dateObj.getFullYear() - 1);
}
let d = Math.floor((dateObj.valueOf() - firstDay.valueOf()) / 86400000);
return Math.floor(d / 7) + 1;
}
export function getFirstWeekBegDay(year) {
let tempdate = new Date(year, 0, 1);
let temp = tempdate.getDay();
if (temp == 1)
return tempdate;
temp = temp == 0 ? 7 : temp;
let t = tempdate.setDate(tempdate.getDate() + (8 - temp));
return new Date(t);
}
/**
* Created by rockyl on 16/3/9.
*/
export function injectProp(target: Object, data: Object = null, callback: Function = null, ignoreMethod: boolean = true, ignoreNull: boolean = true): boolean {
if (!target || !data) {
return false;
}
let result = true;
for (let key in data) {
let value: any = data[key];
if ((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null)) {
if (callback) {
callback(target, key, value);
} else {
target[key] = value;
}
}
}
return result;
}
export function getDirtyData(oldData: any, newData: any): any {
let dirtyData: any;
for (let key in newData) {
if (oldData[key] != newData[key]) {
if (!dirtyData) {
dirtyData = {};
}
dirtyData[key] = newData[key];
}
}
return dirtyData;
}
export function combineProp(...sources): any {
let ret: any = {};
sources.forEach((source: any) => {
if (!source) {
return;
}
for (let key in source) {
if (source[key] !== null && source[key] !== undefined && source[key] !== '') {
ret[key] = source[key];
}
}
});
return ret;
}
export function clone(source: any, def: any = null, ignoreMethod: boolean = true): any {
let target: any = def ? new def() : {};
this.injectProp(target, source, null, ignoreMethod);
return target;
}
export function arrToIntArr(arr: any[]): number[] {
for (let i: number = 0, li: number = arr.length; i < li; i++) {
arr[i] = parseInt(arr[i]);
}
return arr;
}
export function getUrlParams(): any {
let params: any = {};
let href: string = window.location.href;
let index: number = href.indexOf("?");
if (index < 0) {
return params;
}
params = this.parseQuery(href.substr(index + 1));
return params;
}
export function parseQuery(query) {
let params: any = {};
let hashes = query.split('&');
for (let i = 0; i < hashes.length; i++) {
let arr: Array<string> = hashes[i].split('=');
params[arr[0]] = arr[1];
}
return params;
}
export function getUrlBase(): string {
let href: string = window.location.href;
let index: number = href.indexOf("?");
return href.substring(0, index < 0 ? href.length : index);
}
export function anchorCenter(target: any, width: number = 0, height: number = 0, resetPos = true): void {
anchorRate(target, 0.5, 0.5, width, height, resetPos);
}
export function anchorRate(target: any, rx: number, ry: number, width: number = 0, height: number = 0, resetPos = true): void {
if (width == 0) {
width = target.width;
}
if (height == 0) {
height = target.height;
}
if (resetPos) {
if (rx == 0) {
target.x -= target.anchorOffsetX;
}
if (ry == 0) {
target.y -= target.anchorOffsetY;
}
}
target.anchorOffsetX = width * rx;
target.anchorOffsetY = height * ry;
if (resetPos) {
if (rx > 0) {
target.x += target.anchorOffsetX;
}
if (ry > 0) {
target.y += target.anchorOffsetY;
}
}
}
/**
* object转成查询字符串
* @param obj
* @returns {string}
*/
export function obj2query(obj: any): string {
if (!obj) {
return '';
}
let arr: string[] = [];
for (let key in obj) {
arr.push(key + '=' + obj[key]);
}
return arr.join('&');
}
export function parseColorTextFlow(source: string): any[] {
let statics: string[] = source.split(/\[.*?\]/g);
let dynamics: string[] = source.match(/\[.*?\]/g);
let ret: any[] = [];
let s;
let i = 0;
let li = statics.length - 1;
for (; i < li; i++) {
s = statics[i];
if (s) {
ret.push({text: s});
}
let cs: string = dynamics[i];
cs = cs.substr(1, cs.length - 2);
let obj: any = {};
let arr = cs.split('|');
if (arr.length == 1) {
obj.style = {textColor: parseInt(arr[0], 16)};
} else {
obj.text = arr[0];
obj.style = {textColor: parseInt(arr[1], 16)};
}
ret.push(obj);
}
s = statics[i];
if (s) {
ret.push({text: s});
}
return ret;
}
export function scrollTo(index, itemSize, gap = 0) {
return (itemSize + gap) * index;
}
export function getByteLen(str) {
return str.replace(/[^\x00-\xff]/g, '__').length;
}
export function findArr(array, func) {
let result = null;
array.some((item) => {
if (func(item)) {
result = item;
return true;
}
});
return result;
}
export function objectValues(obj) {
let arr = [];
for (let key in obj) {
arr.push(obj[key]);
}
return arr;
}
export function getFileName(fullName) {
return fullName.substr(0, fullName.indexOf('.'));
}
/**
* Created by NGames on 2015/3/24.
*/
export class Vector2D {
x: number;
y: number;
constructor(x: number = 0, y: number = 0) {
this.setXY(x, y);
}
setXY(x: number = 0, y: number = 0): void {
this.x = x;
this.y = y;
}
copyFrom(v2: Vector2D): Vector2D {
this.x = v2.x;
this.y = v2.y;
return this;
}
clone(): Vector2D {
return new Vector2D(this.x, this.y);
}
zero(): Vector2D {
this.x = 0;
this.y = 0;
return this;
}
get isZero(): boolean {
return this.x == 0 && this.y == 0;
}
normalize(): Vector2D {
let len: number = this.length;
if (len == 0) {
this.x = 1;
return this;
}
this.x /= len;
this.y /= len;
return this;
}
get isNormalized(): boolean {
return this.length == 1.0;
}
truncate(max: number): Vector2D {
this.length = Math.min(max, this.length);
return this;
}
reverse(): Vector2D {
this.x = -this.x;
this.y = -this.y;
return this;
}
dotProd(v2: Vector2D): number {
return this.x * v2.x + this.y * v2.y;
}
crossProd(v2: Vector2D): number {
return this.x * v2.y - this.y * v2.x;
}
distSQ(v2: Vector2D): number {
let dx: number = v2.x - this.x;
let dy: number = v2.y - this.y;
return dx * dx + dy * dy;
}
distance(v2: Vector2D): number {
return Math.sqrt(this.distSQ(v2));
}
add(v2: Vector2D): Vector2D {
this.x += v2.x;
this.y += v2.y;
return this;
}
subtract(v2: Vector2D): Vector2D {
this.x -= v2.x;
this.y -= v2.y;
return this;
}
multiply(value: number): Vector2D {
this.x *= value;
this.y *= value;
return this;
}
divide(value: number): Vector2D {
this.x /= value;
this.y /= value;
return this;
}
set angle(value: number) {
this.radian = value * Math.PI / 180;
}
get angle(): number {
return this.radian * 180 / Math.PI;
}
set radian(value: number) {
let len: number = this.length;
this.setXY(Math.cos(value) * len, Math.sin(value) * len);
}
get radian(): number {
return Math.atan2(this.y, this.x);
}
equals(v2: Vector2D): boolean {
return this.x == v2.x && this.y == v2.y;
}
set length(value: number) {
let a: number = this.radian;
this.setXY(Math.cos(a) * value, Math.sin(a) * value);
}
get length(): number {
return Math.sqrt(this.lengthSQ);
}
get lengthSQ(): number {
return this.x * this.x + this.y * this.y;
}
get slope(): number{
return this.y / this.x;
}
toString(): string {
return "[Vector2D (x:" + this.x + ", y:" + this.y + ")]";
}
static corner(v1:Vector2D, v2:Vector2D){
return Math.acos(v1.dotProd(v2) / (v1.length * v2.length));
}
}
/**
* Created by rockyl on 2018/9/12.
*/
import * as Utils from './Utils'
import * as EgretUtils from './EgretUtils'
import * as StringUtils from './StringUtils'
import * as ResGroupsLoader from './ResGroupsLoader'
import * as TimeUtils from './TimeUtils'
import * as MathUtils from './MathUtils'
import * as ColorUtils from './ColorUtils'
import * as Ajax from './Ajax'
import * as RegUtils from './RegUtils'
import * as ObjectPool from './ObjectPool'
export {
Utils,
EgretUtils,
StringUtils,
ResGroupsLoader,
TimeUtils,
MathUtils,
ColorUtils,
Ajax,
RegUtils,
ObjectPool,
}
\ No newline at end of file
/**
* Created by rockyl on 16/3/9.
*/
function rotateLeft (lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
function addUnsigned (lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4) {
if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F (x, y, z) {
return (x & y) | ((~x) & z);
}
function G (x, y, z) {
return (x & z) | (y & (~z));
}
function H (x, y, z) {
return (x ^ y ^ z);
}
function I (x, y, z) {
return (y ^ (x | (~z)));
}
function FF (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
function GG (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
function HH (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
function II (a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
function convertToWordArray (string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWordsTempOne = lMessageLength + 8;
var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
function wordToHex (lValue) {
var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValueTemp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
}
return WordToHexValue;
};
function uTF8Encode (string) {
string = string.replace(/\x0d\x0a/g, "\x0a");
var output = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
} else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}
return output;
};
export function md5(string) {
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
string = uTF8Encode(string);
x = convertToWordArray(string);
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
return tempValue.toLowerCase();
}
\ No newline at end of file
/**
* Created by rockyl on 2018/1/22.
*
* 有附加部分的进度条
*/
export class AdditionalProgressBar extends eui.ProgressBar {
public thumbAdditional: eui.UIComponent = null;
private _additionalRect: egret.Rectangle;
private _additional = 0;
protected partAdded(partName: string, instance: any): void {
super.partAdded(partName, instance);
switch (partName) {
case 'thumbAdditional':
this.thumbAdditional.scrollRect = this._additionalRect = new egret.Rectangle();
egret.callLater(() => {
this._additionalRect.height = this.thumbAdditional.height;
this.thumbAdditional.scrollRect = this._additionalRect;
}, this);
break;
}
}
protected updateSkinDisplayList(): void {
super.updateSkinDisplayList();
if (this.thumbAdditional) {
this.renderAdditional();
}
}
private renderAdditional() {
this._additionalRect.width = this.thumbAdditional.width * this._additional / this.maximum;
this.thumbAdditional.scrollRect = this._additionalRect;
}
get additional() {
return this._additional;
}
set additional(value) {
this._additional = Math.max((Math.min(value + this.value, this.maximum)), this.value);
if (this.thumbAdditional) {
this.invalidateDisplayList();
}
}
}
/**
* Created by rockyl on 16/3/30.
*
* 滚动图片
*/
import {ITicker, TickerManager} from "../support/TickerManager";
export class ScrollImage extends eui.Group implements ITicker {
private _orgWidth: number;
private _playing: boolean;
private _bmp: eui.Image;
public speedX: number = -0.5;
public speedY: number = 0;
public repeatedImage: string = '';
constructor() {
super();
this.init();
}
private init(): void {
this.scrollEnabled = true;
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedToStage, this);
}
private onAddedToStage(event: egret.Event): void {
if (this._playing) {
TickerManager.register(this);
}
}
private onRemovedToStage(event: egret.Event): void {
TickerManager.unregister(this);
}
protected createChildren(): void {
super.createChildren();
let bmp = this._bmp = new eui.Image();
this.addChild(bmp);
bmp.source = this.repeatedImage;
this._orgWidth = bmp.width;
bmp.fillMode = egret.BitmapFillMode.REPEAT;
bmp.width *= 2;
this.play();
}
play(): void {
if (this._playing) {
return;
}
this._playing = true;
TickerManager.register(this);
}
stop(): void {
if (!this._playing) {
return;
}
this._playing = false;
TickerManager.unregister(this);
}
update(): void {
this.scrollH -= this.speedX;
if (this.speedX < 0 && this.scrollH > this._orgWidth) {
this.scrollH -= this._orgWidth;
}
if (this.speedX > 0 && this.scrollH < 0) {
this.scrollH += this._orgWidth;
}
/*this.scrollV -= this.speedY;
if(this.speedY < 0 && this.scrollV > this._orgWidth){
this.scrollV -= this._orgWidth;
}*/
}
}
/**
* Created by rocky.l on 2017/9/2.
*/
import {VisualEventComponent} from "../support/EventComponent";
export class Shape extends VisualEventComponent {
protected _shape: egret.Shape;
constructor() {
super();
this._shape = new egret.Shape();
this.addChild(this._shape);
}
protected childrenCreated(): void {
super.childrenCreated();
this.onResize();
this.registerEvent(this, egret.Event.RESIZE, this.onResize, this);
}
protected onResize(event: egret.Event = null): void {
let g = this._shape.graphics;
this.redraw(g);
}
protected redraw(graphics: egret.Graphics) {
}
}
This diff is collapsed.
/**
* Created by rockyl on 2018/9/12.
*/
export {
}
......@@ -8,9 +8,7 @@ exports.replaces = {
'index.html',
'project.json'
],
nameOfFiles: [
]
nameOfFiles: []
};
//收尾时删除的文件
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment