reformat code

This commit is contained in:
yhh
2020-07-28 16:25:20 +08:00
parent 5994f0bee3
commit 514572f291
103 changed files with 2896 additions and 2839 deletions
+11 -11
View File
@@ -1,13 +1,13 @@
{ {
// See https://go.microsoft.com/fwlink/?LinkId=733558 // See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format // for the documentation about the tasks.json format
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
{ {
"type": "gulp", "type": "gulp",
"task": "build", "task": "build",
"group": "build", "group": "build",
"problemMatcher": [] "problemMatcher": []
} }
] ]
} }
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"typescript.tsdk": "./node_modules/typescript/lib" "typescript.tsdk": "./node_modules/typescript/lib"
} }
+167 -167
View File
@@ -27,9 +27,9 @@ declare module es {
declare module es { declare module es {
class AStarPathfinder { class AStarPathfinder {
static search<T>(graph: IAstarGraph<T>, start: T, goal: T): T[]; static search<T>(graph: IAstarGraph<T>, start: T, goal: T): T[];
static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[];
private static hasKey; private static hasKey;
private static getKey; private static getKey;
static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[];
} }
class AStarNode<T> extends PriorityQueueNode { class AStarNode<T> extends PriorityQueueNode {
data: T; data: T;
@@ -68,9 +68,9 @@ declare module es {
private _nodes; private _nodes;
private _numNodesEverEnqueued; private _numNodesEverEnqueued;
constructor(maxNodes: number); constructor(maxNodes: number);
clear(): void;
readonly count: number; readonly count: number;
readonly maxSize: number; readonly maxSize: number;
clear(): void;
contains(node: T): boolean; contains(node: T): boolean;
enqueue(node: T, priority: number): void; enqueue(node: T, priority: number): void;
dequeue(): T; dequeue(): T;
@@ -103,28 +103,21 @@ declare module es {
} }
declare module es { declare module es {
class Vector2 { class Vector2 {
x: number;
y: number;
private static readonly unitYVector; private static readonly unitYVector;
private static readonly unitXVector; private static readonly unitXVector;
private static readonly unitVector2; private static readonly unitVector2;
private static readonly zeroVector2; private static readonly zeroVector2;
x: number;
y: number;
constructor(x?: number, y?: number);
static readonly zero: Vector2; static readonly zero: Vector2;
static readonly one: Vector2; static readonly one: Vector2;
static readonly unitX: Vector2; static readonly unitX: Vector2;
static readonly unitY: Vector2; static readonly unitY: Vector2;
constructor(x?: number, y?: number);
add(value: Vector2): Vector2;
divide(value: Vector2): Vector2;
multiply(value: Vector2): Vector2;
subtract(value: Vector2): this;
static add(value1: Vector2, value2: Vector2): Vector2; static add(value1: Vector2, value2: Vector2): Vector2;
static divide(value1: Vector2, value2: Vector2): Vector2; static divide(value1: Vector2, value2: Vector2): Vector2;
static multiply(value1: Vector2, value2: Vector2): Vector2; static multiply(value1: Vector2, value2: Vector2): Vector2;
static subtract(value1: Vector2, value2: Vector2): Vector2; static subtract(value1: Vector2, value2: Vector2): Vector2;
normalize(): void;
length(): number;
round(): Vector2;
static normalize(value: Vector2): Vector2; static normalize(value: Vector2): Vector2;
static dot(value1: Vector2, value2: Vector2): number; static dot(value1: Vector2, value2: Vector2): number;
static distanceSquared(value1: Vector2, value2: Vector2): number; static distanceSquared(value1: Vector2, value2: Vector2): number;
@@ -133,6 +126,13 @@ declare module es {
static transform(position: Vector2, matrix: Matrix2D): Vector2; static transform(position: Vector2, matrix: Matrix2D): Vector2;
static distance(value1: Vector2, value2: Vector2): number; static distance(value1: Vector2, value2: Vector2): number;
static negate(value: Vector2): Vector2; static negate(value: Vector2): Vector2;
add(value: Vector2): Vector2;
divide(value: Vector2): Vector2;
multiply(value: Vector2): Vector2;
subtract(value: Vector2): this;
normalize(): void;
length(): number;
round(): Vector2;
equals(other: Vector2): boolean; equals(other: Vector2): boolean;
} }
} }
@@ -185,9 +185,9 @@ declare module es {
} }
class WeightedPathfinder { class WeightedPathfinder {
static search<T>(graph: IWeightedGraph<T>, start: T, goal: T): T[]; static search<T>(graph: IWeightedGraph<T>, start: T, goal: T): T[];
static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[];
private static hasKey; private static hasKey;
private static getKey; private static getKey;
static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[];
} }
} }
declare module es { declare module es {
@@ -228,12 +228,12 @@ declare module es {
declare module es { declare module es {
abstract class Component { abstract class Component {
entity: Entity; entity: Entity;
readonly transform: Transform;
enabled: boolean;
updateOrder: number;
updateInterval: number; updateInterval: number;
readonly transform: Transform;
private _enabled; private _enabled;
enabled: boolean;
private _updateOrder; private _updateOrder;
updateOrder: number;
initialize(): void; initialize(): void;
onAddedToEntity(): void; onAddedToEntity(): void;
onRemovedFromEntity(): void; onRemovedFromEntity(): void;
@@ -252,27 +252,27 @@ declare module es {
static emitter: Emitter<CoreEvents>; static emitter: Emitter<CoreEvents>;
static graphicsDevice: GraphicsDevice; static graphicsDevice: GraphicsDevice;
static content: ContentManager; static content: ContentManager;
static readonly Instance: Core;
static _instance: Core; static _instance: Core;
_scene: Scene;
_nextScene: Scene; _nextScene: Scene;
_sceneTransition: SceneTransition; _sceneTransition: SceneTransition;
_globalManagers: GlobalManager[]; _globalManagers: GlobalManager[];
static scene: Scene;
constructor(); constructor();
private onAddToStage; static readonly Instance: Core;
onOrientationChanged(): void; _scene: Scene;
protected onGraphicsDeviceReset(): void; static scene: Scene;
protected initialize(): void;
protected update(): Promise<void>;
draw(): Promise<void>;
startDebugUpdate(): void;
endDebugUpdate(): void;
onSceneChanged(): void;
static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T; static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T;
static registerGlobalManager(manager: es.GlobalManager): void; static registerGlobalManager(manager: es.GlobalManager): void;
static unregisterGlobalManager(manager: es.GlobalManager): void; static unregisterGlobalManager(manager: es.GlobalManager): void;
static getGlobalManager<T extends es.GlobalManager>(type: any): T; static getGlobalManager<T extends es.GlobalManager>(type: any): T;
onOrientationChanged(): void;
draw(): Promise<void>;
startDebugUpdate(): void;
endDebugUpdate(): void;
onSceneChanged(): void;
protected onGraphicsDeviceReset(): void;
protected initialize(): void;
protected update(): Promise<void>;
private onAddToStage;
} }
} }
declare module es { declare module es {
@@ -290,16 +290,17 @@ declare module es {
readonly id: number; readonly id: number;
readonly transform: Transform; readonly transform: Transform;
readonly components: ComponentList; readonly components: ComponentList;
tag: number;
updateInterval: number; updateInterval: number;
enabled: boolean; componentBits: BitSet;
updateOrder: number; constructor(name: string);
_isDestroyed: boolean; _isDestroyed: boolean;
readonly isDestroyed: boolean; readonly isDestroyed: boolean;
componentBits: BitSet;
private _tag; private _tag;
tag: number;
private _enabled; private _enabled;
enabled: boolean;
private _updateOrder; private _updateOrder;
updateOrder: number;
parent: Transform; parent: Transform;
readonly childCount: number; readonly childCount: number;
position: Vector2; position: Vector2;
@@ -313,7 +314,6 @@ declare module es {
readonly worldInverseTransform: Matrix2D; readonly worldInverseTransform: Matrix2D;
readonly localToWorldTransform: Matrix2D; readonly localToWorldTransform: Matrix2D;
readonly worldToLocalTransform: Matrix2D; readonly worldToLocalTransform: Matrix2D;
constructor(name: string);
onTransformChanged(comp: transform.Component): void; onTransformChanged(comp: transform.Component): void;
setTag(tag: number): Entity; setTag(tag: number): Entity;
setEnabled(isEnabled: boolean): this; setEnabled(isEnabled: boolean): this;
@@ -322,7 +322,6 @@ declare module es {
detachFromScene(): void; detachFromScene(): void;
attachToScene(newScene: Scene): void; attachToScene(newScene: Scene): void;
clone(position?: Vector2): Entity; clone(position?: Vector2): Entity;
protected copyFrom(entity: Entity): void;
onAddedToScene(): void; onAddedToScene(): void;
onRemovedFromScene(): void; onRemovedFromScene(): void;
update(): void; update(): void;
@@ -336,6 +335,7 @@ declare module es {
removeAllComponents(): void; removeAllComponents(): void;
compareTo(other: Entity): number; compareTo(other: Entity): number;
toString(): string; toString(): string;
protected copyFrom(entity: Entity): void;
} }
} }
declare module es { declare module es {
@@ -349,8 +349,8 @@ declare module es {
_renderers: Renderer[]; _renderers: Renderer[];
readonly _postProcessors: PostProcessor[]; readonly _postProcessors: PostProcessor[];
_didSceneBegin: any; _didSceneBegin: any;
static createWithDefaultRenderer(): Scene;
constructor(); constructor();
static createWithDefaultRenderer(): Scene;
initialize(): void; initialize(): void;
onStart(): Promise<void>; onStart(): Promise<void>;
unload(): void; unload(): void;
@@ -397,20 +397,6 @@ declare module es {
} }
class Transform extends HashObject { class Transform extends HashObject {
readonly entity: Entity; readonly entity: Entity;
parent: Transform;
readonly childCount: number;
position: Vector2;
localPosition: Vector2;
rotation: number;
rotationDegrees: number;
localRotation: number;
localRotationDegrees: number;
scale: Vector2;
localScale: Vector2;
readonly worldInverseTransform: Matrix2D;
readonly localToWorldTransform: Matrix2D;
readonly worldToLocalTransform: Matrix2D;
_parent: Transform;
hierarchyDirty: DirtyType; hierarchyDirty: DirtyType;
_localDirty: boolean; _localDirty: boolean;
_localPositionDirty: boolean; _localPositionDirty: boolean;
@@ -421,19 +407,33 @@ declare module es {
_worldInverseDirty: boolean; _worldInverseDirty: boolean;
_localTransform: Matrix2D; _localTransform: Matrix2D;
_worldTransform: Matrix2D; _worldTransform: Matrix2D;
_worldToLocalTransform: Matrix2D;
_worldInverseTransform: Matrix2D;
_rotationMatrix: Matrix2D; _rotationMatrix: Matrix2D;
_translationMatrix: Matrix2D; _translationMatrix: Matrix2D;
_scaleMatrix: Matrix2D; _scaleMatrix: Matrix2D;
_position: Vector2;
_scale: Vector2;
_rotation: number;
_localPosition: Vector2;
_localScale: Vector2;
_localRotation: number;
_children: Transform[]; _children: Transform[];
constructor(entity: Entity); constructor(entity: Entity);
readonly childCount: number;
rotationDegrees: number;
localRotationDegrees: number;
readonly localToWorldTransform: Matrix2D;
_parent: Transform;
parent: Transform;
_worldToLocalTransform: Matrix2D;
readonly worldToLocalTransform: Matrix2D;
_worldInverseTransform: Matrix2D;
readonly worldInverseTransform: Matrix2D;
_position: Vector2;
position: Vector2;
_scale: Vector2;
scale: Vector2;
_rotation: number;
rotation: number;
_localPosition: Vector2;
localPosition: Vector2;
_localScale: Vector2;
localScale: Vector2;
_localRotation: number;
localRotation: number;
getChild(index: number): Transform; getChild(index: number): Transform;
setParent(parent: Transform): Transform; setParent(parent: Transform): Transform;
setPosition(x: number, y: number): Transform; setPosition(x: number, y: number): Transform;
@@ -465,23 +465,7 @@ declare module es {
bottom: number; bottom: number;
} }
class Camera extends Component { class Camera extends Component {
position: Vector2;
rotation: number;
zoom: number;
minimumZoom: number;
maximumZoom: number;
readonly bounds: Rectangle;
readonly transformMatrix: Matrix2D;
readonly inverseTransformMatrix: Matrix2D;
origin: Vector2;
_zoom: any;
_minimumZoom: number;
_maximumZoom: number;
_bounds: Rectangle;
_inset: CameraInset; _inset: CameraInset;
_transformMatrix: Matrix2D;
_inverseTransformMatrix: Matrix2D;
_origin: Vector2;
_areMatrixedDirty: boolean; _areMatrixedDirty: boolean;
_areBoundsDirty: boolean; _areBoundsDirty: boolean;
_isProjectionMatrixDirty: boolean; _isProjectionMatrixDirty: boolean;
@@ -496,8 +480,23 @@ declare module es {
_cameraStyle: CameraStyle; _cameraStyle: CameraStyle;
_worldSpaceDeadZone: Rectangle; _worldSpaceDeadZone: Rectangle;
constructor(targetEntity?: Entity, cameraStyle?: CameraStyle); constructor(targetEntity?: Entity, cameraStyle?: CameraStyle);
position: Vector2;
rotation: number;
_zoom: any;
zoom: number;
_minimumZoom: number;
minimumZoom: number;
_maximumZoom: number;
maximumZoom: number;
_bounds: Rectangle;
readonly bounds: Rectangle;
_transformMatrix: Matrix2D;
readonly transformMatrix: Matrix2D;
_inverseTransformMatrix: Matrix2D;
readonly inverseTransformMatrix: Matrix2D;
_origin: Vector2;
origin: Vector2;
onSceneSizeChanged(newWidth: number, newHeight: number): void; onSceneSizeChanged(newWidth: number, newHeight: number): void;
protected updateMatrixes(): void;
setInset(left: number, right: number, top: number, bottom: number): Camera; setInset(left: number, right: number, top: number, bottom: number): Camera;
setPosition(position: Vector2): this; setPosition(position: Vector2): this;
setRotation(rotation: number): Camera; setRotation(rotation: number): Camera;
@@ -516,6 +515,7 @@ declare module es {
updateFollow(): void; updateFollow(): void;
follow(targetEntity: Entity, cameraStyle?: CameraStyle): void; follow(targetEntity: Entity, cameraStyle?: CameraStyle): void;
setCenteredDeadzone(width: number, height: number): void; setCenteredDeadzone(width: number, height: number): void;
protected updateMatrixes(): void;
} }
} }
declare module es { declare module es {
@@ -540,28 +540,28 @@ declare module es {
declare module es { declare module es {
abstract class RenderableComponent extends Component implements IRenderable { abstract class RenderableComponent extends Component implements IRenderable {
displayObject: egret.DisplayObject; displayObject: egret.DisplayObject;
color: number;
protected _areBoundsDirty: boolean;
readonly width: number; readonly width: number;
readonly height: number; readonly height: number;
readonly bounds: Rectangle;
renderLayer: number;
color: number;
localOffset: Vector2;
isVisible: boolean;
protected _localOffset: Vector2; protected _localOffset: Vector2;
localOffset: Vector2;
protected _renderLayer: number; protected _renderLayer: number;
renderLayer: number;
protected _bounds: Rectangle; protected _bounds: Rectangle;
readonly bounds: Rectangle;
private _isVisible; private _isVisible;
protected _areBoundsDirty: boolean; isVisible: boolean;
onEntityTransformChanged(comp: transform.Component): void; onEntityTransformChanged(comp: transform.Component): void;
abstract render(camera: Camera): any; abstract render(camera: Camera): any;
protected onBecameVisible(): void;
protected onBecameInvisible(): void;
isVisibleFromCamera(camera: Camera): boolean; isVisibleFromCamera(camera: Camera): boolean;
setRenderLayer(renderLayer: number): RenderableComponent; setRenderLayer(renderLayer: number): RenderableComponent;
setColor(color: number): RenderableComponent; setColor(color: number): RenderableComponent;
setLocalOffset(offset: Vector2): RenderableComponent; setLocalOffset(offset: Vector2): RenderableComponent;
sync(camera: Camera): void; sync(camera: Camera): void;
toString(): string; toString(): string;
protected onBecameVisible(): void;
protected onBecameInvisible(): void;
} }
} }
declare module es { declare module es {
@@ -575,13 +575,13 @@ declare module es {
} }
declare module es { declare module es {
class SpriteRenderer extends RenderableComponent { class SpriteRenderer extends RenderableComponent {
readonly bounds: Rectangle;
origin: Vector2;
originNormalized: Vector2;
sprite: Sprite;
protected _origin: Vector2;
protected _sprite: Sprite;
constructor(sprite?: Sprite | egret.Texture); constructor(sprite?: Sprite | egret.Texture);
readonly bounds: Rectangle;
originNormalized: Vector2;
protected _origin: Vector2;
origin: Vector2;
protected _sprite: Sprite;
sprite: Sprite;
setSprite(sprite: Sprite): SpriteRenderer; setSprite(sprite: Sprite): SpriteRenderer;
setOrigin(origin: Vector2): SpriteRenderer; setOrigin(origin: Vector2): SpriteRenderer;
setOriginNormalized(value: Vector2): SpriteRenderer; setOriginNormalized(value: Vector2): SpriteRenderer;
@@ -593,9 +593,9 @@ declare module es {
protected sourceRect: Rectangle; protected sourceRect: Rectangle;
protected leftTexture: egret.Bitmap; protected leftTexture: egret.Bitmap;
protected rightTexture: egret.Bitmap; protected rightTexture: egret.Bitmap;
constructor(sprite: Sprite);
scrollX: number; scrollX: number;
scrollY: number; scrollY: number;
constructor(sprite: Sprite);
render(camera: es.Camera): void; render(camera: es.Camera): void;
} }
} }
@@ -647,12 +647,12 @@ declare module es {
currentAnimation: SpriteAnimation; currentAnimation: SpriteAnimation;
currentAnimationName: string; currentAnimationName: string;
currentFrame: number; currentFrame: number;
readonly isRunning: boolean;
readonly animations: Map<string, SpriteAnimation>;
private _animations;
_elapsedTime: number; _elapsedTime: number;
_loopMode: LoopMode; _loopMode: LoopMode;
constructor(sprite?: Sprite); constructor(sprite?: Sprite);
readonly isRunning: boolean;
private _animations;
readonly animations: Map<string, SpriteAnimation>;
update(): void; update(): void;
addAnimation(name: string, animation: SpriteAnimation): SpriteAnimator; addAnimation(name: string, animation: SpriteAnimation): SpriteAnimator;
play(name: string, loopMode?: LoopMode): void; play(name: string, loopMode?: LoopMode): void;
@@ -689,22 +689,22 @@ declare module es {
declare module es { declare module es {
abstract class Collider extends Component { abstract class Collider extends Component {
shape: Shape; shape: Shape;
localOffset: Vector2;
readonly absolutePosition: Vector2;
readonly rotation: number;
isTrigger: boolean; isTrigger: boolean;
physicsLayer: number; physicsLayer: number;
collidesWithLayers: number; collidesWithLayers: number;
shouldColliderScaleAndRotateWithTransform: boolean; shouldColliderScaleAndRotateWithTransform: boolean;
readonly bounds: Rectangle;
registeredPhysicsBounds: Rectangle; registeredPhysicsBounds: Rectangle;
protected _colliderRequiresAutoSizing: any;
protected _localOffset: Vector2;
_localOffsetLength: number; _localOffsetLength: number;
protected _isParentEntityAddedToScene: any;
protected _isColliderRegistered: any;
_isPositionDirty: boolean; _isPositionDirty: boolean;
_isRotationDirty: boolean; _isRotationDirty: boolean;
protected _colliderRequiresAutoSizing: any;
protected _isParentEntityAddedToScene: any;
protected _isColliderRegistered: any;
readonly absolutePosition: Vector2;
readonly rotation: number;
readonly bounds: Rectangle;
protected _localOffset: Vector2;
localOffset: Vector2;
setLocalOffset(offset: Vector2): Collider; setLocalOffset(offset: Vector2): Collider;
setShouldColliderScaleAndRotateWithTransform(shouldColliderScaleAndRotationWithTransform: boolean): Collider; setShouldColliderScaleAndRotateWithTransform(shouldColliderScaleAndRotationWithTransform: boolean): Collider;
onAddedToEntity(): void; onAddedToEntity(): void;
@@ -721,9 +721,9 @@ declare module es {
} }
declare module es { declare module es {
class BoxCollider extends Collider { class BoxCollider extends Collider {
constructor();
width: number; width: number;
height: number; height: number;
constructor();
setSize(width: number, height: number): this; setSize(width: number, height: number): this;
setWidth(width: number): BoxCollider; setWidth(width: number): BoxCollider;
setHeight(height: number): void; setHeight(height: number): void;
@@ -732,8 +732,8 @@ declare module es {
} }
declare module es { declare module es {
class CircleCollider extends Collider { class CircleCollider extends Collider {
radius: number;
constructor(radius?: number); constructor(radius?: number);
radius: number;
setRadius(radius: number): CircleCollider; setRadius(radius: number): CircleCollider;
toString(): string; toString(): string;
} }
@@ -745,12 +745,12 @@ declare module es {
} }
declare module es { declare module es {
class EntitySystem { class EntitySystem {
private _scene;
private _entities; private _entities;
constructor(matcher?: Matcher);
private _scene;
scene: Scene;
private _matcher; private _matcher;
readonly matcher: Matcher; readonly matcher: Matcher;
scene: Scene;
constructor(matcher?: Matcher);
initialize(): void; initialize(): void;
onChanged(entity: Entity): void; onChanged(entity: Entity): void;
add(entity: Entity): void; add(entity: Entity): void;
@@ -783,8 +783,8 @@ declare module es {
declare module es { declare module es {
abstract class ProcessingSystem extends EntitySystem { abstract class ProcessingSystem extends EntitySystem {
onChanged(entity: Entity): void; onChanged(entity: Entity): void;
protected process(entities: Entity[]): void;
abstract processSystem(): any; abstract processSystem(): any;
protected process(entities: Entity[]): void;
} }
} }
declare module es { declare module es {
@@ -796,12 +796,12 @@ declare module es {
andNot(bs: BitSet): void; andNot(bs: BitSet): void;
cardinality(): number; cardinality(): number;
clear(pos?: number): void; clear(pos?: number): void;
private ensure;
get(pos: number): boolean; get(pos: number): boolean;
intersects(set: BitSet): boolean; intersects(set: BitSet): boolean;
isEmpty(): boolean; isEmpty(): boolean;
nextSetBit(from: number): number; nextSetBit(from: number): number;
set(pos: number, value?: boolean): void; set(pos: number, value?: boolean): void;
private ensure;
} }
} }
declare module es { declare module es {
@@ -879,13 +879,13 @@ declare module es {
onComponentRemoved(entity: Entity): void; onComponentRemoved(entity: Entity): void;
onEntityAdded(entity: Entity): void; onEntityAdded(entity: Entity): void;
onEntityRemoved(entity: Entity): void; onEntityRemoved(entity: Entity): void;
protected notifyEntityChanged(entity: Entity): void;
protected removeFromProcessors(entity: Entity): void;
begin(): void; begin(): void;
update(): void; update(): void;
lateUpdate(): void; lateUpdate(): void;
end(): void; end(): void;
getProcessor<T extends EntitySystem>(): T; getProcessor<T extends EntitySystem>(): T;
protected notifyEntityChanged(entity: Entity): void;
protected removeFromProcessors(entity: Entity): void;
} }
} }
declare module es { declare module es {
@@ -939,13 +939,13 @@ declare module es {
} }
} }
declare class StringUtils { declare class StringUtils {
private static specialSigns;
static matchChineseWord(str: string): string[]; static matchChineseWord(str: string): string[];
static lTrim(target: string): string; static lTrim(target: string): string;
static rTrim(target: string): string; static rTrim(target: string): string;
static trim(target: string): string; static trim(target: string): string;
static isWhiteSpace(str: string): boolean; static isWhiteSpace(str: string): boolean;
static replaceMatch(mainStr: string, targetStr: string, replaceStr: string, caseMark?: boolean): string; static replaceMatch(mainStr: string, targetStr: string, replaceStr: string, caseMark?: boolean): string;
private static specialSigns;
static htmlSpecialChars(str: string, reversion?: boolean): string; static htmlSpecialChars(str: string, reversion?: boolean): string;
static zfill(str: string, width?: number): string; static zfill(str: string, width?: number): string;
static reverse(str: string): string; static reverse(str: string): string;
@@ -969,8 +969,8 @@ declare module es {
static deltaTime: number; static deltaTime: number;
static timeScale: number; static timeScale: number;
static frameCount: number; static frameCount: number;
private static _lastTime;
static _timeSinceSceneLoad: any; static _timeSinceSceneLoad: any;
private static _lastTime;
static update(currentTime: number): void; static update(currentTime: number): void;
static sceneChanged(): void; static sceneChanged(): void;
static checkEvery(interval: number): boolean; static checkEvery(interval: number): boolean;
@@ -998,10 +998,10 @@ declare module es {
} }
declare module es { declare module es {
class GraphicsDevice { class GraphicsDevice {
private _viewport;
readonly viewport: Viewport;
graphicsCapabilities: GraphicsCapabilities; graphicsCapabilities: GraphicsCapabilities;
constructor(); constructor();
private _viewport;
readonly viewport: Viewport;
private setup; private setup;
} }
} }
@@ -1009,15 +1009,15 @@ declare module es {
class Viewport { class Viewport {
private _x; private _x;
private _y; private _y;
private _width;
private _height;
private _minDepth; private _minDepth;
private _maxDepth; private _maxDepth;
height: number; constructor(x: number, y: number, width: number, height: number);
private _width;
width: number; width: number;
private _height;
height: number;
readonly aspectRatio: number; readonly aspectRatio: number;
bounds: Rectangle; bounds: Rectangle;
constructor(x: number, y: number, width: number, height: number);
} }
} }
declare module es { declare module es {
@@ -1035,17 +1035,17 @@ declare module es {
} }
declare module es { declare module es {
class PostProcessor { class PostProcessor {
static default_vert: string;
enabled: boolean; enabled: boolean;
effect: egret.Filter; effect: egret.Filter;
scene: Scene; scene: Scene;
shape: egret.Shape; shape: egret.Shape;
static default_vert: string;
constructor(effect?: egret.Filter); constructor(effect?: egret.Filter);
onAddedToScene(scene: Scene): void; onAddedToScene(scene: Scene): void;
process(): void; process(): void;
onSceneBackBufferSizeChanged(newWidth: number, newHeight: number): void; onSceneBackBufferSizeChanged(newWidth: number, newHeight: number): void;
protected drawFullscreenQuad(): void;
unload(): void; unload(): void;
protected drawFullscreenQuad(): void;
} }
} }
declare module es { declare module es {
@@ -1060,11 +1060,11 @@ declare module es {
protected constructor(renderOrder: number, camera?: Camera); protected constructor(renderOrder: number, camera?: Camera);
onAddedToScene(scene: Scene): void; onAddedToScene(scene: Scene): void;
unload(): void; unload(): void;
protected beginRender(cam: Camera): void;
abstract render(scene: Scene): any; abstract render(scene: Scene): any;
protected renderAfterStateCheck(renderable: IRenderable, cam: Camera): void;
onSceneBackBufferSizeChanged(newWidth: number, newHeight: number): void; onSceneBackBufferSizeChanged(newWidth: number, newHeight: number): void;
compareTo(other: Renderer): number; compareTo(other: Renderer): number;
protected beginRender(cam: Camera): void;
protected renderAfterStateCheck(renderable: IRenderable, cam: Camera): void;
} }
} }
declare module es { declare module es {
@@ -1081,33 +1081,33 @@ declare module es {
declare module es { declare module es {
class PolyLight extends RenderableComponent { class PolyLight extends RenderableComponent {
power: number; power: number;
protected _radius: number;
private _lightEffect; private _lightEffect;
private _indices; private _indices;
radius: number;
constructor(radius: number, color: number, power: number); constructor(radius: number, color: number, power: number);
private computeTriangleIndices; protected _radius: number;
radius: number;
setRadius(radius: number): void; setRadius(radius: number): void;
render(camera: Camera): void; render(camera: Camera): void;
reset(): void; reset(): void;
private computeTriangleIndices;
} }
} }
declare module es { declare module es {
abstract class SceneTransition { abstract class SceneTransition {
private _hasPreviousSceneRender;
loadsNewScene: boolean; loadsNewScene: boolean;
isNewSceneLoaded: boolean; isNewSceneLoaded: boolean;
protected sceneLoadAction: Function;
onScreenObscured: Function; onScreenObscured: Function;
onTransitionCompleted: Function; onTransitionCompleted: Function;
readonly hasPreviousSceneRender: boolean; protected sceneLoadAction: Function;
constructor(sceneLoadAction: Function); constructor(sceneLoadAction: Function);
private _hasPreviousSceneRender;
readonly hasPreviousSceneRender: boolean;
preRender(): void; preRender(): void;
render(): void; render(): void;
onBeginTransition(): Promise<void>; onBeginTransition(): Promise<void>;
tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection?: boolean): Promise<boolean>;
protected transitionComplete(): void; protected transitionComplete(): void;
protected loadNextScene(): Promise<void>; protected loadNextScene(): Promise<void>;
tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection?: boolean): Promise<boolean>;
} }
} }
declare module es { declare module es {
@@ -1125,13 +1125,13 @@ declare module es {
} }
declare module es { declare module es {
class WindTransition extends SceneTransition { class WindTransition extends SceneTransition {
duration: number;
easeType: (t: number) => number;
private _mask; private _mask;
private _windEffect; private _windEffect;
duration: number; constructor(sceneLoadAction: Function);
windSegments: number; windSegments: number;
size: number; size: number;
easeType: (t: number) => number;
constructor(sceneLoadAction: Function);
onBeginTransition(): Promise<void>; onBeginTransition(): Promise<void>;
} }
} }
@@ -1202,14 +1202,14 @@ declare module es {
readonly center: Vector2; readonly center: Vector2;
location: Vector2; location: Vector2;
size: Vector2; size: Vector2;
static fromMinMax(minX: number, minY: number, maxX: number, maxY: number): Rectangle;
static rectEncompassingPoints(points: Vector2[]): Rectangle;
intersects(value: egret.Rectangle): boolean; intersects(value: egret.Rectangle): boolean;
containsRect(value: Rectangle): boolean; containsRect(value: Rectangle): boolean;
getHalfSize(): Vector2; getHalfSize(): Vector2;
static fromMinMax(minX: number, minY: number, maxX: number, maxY: number): Rectangle;
getClosestPointOnRectangleBorderToPoint(point: Vector2, edgeNormal: Vector2): Vector2; getClosestPointOnRectangleBorderToPoint(point: Vector2, edgeNormal: Vector2): Vector2;
getClosestPointOnBoundsToOrigin(): Vector2; getClosestPointOnBoundsToOrigin(): Vector2;
calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number): void; calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number): void;
static rectEncompassingPoints(points: Vector2[]): Rectangle;
} }
} }
declare module es { declare module es {
@@ -1259,9 +1259,9 @@ declare module es {
} }
declare module es { declare module es {
class Physics { class Physics {
private static _spatialHash;
static spatialHashCellSize: number; static spatialHashCellSize: number;
static readonly allLayers: number; static readonly allLayers: number;
private static _spatialHash;
static reset(): void; static reset(): void;
static clear(): void; static clear(): void;
static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask?: number): number; static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask?: number): number;
@@ -1288,21 +1288,21 @@ declare module es {
declare module es { declare module es {
class Polygon extends Shape { class Polygon extends Shape {
points: Vector2[]; points: Vector2[];
readonly edgeNormals: Vector2[];
_areEdgeNormalsDirty: boolean; _areEdgeNormalsDirty: boolean;
_edgeNormals: Vector2[];
_originalPoints: Vector2[]; _originalPoints: Vector2[];
_polygonCenter: Vector2; _polygonCenter: Vector2;
isBox: boolean; isBox: boolean;
isUnrotated: boolean; isUnrotated: boolean;
constructor(points: Vector2[], isBox?: boolean); constructor(points: Vector2[], isBox?: boolean);
setPoints(points: Vector2[]): void; _edgeNormals: Vector2[];
recalculateCenterAndEdgeNormals(): void; readonly edgeNormals: Vector2[];
buildEdgeNormals(): void;
static buildSymmetricalPolygon(vertCount: number, radius: number): any[]; static buildSymmetricalPolygon(vertCount: number, radius: number): any[];
static recenterPolygonVerts(points: Vector2[]): void; static recenterPolygonVerts(points: Vector2[]): void;
static findPolygonCenter(points: Vector2[]): Vector2; static findPolygonCenter(points: Vector2[]): Vector2;
static getClosestPointOnPolygonToPoint(points: Vector2[], point: Vector2, distanceSquared: number, edgeNormal: Vector2): Vector2; static getClosestPointOnPolygonToPoint(points: Vector2[], point: Vector2, distanceSquared: number, edgeNormal: Vector2): Vector2;
setPoints(points: Vector2[]): void;
recalculateCenterAndEdgeNormals(): void;
buildEdgeNormals(): void;
recalculateBounds(collider: Collider): void; recalculateBounds(collider: Collider): void;
overlaps(other: Shape): any; overlaps(other: Shape): any;
collidesWithShape(other: Shape, result: CollisionResult): boolean; collidesWithShape(other: Shape, result: CollisionResult): boolean;
@@ -1370,24 +1370,24 @@ declare module es {
_cellDict: NumberDictionary; _cellDict: NumberDictionary;
_tempHashSet: Collider[]; _tempHashSet: Collider[];
constructor(cellSize?: number); constructor(cellSize?: number);
private cellCoords;
private cellAtPosition;
register(collider: Collider): void; register(collider: Collider): void;
remove(collider: Collider): void; remove(collider: Collider): void;
removeWithBruteForce(obj: Collider): void; removeWithBruteForce(obj: Collider): void;
clear(): void; clear(): void;
debugDraw(secondsToDisplay: number, textScale?: number): void; debugDraw(secondsToDisplay: number, textScale?: number): void;
private debugDrawCellDetails;
aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number): Collider[]; aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number): Collider[];
overlapCircle(circleCenter: Vector2, radius: number, results: Collider[], layerMask: any): number; overlapCircle(circleCenter: Vector2, radius: number, results: Collider[], layerMask: any): number;
private cellCoords;
private cellAtPosition;
private debugDrawCellDetails;
} }
class NumberDictionary { class NumberDictionary {
_store: Map<string, Collider[]>; _store: Map<string, Collider[]>;
private getKey;
add(x: number, y: number, list: Collider[]): void; add(x: number, y: number, list: Collider[]): void;
remove(obj: Collider): void; remove(obj: Collider): void;
tryGetValue(x: number, y: number): Collider[]; tryGetValue(x: number, y: number): Collider[];
clear(): void; clear(): void;
private getKey;
} }
class RaycastResultParser { class RaycastResultParser {
} }
@@ -1412,8 +1412,8 @@ declare class Base64Utils {
private static _keyStr; private static _keyStr;
private static _keyAll; private static _keyAll;
static encode: (input: any) => string; static encode: (input: any) => string;
private static _utf8_encode;
static decode(input: any, isNotStr?: boolean): string; static decode(input: any, isNotStr?: boolean): string;
private static _utf8_encode;
private static _utf8_decode; private static _utf8_decode;
private static getConfKey; private static getConfKey;
} }
@@ -1450,9 +1450,9 @@ declare module es {
} }
declare module es { declare module es {
class GlobalManager { class GlobalManager {
_enabled: boolean;
enabled: boolean; enabled: boolean;
setEnabled(isEnabled: boolean): void; setEnabled(isEnabled: boolean): void;
_enabled: boolean;
onEnabled(): void; onEnabled(): void;
onDisabled(): void; onDisabled(): void;
update(): void; update(): void;
@@ -1470,31 +1470,29 @@ declare module es {
class Input { class Input {
private static _init; private static _init;
private static _previousTouchState; private static _previousTouchState;
private static _gameTouchs;
private static _resolutionOffset; private static _resolutionOffset;
private static _resolutionScale;
private static _touchIndex; private static _touchIndex;
private static _gameTouchs;
static readonly gameTouchs: TouchState[];
private static _resolutionScale;
static readonly resolutionScale: Vector2;
private static _totalTouchCount; private static _totalTouchCount;
static readonly totalTouchCount: number;
static readonly touchPosition: Vector2; static readonly touchPosition: Vector2;
static maxSupportedTouch: number; static maxSupportedTouch: number;
static readonly resolutionScale: Vector2;
static readonly totalTouchCount: number;
static readonly gameTouchs: TouchState[];
static readonly touchPositionDelta: Vector2; static readonly touchPositionDelta: Vector2;
static initialize(): void; static initialize(): void;
static scaledPosition(position: Vector2): Vector2;
private static initTouchCache; private static initTouchCache;
private static touchBegin; private static touchBegin;
private static touchMove; private static touchMove;
private static touchEnd; private static touchEnd;
private static setpreviousTouchState; private static setpreviousTouchState;
static scaledPosition(position: Vector2): Vector2;
} }
} }
declare class KeyboardUtils { declare class KeyboardUtils {
static TYPE_KEY_DOWN: number; static TYPE_KEY_DOWN: number;
static TYPE_KEY_UP: number; static TYPE_KEY_UP: number;
private static keyDownDict;
private static keyUpDict;
static A: string; static A: string;
static B: string; static B: string;
static C: string; static C: string;
@@ -1566,13 +1564,15 @@ declare class KeyboardUtils {
static NUM_LOCK: string; static NUM_LOCK: string;
static SCROLL_LOCK: string; static SCROLL_LOCK: string;
static WINDOWS: string; static WINDOWS: string;
private static keyDownDict;
private static keyUpDict;
static init(): void; static init(): void;
private static onKeyDonwHander;
private static onKeyUpHander;
static registerKey(key: string, fun: Function, thisObj: any, type?: number, ...args: any[]): void; static registerKey(key: string, fun: Function, thisObj: any, type?: number, ...args: any[]): void;
static unregisterKey(key: string, type?: number): void; static unregisterKey(key: string, type?: number): void;
private static keyCodeToString;
static destroy(): void; static destroy(): void;
private static onKeyDonwHander;
private static onKeyUpHander;
private static keyCodeToString;
} }
declare module es { declare module es {
class ListPool { class ListPool {
@@ -1609,11 +1609,11 @@ declare class RandomUtils {
static randint(a: number, b: number): number; static randint(a: number, b: number): number;
static randnum(a: number, b: number): number; static randnum(a: number, b: number): number;
static shuffle(array: any[]): any[]; static shuffle(array: any[]): any[];
private static _randomCompare;
static choice(sequence: any): any; static choice(sequence: any): any;
static sample(sequence: any[], num: number): any[]; static sample(sequence: any[], num: number): any[];
static random(): number; static random(): number;
static boolean(chance?: number): boolean; static boolean(chance?: number): boolean;
private static _randomCompare;
} }
declare module es { declare module es {
class RectangleExt { class RectangleExt {
@@ -1625,9 +1625,9 @@ declare module es {
triangleIndices: number[]; triangleIndices: number[];
private _triPrev; private _triPrev;
private _triNext; private _triNext;
static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean;
triangulate(points: Vector2[], arePointsCCW?: boolean): void; triangulate(points: Vector2[], arePointsCCW?: boolean): void;
private initialize; private initialize;
static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean;
} }
} }
declare module es { declare module es {
@@ -1689,12 +1689,12 @@ declare namespace stopwatch {
getCompletedAndPendingSlices(): Slice[]; getCompletedAndPendingSlices(): Slice[];
getPendingSlice(): Slice; getPendingSlice(): Slice;
getTime(): number; getTime(): number;
private calculatePendingSlice;
private caculateStopwatchTime;
private getSystemTimeOfCurrentStopwatchTime;
reset(): void; reset(): void;
start(forceReset?: boolean): void; start(forceReset?: boolean): void;
stop(recordPendingSlice?: boolean): number; stop(recordPendingSlice?: boolean): number;
private calculatePendingSlice;
private caculateStopwatchTime;
private getSystemTimeOfCurrentStopwatchTime;
private recordPendingSlice; private recordPendingSlice;
} }
type GetTimeFunc = () => number; type GetTimeFunc = () => number;
@@ -1721,14 +1721,14 @@ declare module es {
static readonly barPadding: number; static readonly barPadding: number;
static readonly autoAdjustDelay: number; static readonly autoAdjustDelay: number;
private static _instance; private static _instance;
static readonly Instance: TimeRuler; targetSampleFrames: number;
width: number;
enabled: true;
showLog: boolean;
private _frameKey; private _frameKey;
private _logKey; private _logKey;
private _logs; private _logs;
private sampleFrames; private sampleFrames;
targetSampleFrames: number;
width: number;
enabled: true;
private _position; private _position;
private _prevLog; private _prevLog;
private _curLog; private _curLog;
@@ -1737,16 +1737,16 @@ declare module es {
private stopwacth; private stopwacth;
private _markerNameToIdMap; private _markerNameToIdMap;
private _updateCount; private _updateCount;
showLog: boolean;
private _frameAdjust; private _frameAdjust;
constructor(); constructor();
private onGraphicsDeviceReset; static readonly Instance: TimeRuler;
startFrame(): void; startFrame(): void;
beginMark(markerName: string, color: number, barIndex?: number): void; beginMark(markerName: string, color: number, barIndex?: number): void;
endMark(markerName: string, barIndex?: number): void; endMark(markerName: string, barIndex?: number): void;
getAverageTime(barIndex: number, markerName: string): number; getAverageTime(barIndex: number, markerName: string): number;
resetLog(): void; resetLog(): void;
render(position?: Vector2, width?: number): void; render(position?: Vector2, width?: number): void;
private onGraphicsDeviceReset;
} }
class FrameLog { class FrameLog {
bars: MarkerCollection[]; bars: MarkerCollection[];
+546 -532
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -11,7 +11,7 @@ gulp.task('buildJs', () => {
.js.pipe(inject.replace('var framework;', '')) .js.pipe(inject.replace('var framework;', ''))
.pipe(inject.prepend('window.framework = {};\n')) .pipe(inject.prepend('window.framework = {};\n'))
.pipe(inject.replace('var __extends =', 'window.__extends =')) .pipe(inject.replace('var __extends =', 'window.__extends ='))
.pipe(minify({ ext: { min: ".min.js" } })) .pipe(minify({ext: {min: ".min.js"}}))
.pipe(gulp.dest('./bin')); .pipe(gulp.dest('./bin'));
}); });
@@ -10,7 +10,7 @@ module es {
* @param start * @param start
* @param goal * @param goal
*/ */
public static search<T>(graph: IAstarGraph<T>, start: T, goal: T){ public static search<T>(graph: IAstarGraph<T>, start: T, goal: T) {
let foundPath = false; let foundPath = false;
let cameFrom = new Map<T, T>(); let cameFrom = new Map<T, T>();
cameFrom.set(start, start); cameFrom.set(start, start);
@@ -21,17 +21,17 @@ module es {
costSoFar.set(start, 0); costSoFar.set(start, 0);
while (frontier.count > 0){ while (frontier.count > 0) {
let current = frontier.dequeue(); let current = frontier.dequeue();
if (JSON.stringify(current.data) == JSON.stringify(goal)){ if (JSON.stringify(current.data) == JSON.stringify(goal)) {
foundPath = true; foundPath = true;
break; break;
} }
graph.getNeighbors(current.data).forEach(next => { graph.getNeighbors(current.data).forEach(next => {
let newCost = costSoFar.get(current.data) + graph.cost(current.data, next); let newCost = costSoFar.get(current.data) + graph.cost(current.data, next);
if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){ if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) {
costSoFar.set(next, newCost); costSoFar.set(next, newCost);
let priority = newCost + graph.heuristic(next, goal); let priority = newCost + graph.heuristic(next, goal);
frontier.enqueue(new AStarNode<T>(next), priority); frontier.enqueue(new AStarNode<T>(next), priority);
@@ -43,7 +43,28 @@ module es {
return foundPath ? this.recontructPath(cameFrom, start, goal) : null; return foundPath ? this.recontructPath(cameFrom, start, goal) : null;
} }
private static hasKey<T>(map: Map<T, number>, compareKey: T){ /**
* cameFrom字典重新构造路径
* @param cameFrom
* @param start
* @param goal
*/
public static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[] {
let path = [];
let current = goal;
path.push(goal);
while (current != start) {
current = this.getKey(cameFrom, current);
path.push(current);
}
path.reverse();
return path;
}
private static hasKey<T>(map: Map<T, number>, compareKey: T) {
let iterator = map.keys(); let iterator = map.keys();
let r: IteratorResult<T>; let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) { while (r = iterator.next() , !r.done) {
@@ -54,7 +75,7 @@ module es {
return false; return false;
} }
private static getKey<T>(map: Map<T, T>, compareKey: T){ private static getKey<T>(map: Map<T, T>, compareKey: T) {
let iterator = map.keys(); let iterator = map.keys();
let valueIterator = map.values(); let valueIterator = map.values();
let r: IteratorResult<T>; let r: IteratorResult<T>;
@@ -66,27 +87,6 @@ module es {
return null; return null;
} }
/**
* cameFrom字典重新构造路径
* @param cameFrom
* @param start
* @param goal
*/
public static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[]{
let path = [];
let current = goal;
path.push(goal);
while (current != start){
current = this.getKey(cameFrom, current);
path.push(current);
}
path.reverse();
return path;
}
} }
/** /**
@@ -95,7 +95,7 @@ module es {
export class AStarNode<T> extends PriorityQueueNode { export class AStarNode<T> extends PriorityQueueNode {
public data: T; public data: T;
constructor(data: T){ constructor(data: T) {
super(); super();
this.data = data; this.data = data;
} }
@@ -20,7 +20,7 @@ module es {
private _height; private _height;
private _neighbors: Vector2[] = new Array(4); private _neighbors: Vector2[] = new Array(4);
constructor(width: number, height: number){ constructor(width: number, height: number) {
this._width = width; this._width = width;
this._height = height; this._height = height;
} }
@@ -46,7 +46,7 @@ module es {
* @param start * @param start
* @param goal * @param goal
*/ */
public search(start: Vector2, goal: Vector2){ public search(start: Vector2, goal: Vector2) {
return AStarPathfinder.search(this, start, goal); return AStarPathfinder.search(this, start, goal);
} }
@@ -63,7 +63,7 @@ module es {
} }
public cost(from: Vector2, to: Vector2): number { public cost(from: Vector2, to: Vector2): number {
return this.weightedNodes.find((p)=> JSON.stringify(p) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight; return this.weightedNodes.find((p) => JSON.stringify(p) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight;
} }
public heuristic(node: Vector2, goal: Vector2) { public heuristic(node: Vector2, goal: Vector2) {
@@ -8,12 +8,14 @@ module es {
* @param node * @param node
*/ */
getNeighbors(node: T): Array<T>; getNeighbors(node: T): Array<T>;
/** /**
* from到to的成本 * from到to的成本
* @param from * @param from
* @param to * @param to
*/ */
cost(from: T, to: T): number; cost(from: T, to: T): number;
/** /**
* node到to的启发式WeightedGridGraph了解常用的Manhatten方法 * node到to的启发式WeightedGridGraph了解常用的Manhatten方法
* @param node * @param node
@@ -19,15 +19,6 @@ module es {
this._numNodesEverEnqueued = 0; this._numNodesEverEnqueued = 0;
} }
/**
*
* O(n)
*/
public clear() {
this._nodes.splice(1, this._numNodes);
this._numNodes = 0;
}
/** /**
* *
* O(1) * O(1)
@@ -44,18 +35,27 @@ module es {
return this._nodes.length - 1; return this._nodes.length - 1;
} }
/**
*
* O(n)
*/
public clear() {
this._nodes.splice(1, this._numNodes);
this._numNodes = 0;
}
/** /**
* (O(1)) * (O(1))
* O (1) * O (1)
* @param node * @param node
*/ */
public contains(node: T): boolean { public contains(node: T): boolean {
if (!node){ if (!node) {
console.error("node cannot be null"); console.error("node cannot be null");
return false; return false;
} }
if (node.queueIndex < 0 || node.queueIndex >= this._nodes.length){ if (node.queueIndex < 0 || node.queueIndex >= this._nodes.length) {
console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?"); console.error("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?");
return false; return false;
} }
@@ -3,7 +3,7 @@ module es {
* IUnweightedGraph和开始/ * IUnweightedGraph和开始/
*/ */
export class BreadthFirstPathfinder { export class BreadthFirstPathfinder {
public static search<T>(graph: IUnweightedGraph<T>, start: T, goal: T): T[]{ public static search<T>(graph: IUnweightedGraph<T>, start: T, goal: T): T[] {
let foundPath = false; let foundPath = false;
let frontier = []; let frontier = [];
frontier.unshift(start); frontier.unshift(start);
@@ -11,15 +11,15 @@ module es {
let cameFrom = new Map<T, T>(); let cameFrom = new Map<T, T>();
cameFrom.set(start, start); cameFrom.set(start, start);
while (frontier.length > 0){ while (frontier.length > 0) {
let current = frontier.shift(); let current = frontier.shift();
if (JSON.stringify(current) == JSON.stringify(goal)){ if (JSON.stringify(current) == JSON.stringify(goal)) {
foundPath = true; foundPath = true;
break; break;
} }
graph.getNeighbors(current).forEach(next => { graph.getNeighbors(current).forEach(next => {
if (!this.hasKey(cameFrom, next)){ if (!this.hasKey(cameFrom, next)) {
frontier.unshift(next); frontier.unshift(next);
cameFrom.set(next, current); cameFrom.set(next, current);
} }
@@ -29,7 +29,7 @@ module es {
return foundPath ? AStarPathfinder.recontructPath(cameFrom, start, goal) : null; return foundPath ? AStarPathfinder.recontructPath(cameFrom, start, goal) : null;
} }
private static hasKey<T>(map: Map<T, T>, compareKey: T){ private static hasKey<T>(map: Map<T, T>, compareKey: T) {
let iterator = map.keys(); let iterator = map.keys();
let r: IteratorResult<T>; let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) { while (r = iterator.next() , !r.done) {
@@ -1,5 +1,5 @@
module es { module es {
export interface IUnweightedGraph<T>{ export interface IUnweightedGraph<T> {
/** /**
* getNeighbors方法应该返回从传入的节点可以到达的任何相邻节点 * getNeighbors方法应该返回从传入的节点可以到达的任何相邻节点
* @param node * @param node
@@ -6,12 +6,12 @@ module es {
export class UnweightedGraph<T> implements IUnweightedGraph<T> { export class UnweightedGraph<T> implements IUnweightedGraph<T> {
public edges: Map<T, T[]> = new Map<T, T[]>(); public edges: Map<T, T[]> = new Map<T, T[]>();
public addEdgesForNode(node: T, edges: T[]){ public addEdgesForNode(node: T, edges: T[]) {
this.edges.set(node, edges); this.edges.set(node, edges);
return this; return this;
} }
public getNeighbors(node: T){ public getNeighbors(node: T) {
return this.edges.get(node); return this.edges.get(node);
} }
} }
@@ -1,5 +1,5 @@
module es { module es {
export interface IWeightedGraph<T>{ export interface IWeightedGraph<T> {
/** /**
* *
* @param node * @param node
@@ -32,13 +32,13 @@ module es {
private _dirs: Vector2[]; private _dirs: Vector2[];
private _neighbors: Vector2[] = new Array(4); private _neighbors: Vector2[] = new Array(4);
constructor(width: number, height: number, allowDiagonalSearch: boolean = false){ constructor(width: number, height: number, allowDiagonalSearch: boolean = false) {
this._width = width; this._width = width;
this._height = height; this._height = height;
this._dirs = allowDiagonalSearch ? WeightedGridGraph.COMPASS_DIRS : WeightedGridGraph.CARDINAL_DIRS; this._dirs = allowDiagonalSearch ? WeightedGridGraph.COMPASS_DIRS : WeightedGridGraph.CARDINAL_DIRS;
} }
public isNodeInBounds(node: Vector2){ public isNodeInBounds(node: Vector2) {
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height; return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height;
} }
@@ -46,11 +46,11 @@ module es {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node)); return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
} }
public search(start: Vector2, goal: Vector2){ public search(start: Vector2, goal: Vector2) {
return WeightedPathfinder.search(this, start, goal); return WeightedPathfinder.search(this, start, goal);
} }
public getNeighbors(node: Vector2): Vector2[]{ public getNeighbors(node: Vector2): Vector2[] {
this._neighbors.length = 0; this._neighbors.length = 0;
this._dirs.forEach(dir => { this._dirs.forEach(dir => {
@@ -62,7 +62,7 @@ module es {
return this._neighbors; return this._neighbors;
} }
public cost(from: Vector2, to: Vector2): number{ public cost(from: Vector2, to: Vector2): number {
return this.weightedNodes.find(t => JSON.stringify(t) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight; return this.weightedNodes.find(t => JSON.stringify(t) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight;
} }
} }
@@ -2,14 +2,14 @@ module es {
export class WeightedNode<T> extends PriorityQueueNode { export class WeightedNode<T> extends PriorityQueueNode {
public data: T; public data: T;
constructor(data: T){ constructor(data: T) {
super(); super();
this.data = data; this.data = data;
} }
} }
export class WeightedPathfinder { export class WeightedPathfinder {
public static search<T>(graph: IWeightedGraph<T>, start: T, goal: T){ public static search<T>(graph: IWeightedGraph<T>, start: T, goal: T) {
let foundPath = false; let foundPath = false;
let cameFrom = new Map<T, T>(); let cameFrom = new Map<T, T>();
@@ -21,17 +21,17 @@ module es {
costSoFar.set(start, 0); costSoFar.set(start, 0);
while (frontier.count > 0){ while (frontier.count > 0) {
let current = frontier.dequeue(); let current = frontier.dequeue();
if (JSON.stringify(current.data) == JSON.stringify(goal)){ if (JSON.stringify(current.data) == JSON.stringify(goal)) {
foundPath = true; foundPath = true;
break; break;
} }
graph.getNeighbors(current.data).forEach(next => { graph.getNeighbors(current.data).forEach(next => {
let newCost = costSoFar.get(current.data) + graph.cost(current.data, next); let newCost = costSoFar.get(current.data) + graph.cost(current.data, next);
if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){ if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) {
costSoFar.set(next, newCost); costSoFar.set(next, newCost);
let priprity = newCost; let priprity = newCost;
frontier.enqueue(new WeightedNode<T>(next), priprity); frontier.enqueue(new WeightedNode<T>(next), priprity);
@@ -43,7 +43,22 @@ module es {
return foundPath ? this.recontructPath(cameFrom, start, goal) : null; return foundPath ? this.recontructPath(cameFrom, start, goal) : null;
} }
private static hasKey<T>(map: Map<T, number>, compareKey: T){ public static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[] {
let path = [];
let current = goal;
path.push(goal);
while (current != start) {
current = this.getKey(cameFrom, current);
path.push(current);
}
path.reverse();
return path;
}
private static hasKey<T>(map: Map<T, number>, compareKey: T) {
let iterator = map.keys(); let iterator = map.keys();
let r: IteratorResult<T>; let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) { while (r = iterator.next() , !r.done) {
@@ -54,7 +69,7 @@ module es {
return false; return false;
} }
private static getKey<T>(map: Map<T, T>, compareKey: T){ private static getKey<T>(map: Map<T, T>, compareKey: T) {
let iterator = map.keys(); let iterator = map.keys();
let valueIterator = map.values(); let valueIterator = map.values();
let r: IteratorResult<T>; let r: IteratorResult<T>;
@@ -66,20 +81,5 @@ module es {
return null; return null;
} }
public static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[]{
let path = [];
let current = goal;
path.push(goal);
while (current != start){
current = this.getKey(cameFrom, current);
path.push(current);
}
path.reverse();
return path;
}
} }
} }
+5 -5
View File
@@ -2,18 +2,18 @@ module es {
export class Debug { export class Debug {
private static _debugDrawItems: DebugDrawItem[] = []; private static _debugDrawItems: DebugDrawItem[] = [];
public static drawHollowRect(rectanle: Rectangle, color: number, duration = 0){ public static drawHollowRect(rectanle: Rectangle, color: number, duration = 0) {
this._debugDrawItems.push(new DebugDrawItem(rectanle, color, duration)); this._debugDrawItems.push(new DebugDrawItem(rectanle, color, duration));
} }
public static render(){ public static render() {
if (this._debugDrawItems.length > 0){ if (this._debugDrawItems.length > 0) {
let debugShape = new egret.Shape(); let debugShape = new egret.Shape();
if (Core.scene){ if (Core.scene) {
Core.scene.addChild(debugShape); Core.scene.addChild(debugShape);
} }
for (let i = this._debugDrawItems.length - 1; i >= 0; i --){ for (let i = this._debugDrawItems.length - 1; i >= 0; i--) {
let item = this._debugDrawItems[i]; let item = this._debugDrawItems[i];
if (item.draw(debugShape)) if (item.draw(debugShape))
this._debugDrawItems.removeAt(i); this._debugDrawItems.removeAt(i);
+3 -3
View File
@@ -18,15 +18,15 @@ module es {
public y: number; public y: number;
public size: number; public size: number;
constructor(rectangle: Rectangle, color: number, duration: number){ constructor(rectangle: Rectangle, color: number, duration: number) {
this.rectangle = rectangle; this.rectangle = rectangle;
this.color = color; this.color = color;
this.duration = duration; this.duration = duration;
this.drawType = DebugDrawType.hollowRectangle; this.drawType = DebugDrawType.hollowRectangle;
} }
public draw(shape: egret.Shape): boolean{ public draw(shape: egret.Shape): boolean {
switch (this.drawType){ switch (this.drawType) {
case DebugDrawType.line: case DebugDrawType.line:
DrawUtils.drawLine(shape, this.start, this.end, this.color); DrawUtils.drawLine(shape, this.start, this.end, this.color);
break; break;
+8 -8
View File
@@ -12,6 +12,10 @@ module es {
* *
*/ */
public entity: Entity; public entity: Entity;
/**
*
*/
public updateInterval: number = 1;
/** /**
* 访 this.entity.transform * 访 this.entity.transform
@@ -20,6 +24,8 @@ module es {
return this.entity.transform; return this.entity.transform;
} }
private _enabled: boolean = true;
/** /**
* onEnabled/onDisable * onEnabled/onDisable
*/ */
@@ -35,6 +41,8 @@ module es {
this.setEnabled(value); this.setEnabled(value);
} }
private _updateOrder = 0;
/** 更新此实体上组件的顺序 */ /** 更新此实体上组件的顺序 */
public get updateOrder() { public get updateOrder() {
return this._updateOrder; return this._updateOrder;
@@ -45,14 +53,6 @@ module es {
this.setUpdateOrder(value); this.setUpdateOrder(value);
} }
/**
*
*/
public updateInterval: number = 1;
private _enabled: boolean = true;
private _updateOrder = 0;
/** /**
* 西访 * 西访
*/ */
+87 -83
View File
@@ -12,6 +12,46 @@ module es {
} }
export class Camera extends Component { export class Camera extends Component {
public _inset: CameraInset = new CameraInset();
public _areMatrixedDirty: boolean = true;
public _areBoundsDirty: boolean = true;
public _isProjectionMatrixDirty = true;
/**
* cameraWindow
*
*/
public followLerp = 0.1;
/**
* cameraWindow模式下/
* lockOn模式下使deadZone的x/y值 setCenteredDeadzone重写它来自定义deadZone
*/
public deadzone: Rectangle = new Rectangle();
/**
*
*/
public focusOffset: Vector2 = Vector2.zero;
/**
* true 0, 0, mapwidth, mapheight
*/
public mapLockEnabled: boolean = false;
/**
*
*/
public mapSize: Vector2 = Vector2.zero;
public _targetEntity: Entity;
public _targetCollider: Collider;
public _desiredPositionDelta: Vector2 = new Vector2();
public _cameraStyle: CameraStyle;
public _worldSpaceDeadZone: Rectangle = new Rectangle();
constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) {
super();
this._targetEntity = targetEntity;
this._cameraStyle = cameraStyle;
this.setZoom(0);
}
/** /**
* entity.transform.position的快速访问 * entity.transform.position的快速访问
*/ */
@@ -42,6 +82,8 @@ module es {
this.entity.transform.rotation = value; this.entity.transform.rotation = value;
} }
public _zoom;
/** /**
* -11minimumZoom转换为maximumZoom * -11minimumZoom转换为maximumZoom
* /使-11 * /使-11
@@ -65,6 +107,8 @@ module es {
this.setZoom(value); this.setZoom(value);
} }
public _minimumZoom = 0.3;
/** /**
* 0-number.max0.3 * 0-number.max0.3
*/ */
@@ -80,6 +124,8 @@ module es {
this.setMinimumZoom(value); this.setMinimumZoom(value);
} }
public _maximumZoom = 3;
/** /**
* 0-number.max3 * 0-number.max3
*/ */
@@ -95,20 +141,22 @@ module es {
this.setMaximumZoom(value); this.setMaximumZoom(value);
} }
public _bounds: Rectangle = new Rectangle();
/** /**
* - * -
*/ */
public get bounds(){ public get bounds() {
if (this._areMatrixedDirty) if (this._areMatrixedDirty)
this.updateMatrixes(); this.updateMatrixes();
if (this._areBoundsDirty){ if (this._areBoundsDirty) {
// 旋转或非旋转的边界都需要左上角和右下角 // 旋转或非旋转的边界都需要左上角和右下角
let topLeft = this.screenToWorldPoint(new Vector2(this._inset.left, this._inset.top)); let topLeft = this.screenToWorldPoint(new Vector2(this._inset.left, this._inset.top));
let bottomRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right, let bottomRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right,
Core.graphicsDevice.viewport.height - this._inset.bottom)); Core.graphicsDevice.viewport.height - this._inset.bottom));
if (this.entity.transform.rotation != 0){ if (this.entity.transform.rotation != 0) {
// 特别注意旋转的边界。我们需要找到绝对的最小/最大值并从中创建边界 // 特别注意旋转的边界。我们需要找到绝对的最小/最大值并从中创建边界
let topRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right, let topRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right,
this._inset.top)); this._inset.top));
@@ -135,6 +183,8 @@ module es {
return this._bounds; return this._bounds;
} }
public _transformMatrix: Matrix2D = new Matrix2D().identity();
/** /**
* *
*/ */
@@ -144,6 +194,8 @@ module es {
return this._transformMatrix; return this._transformMatrix;
} }
public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity();
/** /**
* *
*/ */
@@ -153,6 +205,8 @@ module es {
return this._inverseTransformMatrix; return this._inverseTransformMatrix;
} }
public _origin: Vector2 = Vector2.zero;
public get origin() { public get origin() {
return this._origin; return this._origin;
} }
@@ -164,56 +218,6 @@ module es {
} }
} }
public _zoom;
public _minimumZoom = 0.3;
public _maximumZoom = 3;
public _bounds: Rectangle = new Rectangle();
public _inset: CameraInset = new CameraInset();
public _transformMatrix: Matrix2D = new Matrix2D().identity();
public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity();
public _origin: Vector2 = Vector2.zero;
public _areMatrixedDirty: boolean = true;
public _areBoundsDirty: boolean = true;
public _isProjectionMatrixDirty = true;
/**
* cameraWindow
*
*/
public followLerp = 0.1;
/**
* cameraWindow模式下/
* lockOn模式下使deadZone的x/y值 setCenteredDeadzone重写它来自定义deadZone
*/
public deadzone: Rectangle = new Rectangle();
/**
*
*/
public focusOffset: Vector2 = Vector2.zero;
/**
* true 0, 0, mapwidth, mapheight
*/
public mapLockEnabled: boolean = false;
/**
*
*/
public mapSize: Vector2 = Vector2.zero;
public _targetEntity: Entity;
public _targetCollider: Collider;
public _desiredPositionDelta: Vector2 = new Vector2();
public _cameraStyle: CameraStyle;
public _worldSpaceDeadZone: Rectangle = new Rectangle();
constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) {
super();
this._targetEntity = targetEntity;
this._cameraStyle = cameraStyle;
this.setZoom(0);
}
/** /**
* *
* @param newWidth * @param newWidth
@@ -226,33 +230,6 @@ module es {
this.entity.transform.position = Vector2.add(this.entity.transform.position, Vector2.subtract(this._origin, oldOrigin)); this.entity.transform.position = Vector2.add(this.entity.transform.position, Vector2.subtract(this._origin, oldOrigin));
} }
protected updateMatrixes(){
if (!this._areMatrixedDirty)
return;
let tempMat: Matrix2D;
this._transformMatrix = Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y);
if (this._zoom != 1){
tempMat = Matrix2D.create().scale(this._zoom, this._zoom);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
if (this.entity.transform.rotation != 0){
tempMat = Matrix2D.create().rotate(this.entity.transform.rotation);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
tempMat = Matrix2D.create().translate(this._origin.x, this._origin.y);
this._transformMatrix =this._transformMatrix.multiply(tempMat);
this._inverseTransformMatrix = this._transformMatrix.invert();
// 无论何时矩阵改变边界都是无效的
this._areBoundsDirty = true;
this._areMatrixedDirty = false;
}
/** /**
* *
* @param left * @param left
@@ -357,7 +334,7 @@ module es {
* *
* @param worldPosition * @param worldPosition
*/ */
public worldToScreenPoint(worldPosition: Vector2): Vector2{ public worldToScreenPoint(worldPosition: Vector2): Vector2 {
this.updateMatrixes(); this.updateMatrixes();
worldPosition = Vector2.transform(worldPosition, this._transformMatrix); worldPosition = Vector2.transform(worldPosition, this._transformMatrix);
return worldPosition; return worldPosition;
@@ -367,7 +344,7 @@ module es {
* *
* @param screenPosition * @param screenPosition
*/ */
public screenToWorldPoint(screenPosition: Vector2): Vector2{ public screenToWorldPoint(screenPosition: Vector2): Vector2 {
this.updateMatrixes(); this.updateMatrixes();
screenPosition = Vector2.transform(screenPosition, this._inverseTransformMatrix); screenPosition = Vector2.transform(screenPosition, this._inverseTransformMatrix);
return screenPosition; return screenPosition;
@@ -376,7 +353,7 @@ module es {
/** /**
* *
*/ */
public mouseToWorldPoint(): Vector2{ public mouseToWorldPoint(): Vector2 {
return this.screenToWorldPoint(Input.touchPosition); return this.screenToWorldPoint(Input.touchPosition);
} }
@@ -476,5 +453,32 @@ module es {
public setCenteredDeadzone(width: number, height: number) { public setCenteredDeadzone(width: number, height: number) {
this.deadzone = new Rectangle((this.bounds.width - width) / 2, (this.bounds.height - height) / 2, width, height); this.deadzone = new Rectangle((this.bounds.width - width) / 2, (this.bounds.height - height) / 2, width, height);
} }
protected updateMatrixes() {
if (!this._areMatrixedDirty)
return;
let tempMat: Matrix2D;
this._transformMatrix = Matrix2D.create().translate(-this.entity.transform.position.x, -this.entity.transform.position.y);
if (this._zoom != 1) {
tempMat = Matrix2D.create().scale(this._zoom, this._zoom);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
if (this.entity.transform.rotation != 0) {
tempMat = Matrix2D.create().rotate(this.entity.transform.rotation);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
}
tempMat = Matrix2D.create().translate(this._origin.x, this._origin.y);
this._transformMatrix = this._transformMatrix.multiply(tempMat);
this._inverseTransformMatrix = this._transformMatrix.invert();
// 无论何时矩阵改变边界都是无效的
this._areBoundsDirty = true;
this._areMatrixedDirty = false;
}
} }
} }
+5 -5
View File
@@ -1,22 +1,22 @@
module es { module es {
export class ComponentPool<T extends PooledComponent>{ export class ComponentPool<T extends PooledComponent> {
private _cache: T[]; private _cache: T[];
private _type: any; private _type: any;
constructor(typeClass: any){ constructor(typeClass: any) {
this._type = typeClass; this._type = typeClass;
this._cache = []; this._cache = [];
} }
public obtain(): T{ public obtain(): T {
try { try {
return this._cache.length > 0 ? this._cache.shift() : new this._type(); return this._cache.length > 0 ? this._cache.shift() : new this._type();
} catch(err){ } catch (err) {
throw new Error(this._type + err); throw new Error(this._type + err);
} }
} }
public free(component: T){ public free(component: T) {
component.reset(); component.reset();
this._cache.push(component); this._cache.push(component);
} }
@@ -3,8 +3,8 @@ module es {
* *
*/ */
export class IUpdatableComparer { export class IUpdatableComparer {
public compare(a: Component, b: Component){ public compare(a: Component, b: Component) {
return a.updateOrder - b.updateOrder; return a.updateOrder - b.updateOrder;
} }
} }
} }
+2 -2
View File
@@ -3,13 +3,13 @@ module es {
export class Mesh extends RenderableComponent { export class Mesh extends RenderableComponent {
private _mesh: egret.Mesh; private _mesh: egret.Mesh;
constructor(){ constructor() {
super(); super();
this._mesh = new egret.Mesh(); this._mesh = new egret.Mesh();
} }
public setTexture(texture: egret.Texture): Mesh{ public setTexture(texture: egret.Texture): Mesh {
this._mesh.texture = texture; this._mesh.texture = texture;
return this; return this;
@@ -1,26 +1,10 @@
///<reference path="./Collider.ts" /> ///<reference path="./Collider.ts" />
module es { module es {
export class BoxCollider extends Collider { export class BoxCollider extends Collider {
public get width(){
return (this.shape as Box).width;
}
public set width(value: number){
this.setWidth(value);
}
public get height(){
return (this.shape as Box).height;
}
public set height(value: number){
this.setHeight(value);
}
/** /**
* RenderableComponent在实体上 * RenderableComponent在实体上
*/ */
constructor(){ constructor() {
super(); super();
// 我们在这里插入一个1x1框作为占位符,直到碰撞器在下一阵被添加到实体并可以获得更精确的自动调整大小数据 // 我们在这里插入一个1x1框作为占位符,直到碰撞器在下一阵被添加到实体并可以获得更精确的自动调整大小数据
@@ -28,15 +12,31 @@ module es {
this._colliderRequiresAutoSizing = true; this._colliderRequiresAutoSizing = true;
} }
public get width() {
return (this.shape as Box).width;
}
public set width(value: number) {
this.setWidth(value);
}
public get height() {
return (this.shape as Box).height;
}
public set height(value: number) {
this.setHeight(value);
}
/** /**
* BoxCollider的大小 * BoxCollider的大小
* @param width * @param width
* @param height * @param height
*/ */
public setSize(width: number, height: number){ public setSize(width: number, height: number) {
this._colliderRequiresAutoSizing = false; this._colliderRequiresAutoSizing = false;
let box = this.shape as Box; let box = this.shape as Box;
if (width != box.width || height != box.height){ if (width != box.width || height != box.height) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界 // 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, height); box.updateBox(width, height);
if (this.entity && this._isParentEntityAddedToScene) if (this.entity && this._isParentEntityAddedToScene)
@@ -50,10 +50,10 @@ module es {
* BoxCollider的宽度 * BoxCollider的宽度
* @param width * @param width
*/ */
public setWidth(width: number): BoxCollider{ public setWidth(width: number): BoxCollider {
this._colliderRequiresAutoSizing = false; this._colliderRequiresAutoSizing = false;
let box = this.shape as Box; let box = this.shape as Box;
if (width != box.width){ if (width != box.width) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界 // 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, box.height); box.updateBox(width, box.height);
if (this.entity && this._isParentEntityAddedToScene) if (this.entity && this._isParentEntityAddedToScene)
@@ -67,10 +67,10 @@ module es {
* BoxCollider的高度 * BoxCollider的高度
* @param height * @param height
*/ */
public setHeight(height: number){ public setHeight(height: number) {
this._colliderRequiresAutoSizing = false; this._colliderRequiresAutoSizing = false;
let box = this.shape as Box; let box = this.shape as Box;
if (height != box.height){ if (height != box.height) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界 // 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(box.width, height); box.updateBox(box.width, height);
if (this.entity && this._isParentEntityAddedToScene) if (this.entity && this._isParentEntityAddedToScene)
@@ -78,7 +78,7 @@ module es {
} }
} }
public toString(){ public toString() {
return `[BoxCollider: bounds: ${this.bounds}]`; return `[BoxCollider: bounds: ${this.bounds}]`;
} }
} }
@@ -1,13 +1,5 @@
module es { module es {
export class CircleCollider extends Collider { export class CircleCollider extends Collider {
public get radius(): number {
return (this.shape as Circle).radius;
}
public set radius(value: number) {
this.setRadius(value);
}
/** /**
* *
* *
@@ -23,6 +15,14 @@ module es {
this.shape = new Circle(radius ? radius : 1); this.shape = new Circle(radius ? radius : 1);
} }
public get radius(): number {
return (this.shape as Circle).radius;
}
public set radius(value: number) {
this.setRadius(value);
}
/** /**
* *
* @param radius * @param radius
@@ -4,23 +4,40 @@ module es {
* *
*/ */
public shape: Shape; public shape: Shape;
/** /**
* localOffset添加到实体 *
* /
*/ */
public get localOffset(): Vector2 { public isTrigger: boolean;
return this._localOffset;
}
/** /**
* localOffset添加到实体 * physicsLayer可以用作过滤器Flags类有帮助位掩码的方法
* /
* @param value
*/ */
public set localOffset(value: Vector2) { public physicsLayer = 1 << 0;
this.setLocalOffset(value); /**
} * 使
*
*/
public collidesWithLayers = Physics.allLayers;
/**
* true
*/
public shouldColliderScaleAndRotateWithTransform = true;
/**
*
* 使
*/
public registeredPhysicsBounds: Rectangle = new Rectangle();
public _localOffsetLength: number;
public _isPositionDirty: boolean = true;
public _isRotationDirty: boolean = true;
protected _colliderRequiresAutoSizing;
/**
*
*/
protected _isParentEntityAddedToScene;
/**
*
*/
protected _isColliderRegistered;
/** /**
* *
@@ -39,27 +56,8 @@ module es {
return 0; return 0;
} }
/**
*
*/
public isTrigger: boolean;
/**
* physicsLayer可以用作过滤器Flags类有帮助位掩码的方法
*/
public physicsLayer = 1 << 0;
/**
* 使
*
*/
public collidesWithLayers = Physics.allLayers;
/**
* true
*/
public shouldColliderScaleAndRotateWithTransform = true;
public get bounds(): Rectangle { public get bounds(): Rectangle {
if (this._isPositionDirty || this._isRotationDirty){ if (this._isPositionDirty || this._isRotationDirty) {
this.shape.recalculateBounds(this); this.shape.recalculateBounds(this);
this._isPositionDirty = this._isRotationDirty = false; this._isPositionDirty = this._isRotationDirty = false;
} }
@@ -67,26 +65,24 @@ module es {
return this.shape.bounds; return this.shape.bounds;
} }
/**
*
* 使
*/
public registeredPhysicsBounds: Rectangle = new Rectangle();
protected _colliderRequiresAutoSizing;
protected _localOffset: Vector2 = Vector2.zero; protected _localOffset: Vector2 = Vector2.zero;
public _localOffsetLength: number;
/** /**
* * localOffset添加到实体
* /
*/ */
protected _isParentEntityAddedToScene; public get localOffset(): Vector2 {
/** return this._localOffset;
* }
*/
protected _isColliderRegistered;
public _isPositionDirty: boolean = true; /**
public _isRotationDirty: boolean = true; * localOffset添加到实体
* /
* @param value
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
/** /**
* localOffset添加到实体 * localOffset添加到实体
@@ -229,7 +225,7 @@ module es {
return didCollide; return didCollide;
} }
public clone(): Component{ public clone(): Component {
let collider = ObjectUtils.clone<Collider>(this); let collider = ObjectUtils.clone<Collider>(this);
collider.entity = null; collider.entity = null;
@@ -1,4 +1,4 @@
module es{ module es {
/** /**
* /退 * /退
* ITriggerListener方法将在实现接口的触发器实体上的任何组件上调用 * ITriggerListener方法将在实现接口的触发器实体上的任何组件上调用
+9 -9
View File
@@ -9,7 +9,7 @@ module es {
export class Mover extends Component { export class Mover extends Component {
private _triggerHelper: ColliderTriggerHelper; private _triggerHelper: ColliderTriggerHelper;
public onAddedToEntity(){ public onAddedToEntity() {
this._triggerHelper = new ColliderTriggerHelper(this.entity); this._triggerHelper = new ColliderTriggerHelper(this.entity);
} }
@@ -18,14 +18,14 @@ module es {
* @param motion * @param motion
* @param collisionResult * @param collisionResult
*/ */
public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean{ public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean {
if (!this.entity.getComponent(Collider) || !this._triggerHelper){ if (!this.entity.getComponent(Collider) || !this._triggerHelper) {
return false; return false;
} }
// 移动所有的非触发碰撞器并获得最近的碰撞 // 移动所有的非触发碰撞器并获得最近的碰撞
let colliders: Collider[] = this.entity.getComponents(Collider); let colliders: Collider[] = this.entity.getComponents(Collider);
for (let i = 0; i < colliders.length; i ++){ for (let i = 0; i < colliders.length; i++) {
let collider = colliders[i]; let collider = colliders[i];
// 不检测触发器 在我们移动后会重新访问它 // 不检测触发器 在我们移动后会重新访问它
@@ -38,19 +38,19 @@ module es {
bounds.y += motion.y; bounds.y += motion.y;
let neighbors = Physics.boxcastBroadphaseExcludingSelf(collider, bounds, collider.collidesWithLayers); let neighbors = Physics.boxcastBroadphaseExcludingSelf(collider, bounds, collider.collidesWithLayers);
for (let j = 0; j < neighbors.length; j ++){ for (let j = 0; j < neighbors.length; j++) {
let neighbor = neighbors[j]; let neighbor = neighbors[j];
// 不检测触发器 // 不检测触发器
if (neighbor.isTrigger) if (neighbor.isTrigger)
continue; continue;
let _internalcollisionResult: CollisionResult = new CollisionResult(); let _internalcollisionResult: CollisionResult = new CollisionResult();
if (collider.collidesWith(neighbor, motion, _internalcollisionResult)){ if (collider.collidesWith(neighbor, motion, _internalcollisionResult)) {
// 如果碰撞 则退回之前的移动量 // 如果碰撞 则退回之前的移动量
motion = motion.subtract(_internalcollisionResult.minimumTranslationVector); motion = motion.subtract(_internalcollisionResult.minimumTranslationVector);
// 如果我们碰到多个对象,为了简单起见,只取第一个。 // 如果我们碰到多个对象,为了简单起见,只取第一个。
if (_internalcollisionResult.collider != null){ if (_internalcollisionResult.collider != null) {
collisionResult = _internalcollisionResult; collisionResult = _internalcollisionResult;
} }
} }
@@ -66,7 +66,7 @@ module es {
* calculatemomovement应用到实体并更新triggerHelper * calculatemomovement应用到实体并更新triggerHelper
* @param motion * @param motion
*/ */
public applyMovement(motion: Vector2){ public applyMovement(motion: Vector2) {
// 移动实体到它的新位置,如果我们有一个碰撞,否则移动全部数量。当碰撞发生时,运动被更新 // 移动实体到它的新位置,如果我们有一个碰撞,否则移动全部数量。当碰撞发生时,运动被更新
this.entity.position = Vector2.add(this.entity.position, motion); this.entity.position = Vector2.add(this.entity.position, motion);
@@ -80,7 +80,7 @@ module es {
* @param motion * @param motion
* @param collisionResult * @param collisionResult
*/ */
public move(motion: Vector2, collisionResult: CollisionResult){ public move(motion: Vector2, collisionResult: CollisionResult) {
this.calculateMovement(motion, collisionResult); this.calculateMovement(motion, collisionResult);
this.applyMovement(motion); this.applyMovement(motion);
return collisionResult.collider != null; return collisionResult.collider != null;
@@ -7,7 +7,7 @@ module es {
private _tempTriggerList: ITriggerListener[] = []; private _tempTriggerList: ITriggerListener[] = [];
private _collider: Collider; private _collider: Collider;
public onAddedToEntity(){ public onAddedToEntity() {
this._collider = this.entity.getComponent<Collider>(Collider); this._collider = this.entity.getComponent<Collider>(Collider);
if (!this._collider) if (!this._collider)
console.warn("ProjectileMover has no Collider. ProjectilMover requires a Collider!"); console.warn("ProjectileMover has no Collider. ProjectilMover requires a Collider!");
@@ -17,7 +17,7 @@ module es {
* *
* @param motion * @param motion
*/ */
public move(motion: Vector2): boolean{ public move(motion: Vector2): boolean {
if (!this._collider) if (!this._collider)
return false; return false;
@@ -28,9 +28,9 @@ module es {
// 获取任何可能在新位置发生碰撞的东西 // 获取任何可能在新位置发生碰撞的东西
let neighbors = Physics.boxcastBroadphase(this._collider.bounds, this._collider.collidesWithLayers); let neighbors = Physics.boxcastBroadphase(this._collider.bounds, this._collider.collidesWithLayers);
for (let i = 0; i < neighbors.length; i ++){ for (let i = 0; i < neighbors.length; i++) {
let neighbor = neighbors[i]; let neighbor = neighbors[i];
if (this._collider.overlaps(neighbor) && neighbor.enabled){ if (this._collider.overlaps(neighbor) && neighbor.enabled) {
didCollide = true; didCollide = true;
this.notifyTriggerListeners(this._collider, neighbor); this.notifyTriggerListeners(this._collider, neighbor);
} }
@@ -39,17 +39,17 @@ module es {
return didCollide; return didCollide;
} }
private notifyTriggerListeners(self: Collider, other: Collider){ private notifyTriggerListeners(self: Collider, other: Collider) {
// 通知我们重叠的碰撞器实体上的任何侦听器 // 通知我们重叠的碰撞器实体上的任何侦听器
other.entity.getComponents("ITriggerListener", this._tempTriggerList); other.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i ++){ for (let i = 0; i < this._tempTriggerList.length; i++) {
this._tempTriggerList[i].onTriggerEnter(self, other); this._tempTriggerList[i].onTriggerEnter(self, other);
} }
this._tempTriggerList.length = 0; this._tempTriggerList.length = 0;
// 通知此实体上的任何侦听器 // 通知此实体上的任何侦听器
this.entity.getComponents("ITriggerListener", this._tempTriggerList); this.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i ++){ for (let i = 0; i < this._tempTriggerList.length; i++) {
this._tempTriggerList[i].onTriggerEnter(other, self); this._tempTriggerList[i].onTriggerEnter(other, self);
} }
this._tempTriggerList.length = 0; this._tempTriggerList.length = 0;
@@ -8,6 +8,12 @@ module es {
* egret显示对象 * egret显示对象
*/ */
public displayObject: egret.DisplayObject = new egret.DisplayObject(); public displayObject: egret.DisplayObject = new egret.DisplayObject();
/**
*
*/
public color: number = 0x000000;
protected _areBoundsDirty = true;
/** /**
* renderableComponent的宽度 * renderableComponent的宽度
* bounds属性则需要实现这个 * bounds属性则需要实现这个
@@ -24,11 +30,43 @@ module es {
return this.bounds.height; return this.bounds.height;
} }
protected _localOffset: Vector2 = Vector2.zero;
/**
*
*/
public get localOffset(): Vector2 {
return this._localOffset;
}
/**
*
* @param value
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
protected _renderLayer: number = 0;
/**
*
*/
public get renderLayer(): number {
return this._renderLayer;
}
public set renderLayer(value: number) {
}
protected _bounds: Rectangle = new Rectangle();
/** /**
* AABB, * AABB,
*/ */
public get bounds(): Rectangle { public get bounds(): Rectangle {
if (this._areBoundsDirty){ if (this._areBoundsDirty) {
this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, Vector2.zero, this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, Vector2.zero,
this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height); this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height);
this._areBoundsDirty = false; this._areBoundsDirty = false;
@@ -37,36 +75,7 @@ module es {
return this._bounds; return this._bounds;
} }
/** private _isVisible: boolean;
*
*/
public get renderLayer(): number{
return this._renderLayer;
}
public set renderLayer(value: number){
}
/**
*
*/
public color: number = 0x000000;
/**
*
*/
public get localOffset(): Vector2{
return this._localOffset;
}
/**
*
* @param value
*/
public set localOffset(value: Vector2){
this.setLocalOffset(value);
}
/** /**
* onBecameVisible/onBecameInvisible方法 * onBecameVisible/onBecameInvisible方法
@@ -80,7 +89,7 @@ module es {
* @param value * @param value
*/ */
public set isVisible(value: boolean) { public set isVisible(value: boolean) {
if (this._isVisible != value){ if (this._isVisible != value) {
this._isVisible = value; this._isVisible = value;
if (this._isVisible) if (this._isVisible)
@@ -90,12 +99,6 @@ module es {
} }
} }
protected _localOffset: Vector2 = Vector2.zero;
protected _renderLayer: number = 0;
protected _bounds: Rectangle = new Rectangle();
private _isVisible: boolean;
protected _areBoundsDirty = true;
public onEntityTransformChanged(comp: transform.Component) { public onEntityTransformChanged(comp: transform.Component) {
this._areBoundsDirty = true; this._areBoundsDirty = true;
} }
@@ -106,22 +109,6 @@ module es {
*/ */
public abstract render(camera: Camera); public abstract render(camera: Camera);
/**
* renderableComponent进入相机框架时调用
* isVisibleFromCamera进行剔除检查
*/
protected onBecameVisible() {
this.displayObject.visible = this.isVisible;
}
/**
* renderableComponent离开相机框架时调用
* isVisibleFromCamera进行剔除检查
*/
protected onBecameInvisible() {
this.displayObject.visible = this.isVisible;
}
/** /**
* renderableComponent的边界与camera.bounds相交 true * renderableComponent的边界与camera.bounds相交 true
* isVisible标志的状态开关 * isVisible标志的状态开关
@@ -137,8 +124,8 @@ module es {
* *
* @param renderLayer * @param renderLayer
*/ */
public setRenderLayer(renderLayer: number): RenderableComponent{ public setRenderLayer(renderLayer: number): RenderableComponent {
if (renderLayer != this._renderLayer){ if (renderLayer != this._renderLayer) {
let oldRenderLayer = this._renderLayer; let oldRenderLayer = this._renderLayer;
this._renderLayer = renderLayer; this._renderLayer = renderLayer;
@@ -154,7 +141,7 @@ module es {
* *
* @param color * @param color
*/ */
public setColor(color: number): RenderableComponent{ public setColor(color: number): RenderableComponent {
this.color = color; this.color = color;
return this; return this;
} }
@@ -163,8 +150,8 @@ module es {
* *
* @param offset * @param offset
*/ */
public setLocalOffset(offset: Vector2): RenderableComponent{ public setLocalOffset(offset: Vector2): RenderableComponent {
if (this._localOffset != offset){ if (this._localOffset != offset) {
this._localOffset = offset; this._localOffset = offset;
} }
@@ -174,7 +161,7 @@ module es {
/** /**
* *
*/ */
public sync(camera: Camera){ public sync(camera: Camera) {
this.displayObject.x = this.entity.position.x + this.localOffset.x - camera.position.x + camera.origin.x; this.displayObject.x = this.entity.position.x + this.localOffset.x - camera.position.x + camera.origin.x;
this.displayObject.y = this.entity.position.y + this.localOffset.y - camera.position.y + camera.origin.y; this.displayObject.y = this.entity.position.y + this.localOffset.y - camera.position.y + camera.origin.y;
this.displayObject.scaleX = this.entity.scale.x; this.displayObject.scaleX = this.entity.scale.x;
@@ -182,8 +169,24 @@ module es {
this.displayObject.rotation = this.entity.rotation; this.displayObject.rotation = this.entity.rotation;
} }
public toString(){ public toString() {
return `[RenderableComponent] renderLayer: ${this.renderLayer}`; return `[RenderableComponent] renderLayer: ${this.renderLayer}`;
} }
/**
* renderableComponent进入相机框架时调用
* isVisibleFromCamera进行剔除检查
*/
protected onBecameVisible() {
this.displayObject.visible = this.isVisible;
}
/**
* renderableComponent离开相机框架时调用
* isVisibleFromCamera进行剔除检查
*/
protected onBecameInvisible() {
this.displayObject.visible = this.isVisible;
}
} }
} }
@@ -6,7 +6,7 @@ module es {
private _scrollX = 0; private _scrollX = 0;
private _scrollY = 0; private _scrollY = 0;
public update(){ public update() {
this._scrollX += this.scrollSpeedX * Time.deltaTime; this._scrollX += this.scrollSpeedX * Time.deltaTime;
this._scrollY += this.scroolSpeedY * Time.deltaTime; this._scrollY += this.scroolSpeedY * Time.deltaTime;
this.sourceRect.x = this._scrollX; this.sourceRect.x = this._scrollX;
+1 -1
View File
@@ -3,7 +3,7 @@ module es {
public readonly sprites: Sprite[]; public readonly sprites: Sprite[];
public readonly frameRate: number; public readonly frameRate: number;
constructor(sprites: Sprite[], frameRate: number){ constructor(sprites: Sprite[], frameRate: number) {
this.sprites = sprites; this.sprites = sprites;
this.frameRate = frameRate; this.frameRate = frameRate;
} }
+8 -8
View File
@@ -45,6 +45,12 @@ module es {
* *
*/ */
public currentFrame: number; public currentFrame: number;
public _elapsedTime: number = 0;
public _loopMode: LoopMode;
constructor(sprite?: Sprite) {
super(sprite);
}
/** /**
* *
@@ -53,19 +59,13 @@ module es {
return this.animationState == State.running; return this.animationState == State.running;
} }
private _animations: Map<string, SpriteAnimation> = new Map<string, SpriteAnimation>();
/** 提供对可用动画列表的访问 */ /** 提供对可用动画列表的访问 */
public get animations() { public get animations() {
return this._animations; return this._animations;
} }
private _animations: Map<string, SpriteAnimation> = new Map<string, SpriteAnimation>();
public _elapsedTime: number = 0;
public _loopMode: LoopMode;
constructor(sprite?: Sprite) {
super(sprite);
}
public update() { public update() {
if (this.animationState != State.running || !this.currentAnimation) return; if (this.animationState != State.running || !this.currentAnimation) return;
+27 -26
View File
@@ -2,6 +2,14 @@ module es {
import Bitmap = egret.Bitmap; import Bitmap = egret.Bitmap;
export class SpriteRenderer extends RenderableComponent { export class SpriteRenderer extends RenderableComponent {
constructor(sprite: Sprite | egret.Texture = null) {
super();
if (sprite instanceof Sprite)
this.setSprite(sprite);
else if (sprite instanceof egret.Texture)
this.setSprite(new Sprite(sprite));
}
public get bounds() { public get bounds() {
if (this._areBoundsDirty) { if (this._areBoundsDirty) {
if (this._sprite) { if (this._sprite) {
@@ -15,21 +23,6 @@ module es {
return this._bounds; return this._bounds;
} }
/**
*
*/
public get origin(): Vector2 {
return this._origin;
}
/**
*
* @param value
*/
public set origin(value: Vector2) {
this.setOrigin(value);
}
/** /**
* *
* x/y 0-1 * x/y 0-1
@@ -49,6 +42,25 @@ module es {
value.y * this.height / this.entity.transform.scale.y)); value.y * this.height / this.entity.transform.scale.y));
} }
protected _origin: Vector2;
/**
*
*/
public get origin(): Vector2 {
return this._origin;
}
/**
*
* @param value
*/
public set origin(value: Vector2) {
this.setOrigin(value);
}
protected _sprite: Sprite;
/** /**
* *
* origin * origin
@@ -66,17 +78,6 @@ module es {
this.setSprite(value); this.setSprite(value);
} }
protected _origin: Vector2;
protected _sprite: Sprite;
constructor(sprite: Sprite | egret.Texture = null) {
super();
if (sprite instanceof Sprite)
this.setSprite(sprite);
else if (sprite instanceof egret.Texture)
this.setSprite(new Sprite(sprite));
}
/** /**
* sprite.origin * sprite.origin
* @param sprite * @param sprite
@@ -8,19 +8,6 @@ module es {
protected leftTexture: egret.Bitmap; protected leftTexture: egret.Bitmap;
protected rightTexture: egret.Bitmap; protected rightTexture: egret.Bitmap;
public get scrollX() {
return this.sourceRect.x;
}
public set scrollX(value: number) {
this.sourceRect.x = value;
}
public get scrollY() {
return this.sourceRect.y;
}
public set scrollY(value: number) {
this.sourceRect.y = value;
}
constructor(sprite: Sprite) { constructor(sprite: Sprite) {
super(sprite); super(sprite);
@@ -33,6 +20,22 @@ module es {
this.sourceRect = sprite.sourceRect; this.sourceRect = sprite.sourceRect;
} }
public get scrollX() {
return this.sourceRect.x;
}
public set scrollX(value: number) {
this.sourceRect.x = value;
}
public get scrollY() {
return this.sourceRect.y;
}
public set scrollY(value: number) {
this.sourceRect.y = value;
}
public render(camera: es.Camera) { public render(camera: es.Camera) {
if (!this.sprite) if (!this.sprite)
return; return;
+114 -114
View File
@@ -15,20 +15,10 @@ module es {
* *
*/ */
public static content: ContentManager; public static content: ContentManager;
/**
* /访
* @constructor
*/
public static get Instance(){
return this._instance;
}
/** /**
* 访 * 访
*/ */
public static _instance: Core; public static _instance: Core;
public _scene: Scene;
public _nextScene: Scene; public _nextScene: Scene;
public _sceneTransition: SceneTransition; public _sceneTransition: SceneTransition;
/** /**
@@ -36,6 +26,26 @@ module es {
*/ */
public _globalManagers: GlobalManager[] = []; public _globalManagers: GlobalManager[] = [];
constructor() {
super();
Core._instance = this;
Core.emitter = new Emitter<CoreEvents>();
Core.content = new ContentManager();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
/**
* /访
* @constructor
*/
public static get Instance() {
return this._instance;
}
public _scene: Scene;
/** /**
* *
*/ */
@@ -50,7 +60,7 @@ module es {
* @param value * @param value
*/ */
public static set scene(value: Scene) { public static set scene(value: Scene) {
if (!value){ if (!value) {
console.error("场景不能为空"); console.error("场景不能为空");
return; return;
} }
@@ -65,39 +75,106 @@ module es {
} }
} }
constructor() { /**
super(); * SceneTransition
* @param sceneTransition
*/
public static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T {
if (this._instance._sceneTransition) {
console.warn("在前一个场景完成之前,不能开始一个新的场景转换。");
return;
}
Core._instance = this; this._instance._sceneTransition = sceneTransition;
Core.emitter = new Emitter<CoreEvents>(); return sceneTransition;
Core.content = new ContentManager();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
} }
private onAddToStage(){ /**
Core.graphicsDevice = new GraphicsDevice(); *
* @param manager
this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this); */
this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this); public static registerGlobalManager(manager: es.GlobalManager) {
this.addEventListener(egret.Event.ENTER_FRAME, this.update, this); this._instance._globalManagers.push(manager);
manager.enabled = true;
Input.initialize();
this.initialize();
} }
public onOrientationChanged(){ /**
*
* @param manager
*/
public static unregisterGlobalManager(manager: es.GlobalManager) {
this._instance._globalManagers.remove(manager);
manager.enabled = false;
}
/**
* T的全局管理器
* @param type
*/
public static getGlobalManager<T extends es.GlobalManager>(type): T {
for (let i = 0; i < this._instance._globalManagers.length; i++) {
if (this._instance._globalManagers[i] instanceof type)
return this._instance._globalManagers[i] as T;
}
return null;
}
public onOrientationChanged() {
Core.emitter.emit(CoreEvents.OrientationChanged); Core.emitter.emit(CoreEvents.OrientationChanged);
} }
public async draw() {
if (this._sceneTransition) {
this._sceneTransition.preRender();
// 如果我们有场景转换的特殊处理。我们要么渲染场景过渡,要么渲染场景
if (this._scene && !this._sceneTransition.hasPreviousSceneRender) {
this._scene.render();
this._scene.postRender();
await this._sceneTransition.onBeginTransition();
} else if (this._sceneTransition) {
if (this._scene && this._sceneTransition.isNewSceneLoaded) {
this._scene.render();
this._scene.postRender();
}
this._sceneTransition.render();
}
} else if (this._scene) {
this._scene.render();
Debug.render();
// 如果我们没有一个活跃的场景转换,就像平常一样渲染
this._scene.postRender();
}
}
public startDebugUpdate() {
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
}
public endDebugUpdate() {
TimeRuler.Instance.endMark("update");
}
/**
*
*/
public onSceneChanged() {
Core.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged();
}
/** /**
* *
*/ */
protected onGraphicsDeviceReset(){ protected onGraphicsDeviceReset() {
Core.emitter.emit(CoreEvents.GraphicsDeviceReset); Core.emitter.emit(CoreEvents.GraphicsDeviceReset);
} }
protected initialize(){ protected initialize() {
} }
protected async update() { protected async update() {
@@ -139,92 +216,15 @@ module es {
await this.draw(); await this.draw();
} }
public async draw() { private onAddToStage() {
if (this._sceneTransition){ Core.graphicsDevice = new GraphicsDevice();
this._sceneTransition.preRender();
// 如果我们有场景转换的特殊处理。我们要么渲染场景过渡,要么渲染场景 this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this);
if (this._scene && !this._sceneTransition.hasPreviousSceneRender){ this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this);
this._scene.render(); this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
this._scene.postRender();
await this._sceneTransition.onBeginTransition();
} else if (this._sceneTransition) {
if (this._scene && this._sceneTransition.isNewSceneLoaded) {
this._scene.render();
this._scene.postRender();
}
this._sceneTransition.render(); Input.initialize();
} this.initialize();
} else if (this._scene) {
this._scene.render();
Debug.render();
// 如果我们没有一个活跃的场景转换,就像平常一样渲染
this._scene.postRender();
}
}
public startDebugUpdate(){
TimeRuler.Instance.startFrame();
TimeRuler.Instance.beginMark("update", 0x00FF00);
}
public endDebugUpdate(){
TimeRuler.Instance.endMark("update");
}
/**
*
*/
public onSceneChanged(){
Core.emitter.emit(CoreEvents.SceneChanged);
Time.sceneChanged();
}
/**
* SceneTransition
* @param sceneTransition
*/
public static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T {
if (this._instance._sceneTransition) {
console.warn("在前一个场景完成之前,不能开始一个新的场景转换。");
return;
}
this._instance._sceneTransition = sceneTransition;
return sceneTransition;
}
/**
*
* @param manager
*/
public static registerGlobalManager(manager: es.GlobalManager){
this._instance._globalManagers.push(manager);
manager.enabled = true;
}
/**
*
* @param manager
*/
public static unregisterGlobalManager(manager: es.GlobalManager){
this._instance._globalManagers.remove(manager);
manager.enabled = false;
}
/**
* T的全局管理器
* @param type
*/
public static getGlobalManager<T extends es.GlobalManager>(type): T {
for (let i = 0; i < this._instance._globalManagers.length; i ++){
if (this._instance._globalManagers[i] instanceof type)
return this._instance._globalManagers[i] as T;
}
return null;
} }
} }
} }
+1 -1
View File
@@ -1,5 +1,5 @@
module es { module es {
export enum CoreEvents{ export enum CoreEvents {
/** /**
* VRAM将被擦除 * VRAM将被擦除
*/ */
+59 -58
View File
@@ -22,6 +22,31 @@ module es {
* *
*/ */
public readonly components: ComponentList; public readonly components: ComponentList;
/**
* entity update方法的频率12
*/
public updateInterval: number = 1;
public componentBits: BitSet;
constructor(name: string) {
this.components = new ComponentList(this);
this.transform = new Transform(this);
this.name = name;
this.id = Entity._idGenerator++;
this.componentBits = new BitSet();
}
public _isDestroyed: boolean;
/**
* destroytrue
*/
public get isDestroyed() {
return this._isDestroyed;
}
private _tag: number = 0;
/** /**
* 使使 * 使使
@@ -38,10 +63,7 @@ module es {
this.setTag(value); this.setTag(value);
} }
/** private _enabled: boolean = true;
* entity update方法的频率12
*/
public updateInterval: number = 1;
/** /**
* / * /
@@ -58,6 +80,8 @@ module es {
this.setEnabled(value); this.setEnabled(value);
} }
private _updateOrder: number = 0;
/** /**
* updateOrder还用于对scene.entities上的标签列表进行排序 * updateOrder还用于对scene.entities上的标签列表进行排序
*/ */
@@ -73,20 +97,6 @@ module es {
this.setUpdateOrder(value); this.setUpdateOrder(value);
} }
public _isDestroyed: boolean;
/**
* destroytrue
*/
public get isDestroyed() {
return this._isDestroyed;
}
public componentBits: BitSet;
private _tag: number = 0;
private _enabled: boolean = true;
private _updateOrder: number = 0;
public get parent(): Transform { public get parent(): Transform {
return this.transform.parent; return this.transform.parent;
} }
@@ -111,7 +121,7 @@ module es {
return this.transform.localPosition; return this.transform.localPosition;
} }
public set localPosition(value: Vector2){ public set localPosition(value: Vector2) {
this.transform.setLocalPosition(value); this.transform.setLocalPosition(value);
} }
@@ -127,7 +137,7 @@ module es {
return this.transform.rotationDegrees; return this.transform.rotationDegrees;
} }
public set rotationDegrees(value: number){ public set rotationDegrees(value: number) {
this.transform.setRotationDegrees(value); this.transform.setRotationDegrees(value);
} }
@@ -135,7 +145,7 @@ module es {
return this.transform.localRotation; return this.transform.localRotation;
} }
public set localRotation(value: number){ public set localRotation(value: number) {
this.transform.setLocalRotation(value); this.transform.setLocalRotation(value);
} }
@@ -143,7 +153,7 @@ module es {
return this.transform.localRotationDegrees; return this.transform.localRotationDegrees;
} }
public set localRotationDegrees(value: number){ public set localRotationDegrees(value: number) {
this.transform.setLocalRotationDegrees(value); this.transform.setLocalRotationDegrees(value);
} }
@@ -159,7 +169,7 @@ module es {
return this.transform.localScale; return this.transform.localScale;
} }
public set localScale(value: Vector2){ public set localScale(value: Vector2) {
this.transform.setLocalScale(value); this.transform.setLocalScale(value);
} }
@@ -175,15 +185,6 @@ module es {
return this.transform.worldToLocalTransform; return this.transform.worldToLocalTransform;
} }
constructor(name: string) {
this.components = new ComponentList(this);
this.transform = new Transform(this);
this.name = name;
this.id = Entity._idGenerator++;
this.componentBits = new BitSet();
}
public onTransformChanged(comp: transform.Component) { public onTransformChanged(comp: transform.Component) {
// 通知我们的子项改变了位置 // 通知我们的子项改变了位置
this.components.onEntityTransformChanged(comp); this.components.onEntityTransformChanged(comp);
@@ -293,32 +294,6 @@ module es {
return entity; return entity;
} }
/**
*
* @param entity
*/
protected copyFrom(entity: Entity) {
this.tag = entity.tag;
this.updateInterval = entity.updateInterval;
this.updateOrder = entity.updateOrder;
this.enabled = entity.enabled;
this.transform.scale = entity.transform.scale;
this.transform.rotation = entity.transform.rotation;
for (let i = 0; i < entity.components.count; i++)
this.addComponent(entity.components.buffer[i].clone());
for (let i = 0; i < entity.components._componentsToAdd.length; i++)
this.addComponent(entity.components._componentsToAdd[i].clone());
for (let i = 0; i < entity.transform.childCount; i++) {
let child = entity.transform.getChild(i).entity;
let childClone = child.clone();
childClone.transform.copyFrom(child.transform);
childClone.transform.parent = this.transform;
}
}
/** /**
* *
*/ */
@@ -431,5 +406,31 @@ module es {
public toString(): string { public toString(): string {
return `[Entity: name: ${this.name}, tag: ${this.tag}, enabled: ${this.enabled}, depth: ${this.updateOrder}]`; return `[Entity: name: ${this.name}, tag: ${this.tag}, enabled: ${this.enabled}, depth: ${this.updateOrder}]`;
} }
/**
*
* @param entity
*/
protected copyFrom(entity: Entity) {
this.tag = entity.tag;
this.updateInterval = entity.updateInterval;
this.updateOrder = entity.updateOrder;
this.enabled = entity.enabled;
this.transform.scale = entity.transform.scale;
this.transform.rotation = entity.transform.rotation;
for (let i = 0; i < entity.components.count; i++)
this.addComponent(entity.components.buffer[i].clone());
for (let i = 0; i < entity.components._componentsToAdd.length; i++)
this.addComponent(entity.components._componentsToAdd[i].clone());
for (let i = 0; i < entity.transform.childCount; i++) {
let child = entity.transform.getChild(i).entity;
let childClone = child.clone();
childClone.transform.copyFrom(child.transform);
childClone.transform.parent = this.transform;
}
}
} }
} }
+314 -309
View File
@@ -1,350 +1,355 @@
module es { module es {
/** 场景 */ /** 场景 */
export class Scene extends egret.DisplayObjectContainer { export class Scene extends egret.DisplayObjectContainer {
/** /**
* *
*/ */
public camera: Camera; public camera: Camera;
/** /**
* 使/使SceneManager.content * 使/使SceneManager.content
* contentManager来加载它们Nez不会卸载它们 * contentManager来加载它们Nez不会卸载它们
*/ */
public readonly content: ContentManager; public readonly content: ContentManager;
/** /**
* *
*/ */
public enablePostProcessing = true; public enablePostProcessing = true;
/** /**
* *
*/ */
public readonly entities: EntityList; public readonly entities: EntityList;
/** /**
* *
*/ */
public readonly renderableComponents: RenderableComponentList; public readonly renderableComponents: RenderableComponentList;
/** /**
* *
*/ */
public readonly entityProcessors: EntityProcessorList; public readonly entityProcessors: EntityProcessorList;
public _renderers: Renderer[] = []; public _renderers: Renderer[] = [];
public readonly _postProcessors: PostProcessor[] = []; public readonly _postProcessors: PostProcessor[] = [];
public _didSceneBegin; public _didSceneBegin;
/** constructor() {
* DefaultRenderer附加并准备使用 super();
*/ this.entities = new EntityList(this);
public static createWithDefaultRenderer(){ this.renderableComponents = new RenderableComponentList();
let scene = new Scene(); this.content = new ContentManager();
scene.addRenderer(new DefaultRenderer());
return scene;
}
constructor() { this.entityProcessors = new EntityProcessorList();
super();
this.entities = new EntityList(this);
this.renderableComponents = new RenderableComponentList();
this.content = new ContentManager();
this.entityProcessors = new EntityProcessorList(); this.initialize();
}
this.initialize(); /**
} * DefaultRenderer附加并准备使用
*/
public static createWithDefaultRenderer() {
let scene = new Scene();
scene.addRenderer(new DefaultRenderer());
return scene;
}
/** /**
* begin之前 * begin之前
*/ */
public initialize(){} public initialize() {
}
/** /**
* SceneManager将此场景设置为活动场景时 * SceneManager将此场景设置为活动场景时
*/ */
public async onStart() {} public async onStart() {
}
/** /**
* SceneManager从活动槽中删除此场景时调用 * SceneManager从活动槽中删除此场景时调用
*/ */
public unload() { } public unload() {
}
/** /**
* *
*/ */
public onActive() {} public onActive() {
}
/** /**
* *
*/ */
public onDeactive() {} public onDeactive() {
}
public async begin() { public async begin() {
if (this._renderers.length == 0) { if (this._renderers.length == 0) {
this.addRenderer(new DefaultRenderer()); this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染"); console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
}
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
Physics.reset();
if (this.entityProcessors)
this.entityProcessors.begin();
this.addEventListener(egret.Event.ACTIVATE, this.onActive, this);
this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
this._didSceneBegin = true;
this.onStart();
}
public end() {
this._didSceneBegin = false;
this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this);
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].unload();
}
for (let i = 0; i < this._postProcessors.length; i++) {
this._postProcessors[i].unload();
}
this.entities.removeAllEntities();
this.removeChildren();
this.camera = null;
this.content.dispose();
if (this.entityProcessors)
this.entityProcessors.end();
if (this.parent)
this.parent.removeChild(this);
this.unload();
}
public update() {
// 更新我们的列表,以防它们有任何变化
this.entities.updateLists();
// 更新我们的实体解析器
if (this.entityProcessors)
this.entityProcessors.update();
// 更新我们的实体组
this.entities.update();
if (this.entityProcessors)
this.entityProcessors.lateUpdate();
// 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新
this.renderableComponents.updateList();
}
public render() {
if (this._renderers.length == 0){
console.error("there are no renderers in the scene!");
return;
}
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].render(this);
}
}
/**
*
* SceneTransition请求渲染时
*/
public postRender() {
if (this.enablePostProcessing) {
for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i].enabled) {
this._postProcessors[i].process();
}
} }
}
}
/** this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
*
* @param renderer
*/
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
renderer.onAddedToScene(this); Physics.reset();
return renderer; if (this.entityProcessors)
} this.entityProcessors.begin();
/** this.addEventListener(egret.Event.ACTIVATE, this.onActive, this);
* T的第一个渲染器 this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
* @param type this.camera.onSceneSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
*/
public getRenderer<T extends Renderer>(type): T {
for (let i = 0; i < this._renderers.length; i++) {
if (this._renderers[i] instanceof type)
return this._renderers[i] as T;
}
return null; this._didSceneBegin = true;
} this.onStart();
}
/** public end() {
* this._didSceneBegin = false;
* @param renderer
*/
public removeRenderer(renderer: Renderer) {
if (!this._renderers.contains(renderer))
return;
this._renderers.remove(renderer);
renderer.unload();
}
/** this.removeEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
* onAddedToScene使后处理器可以使用场景ContentManager加载资源 this.removeEventListener(egret.Event.ACTIVATE, this.onActive, this);
* @param postProcessor
*/
public addPostProcessor<T extends PostProcessor>(postProcessor: T): T{
this._postProcessors.push(postProcessor);
this._postProcessors.sort();
postProcessor.onAddedToScene(this);
if (this._didSceneBegin){ for (let i = 0; i < this._renderers.length; i++) {
postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight); this._renderers[i].unload();
} }
return postProcessor; for (let i = 0; i < this._postProcessors.length; i++) {
} this._postProcessors[i].unload();
}
/** this.entities.removeAllEntities();
* T的第一个后处理器 this.removeChildren();
* @param type
*/
public getPostProcessor<T extends PostProcessor>(type): T{
for (let i = 0; i < this._postProcessors.length; i ++){
if (this._postProcessors[i] instanceof type)
return this._postProcessors[i] as T;
}
return null; this.camera = null;
} this.content.dispose();
/** if (this.entityProcessors)
* unloadPostProcessorunload来释放资源 this.entityProcessors.end();
* @param postProcessor
*/
public removePostProcessor(postProcessor: PostProcessor){
if (!this._postProcessors.contains(postProcessor))
return;
this._postProcessors.remove(postProcessor); if (this.parent)
postProcessor.unload(); this.parent.removeChild(this);
}
/** this.unload();
* }
* @param name
*/
public createEntity(name: string) {
let entity = new Entity(name);
return this.addEntity(entity);
}
/** public update() {
* // 更新我们的列表,以防它们有任何变化
* @param entity this.entities.updateLists();
*/
public addEntity(entity: Entity) {
if (this.entities.buffer.contains(entity))
console.warn(`You are attempting to add the same entity to a scene twice: ${entity}`);
this.entities.add(entity);
entity.scene = this;
for (let i = 0; i < entity.transform.childCount; i++) // 更新我们的实体解析器
this.addEntity(entity.transform.getChild(i).entity); if (this.entityProcessors)
this.entityProcessors.update();
return entity; // 更新我们的实体组
} this.entities.update();
/** if (this.entityProcessors)
* this.entityProcessors.lateUpdate();
*/
public destroyAllEntities() {
for (let i = 0; i < this.entities.count; i++) {
this.entities.buffer[i].destroy();
}
}
/** // 我们在实体之后更新我们的呈现。如果添加了任何新的渲染,请进行更新
* this.renderableComponents.updateList();
* @param name }
*/
public findEntity(name: string): Entity {
return this.entities.findEntity(name);
}
/** public render() {
* if (this._renderers.length == 0) {
* @param tag console.error("there are no renderers in the scene!");
*/ return;
public findEntitiesWithTag(tag: number): Entity[]{ }
return this.entities.entitiesWithTag(tag);
}
/** for (let i = 0; i < this._renderers.length; i++) {
* T的所有实体 this._renderers[i].render(this);
* @param type }
*/ }
public entitiesOfType<T extends Entity>(type): T[]{
return this.entities.entitiesOfType<T>(type);
}
/** /**
* T的组件 *
* @param type * SceneTransition请求渲染时
*/ */
public findComponentOfType<T extends Component>(type): T { public postRender() {
return this.entities.findComponentOfType<T>(type); if (this.enablePostProcessing) {
} for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i].enabled) {
this._postProcessors[i].process();
}
}
}
}
/** /**
* T的所有已启用已加载组件的列表 *
* @param type * @param renderer
*/ */
public findComponentsOfType<T extends Component>(type): T[] { public addRenderer<T extends Renderer>(renderer: T) {
return this.entities.findComponentsOfType<T>(type); this._renderers.push(renderer);
} this._renderers.sort();
/** renderer.onAddedToScene(this);
* EntitySystem处理器
* @param processor
*/
public addEntityProcessor(processor: EntitySystem) {
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
/** return renderer;
* EntitySystem处理器 }
* @param processor
*/
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
}
/** /**
* EntitySystem处理 * T的第一个渲染
*/ * @param type
public getEntityProcessor<T extends EntitySystem>(): T { */
return this.entityProcessors.getProcessor<T>(); public getRenderer<T extends Renderer>(type): T {
} for (let i = 0; i < this._renderers.length; i++) {
} if (this._renderers[i] instanceof type)
return this._renderers[i] as T;
}
return null;
}
/**
*
* @param renderer
*/
public removeRenderer(renderer: Renderer) {
if (!this._renderers.contains(renderer))
return;
this._renderers.remove(renderer);
renderer.unload();
}
/**
* onAddedToScene使后处理器可以使用场景ContentManager加载资源
* @param postProcessor
*/
public addPostProcessor<T extends PostProcessor>(postProcessor: T): T {
this._postProcessors.push(postProcessor);
this._postProcessors.sort();
postProcessor.onAddedToScene(this);
if (this._didSceneBegin) {
postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
}
return postProcessor;
}
/**
* T的第一个后处理器
* @param type
*/
public getPostProcessor<T extends PostProcessor>(type): T {
for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i] instanceof type)
return this._postProcessors[i] as T;
}
return null;
}
/**
* unloadPostProcessorunload来释放资源
* @param postProcessor
*/
public removePostProcessor(postProcessor: PostProcessor) {
if (!this._postProcessors.contains(postProcessor))
return;
this._postProcessors.remove(postProcessor);
postProcessor.unload();
}
/**
*
* @param name
*/
public createEntity(name: string) {
let entity = new Entity(name);
return this.addEntity(entity);
}
/**
*
* @param entity
*/
public addEntity(entity: Entity) {
if (this.entities.buffer.contains(entity))
console.warn(`You are attempting to add the same entity to a scene twice: ${entity}`);
this.entities.add(entity);
entity.scene = this;
for (let i = 0; i < entity.transform.childCount; i++)
this.addEntity(entity.transform.getChild(i).entity);
return entity;
}
/**
*
*/
public destroyAllEntities() {
for (let i = 0; i < this.entities.count; i++) {
this.entities.buffer[i].destroy();
}
}
/**
*
* @param name
*/
public findEntity(name: string): Entity {
return this.entities.findEntity(name);
}
/**
*
* @param tag
*/
public findEntitiesWithTag(tag: number): Entity[] {
return this.entities.entitiesWithTag(tag);
}
/**
* T的所有实体
* @param type
*/
public entitiesOfType<T extends Entity>(type): T[] {
return this.entities.entitiesOfType<T>(type);
}
/**
* T的组件
* @param type
*/
public findComponentOfType<T extends Component>(type): T {
return this.entities.findComponentOfType<T>(type);
}
/**
* T的所有已启用已加载组件的列表
* @param type
*/
public findComponentsOfType<T extends Component>(type): T[] {
return this.entities.findComponentsOfType<T>(type);
}
/**
* EntitySystem处理器
* @param processor
*/
public addEntityProcessor(processor: EntitySystem) {
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
/**
* EntitySystem处理器
* @param processor
*/
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
}
/**
* EntitySystem处理器
*/
public getEntityProcessor<T extends EntitySystem>(): T {
return this.entityProcessors.getProcessor<T>();
}
}
} }
+23 -21
View File
@@ -1,80 +1,82 @@
module es { module es {
export class EntitySystem { export class EntitySystem {
private _scene: Scene;
private _entities: Entity[] = []; private _entities: Entity[] = [];
private _matcher: Matcher;
public get matcher(){ constructor(matcher?: Matcher) {
return this._matcher; this._matcher = matcher ? matcher : Matcher.empty();
} }
public get scene(){ private _scene: Scene;
public get scene() {
return this._scene; return this._scene;
} }
public set scene(value: Scene){ public set scene(value: Scene) {
this._scene = value; this._scene = value;
this._entities = []; this._entities = [];
} }
constructor(matcher?: Matcher){ private _matcher: Matcher;
this._matcher = matcher ? matcher : Matcher.empty();
public get matcher() {
return this._matcher;
} }
public initialize(){ public initialize() {
} }
public onChanged(entity: Entity){ public onChanged(entity: Entity) {
let contains = this._entities.contains(entity); let contains = this._entities.contains(entity);
let interest = this._matcher.IsIntersted(entity); let interest = this._matcher.IsIntersted(entity);
if (interest && !contains) if (interest && !contains)
this.add(entity); this.add(entity);
else if(!interest && contains) else if (!interest && contains)
this.remove(entity); this.remove(entity);
} }
public add(entity: Entity){ public add(entity: Entity) {
this._entities.push(entity); this._entities.push(entity);
this.onAdded(entity); this.onAdded(entity);
} }
public onAdded(entity: Entity){ public onAdded(entity: Entity) {
} }
public remove(entity: Entity){ public remove(entity: Entity) {
this._entities.remove(entity); this._entities.remove(entity);
this.onRemoved(entity); this.onRemoved(entity);
} }
public onRemoved(entity: Entity){ public onRemoved(entity: Entity) {
} }
public update(){ public update() {
this.begin(); this.begin();
this.process(this._entities); this.process(this._entities);
} }
public lateUpdate(){ public lateUpdate() {
this.lateProcess(this._entities); this.lateProcess(this._entities);
this.end(); this.end();
} }
protected begin(){ protected begin() {
} }
protected process(entities: Entity[]){ protected process(entities: Entity[]) {
} }
protected lateProcess(entities: Entity[]){ protected lateProcess(entities: Entity[]) {
} }
protected end(){ protected end() {
} }
} }
+2 -2
View File
@@ -1,10 +1,10 @@
module es { module es {
export abstract class PassiveSystem extends EntitySystem { export abstract class PassiveSystem extends EntitySystem {
public onChanged(entity: Entity){ public onChanged(entity: Entity) {
} }
protected process(entities: Entity[]){ protected process(entities: Entity[]) {
// 我们用我们自己的不考虑实体的基本实体系统来代替 // 我们用我们自己的不考虑实体的基本实体系统来代替
this.begin(); this.begin();
this.end(); this.end();
+7 -7
View File
@@ -1,17 +1,17 @@
/** 用于协调其他系统的通用系统基类 */ /** 用于协调其他系统的通用系统基类 */
module es { module es {
export abstract class ProcessingSystem extends EntitySystem { export abstract class ProcessingSystem extends EntitySystem {
public onChanged(entity: Entity){ public onChanged(entity: Entity) {
} }
protected process(entities: Entity[]){
this.begin();
this.processSystem();
this.end();
}
/** 处理我们的系统 每帧调用 */ /** 处理我们的系统 每帧调用 */
public abstract processSystem(); public abstract processSystem();
protected process(entities: Entity[]) {
this.begin();
this.processSystem();
this.end();
}
} }
} }
+177 -174
View File
@@ -19,6 +19,78 @@ module es {
export class Transform extends HashObject { export class Transform extends HashObject {
/** 与此转换关联的实体 */ /** 与此转换关联的实体 */
public readonly entity: Entity; public readonly entity: Entity;
public hierarchyDirty: DirtyType;
public _localDirty: boolean;
public _localPositionDirty: boolean;
public _localScaleDirty: boolean;
public _localRotationDirty: boolean;
public _positionDirty: boolean;
public _worldToLocalDirty: boolean;
public _worldInverseDirty: boolean;
/**
*
*/
public _localTransform: Matrix2D = Matrix2D.create();
/**
*
*/
public _worldTransform = Matrix2D.create().identity();
public _rotationMatrix: Matrix2D = Matrix2D.create();
public _translationMatrix: Matrix2D = Matrix2D.create();
public _scaleMatrix: Matrix2D = Matrix2D.create();
public _children: Transform[];
constructor(entity: Entity) {
super();
this.entity = entity;
this.scale = Vector2.one;
this._children = [];
}
/**
*
*/
public get childCount() {
return this._children.length;
}
/**
*
*/
public get rotationDegrees(): number {
return MathHelper.toDegrees(this._rotation);
}
/**
*
* @param value
*/
public set rotationDegrees(value: number) {
this.setRotation(MathHelper.toRadians(value));
}
/**
*
*/
public get localRotationDegrees(): number {
return MathHelper.toDegrees(this._localRotation);
}
/**
*
* @param value
*/
public set localRotationDegrees(value: number) {
this.localRotation = MathHelper.toRadians(value);
}
public get localToWorldTransform(): Matrix2D {
this.updateTransform();
return this._worldTransform;
}
public _parent: Transform;
/** /**
* *
*/ */
@@ -34,22 +106,46 @@ module es {
this.setParent(value); this.setParent(value);
} }
/** public _worldToLocalTransform = Matrix2D.create().identity();
*
*/ public get worldToLocalTransform(): Matrix2D {
public get childCount() { if (this._worldToLocalDirty) {
return this._children.length; if (!this.parent) {
this._worldToLocalTransform = Matrix2D.create().identity();
} else {
this.parent.updateTransform();
this._worldToLocalTransform = this.parent._worldTransform.invert();
}
this._worldToLocalDirty = false;
}
return this._worldToLocalTransform;
} }
public _worldInverseTransform = Matrix2D.create().identity();
public get worldInverseTransform(): Matrix2D {
this.updateTransform();
if (this._worldInverseDirty) {
this._worldInverseTransform = this._worldTransform.invert();
this._worldInverseDirty = false;
}
return this._worldInverseTransform;
}
public _position: Vector2 = Vector2.zero;
/** /**
* *
*/ */
public get position(): Vector2 { public get position(): Vector2 {
this.updateTransform(); this.updateTransform();
if (this._positionDirty){ if (this._positionDirty) {
if (!this.parent){ if (!this.parent) {
this._position = this._localPosition; this._position = this._localPosition;
}else{ } else {
this.parent.updateTransform(); this.parent.updateTransform();
this._position = Vector2Ext.transformR(this._localPosition, this.parent._worldTransform); this._position = Vector2Ext.transformR(this._localPosition, this.parent._worldTransform);
} }
@@ -64,10 +160,48 @@ module es {
* *
* @param value * @param value
*/ */
public set position(value: Vector2){ public set position(value: Vector2) {
this.setPosition(value.x, value.y); this.setPosition(value.x, value.y);
} }
public _scale: Vector2 = Vector2.one;
/**
*
*/
public get scale(): Vector2 {
this.updateTransform();
return this._scale;
}
/**
*
* @param value
*/
public set scale(value: Vector2) {
this.setScale(value);
}
public _rotation: number = 0;
/**
*
*/
public get rotation(): number {
this.updateTransform();
return this._rotation;
}
/**
*
* @param value
*/
public set rotation(value: number) {
this.setRotation(value);
}
public _localPosition: Vector2 = Vector2.zero;
/** /**
* transform.position相同 * transform.position相同
*/ */
@@ -80,87 +214,11 @@ module es {
* transform.position相同 * transform.position相同
* @param value * @param value
*/ */
public set localPosition(value: Vector2){ public set localPosition(value: Vector2) {
this.setLocalPosition(value); this.setLocalPosition(value);
} }
/** public _localScale: Vector2 = Vector2.one;
*
*/
public get rotation(): number {
this.updateTransform();
return this._rotation;
}
/**
*
*/
public get rotationDegrees(): number {
return MathHelper.toDegrees(this._rotation);
}
/**
*
* @param value
*/
public set rotationDegrees(value: number){
this.setRotation(MathHelper.toRadians(value));
}
/**
*
* @param value
*/
public set rotation(value: number){
this.setRotation(value);
}
/**
* transform.rotation相同
*/
public get localRotation(): number {
this.updateTransform();
return this._localRotation;
}
/**
* transform.rotation相同
* @param value
*/
public set localRotation(value: number){
this.setLocalRotation(value);
}
/**
*
*/
public get localRotationDegrees(): number {
return MathHelper.toDegrees(this._localRotation);
}
/**
*
* @param value
*/
public set localRotationDegrees(value: number){
this.localRotation = MathHelper.toRadians(value);
}
/**
*
*/
public get scale(): Vector2{
this.updateTransform();
return this._scale;
}
/**
*
* @param value
*/
public set scale(value: Vector2){
this.setScale(value);
}
/** /**
* transform.scale相同 * transform.scale相同
@@ -174,81 +232,26 @@ module es {
* transform.scale相同 * transform.scale相同
* @param value * @param value
*/ */
public set localScale(value: Vector2){ public set localScale(value: Vector2) {
this.setLocalScale(value); this.setLocalScale(value);
} }
public get worldInverseTransform(): Matrix2D {
this.updateTransform();
if (this._worldInverseDirty){
this._worldInverseTransform = this._worldTransform.invert();
this._worldInverseDirty = false;
}
return this._worldInverseTransform;
}
public get localToWorldTransform(): Matrix2D {
this.updateTransform();
return this._worldTransform;
}
public get worldToLocalTransform(): Matrix2D {
if (this._worldToLocalDirty){
if (!this.parent){
this._worldToLocalTransform = Matrix2D.create().identity();
}else{
this.parent.updateTransform();
this._worldToLocalTransform = this.parent._worldTransform.invert();
}
this._worldToLocalDirty = false;
}
return this._worldToLocalTransform;
}
public _parent: Transform;
public hierarchyDirty: DirtyType;
public _localDirty: boolean;
public _localPositionDirty: boolean;
public _localScaleDirty: boolean;
public _localRotationDirty: boolean;
public _positionDirty: boolean;
public _worldToLocalDirty: boolean;
public _worldInverseDirty: boolean;
/**
*
*/
public _localTransform: Matrix2D = Matrix2D.create();
/**
*
*/
public _worldTransform = Matrix2D.create().identity();
public _worldToLocalTransform = Matrix2D.create().identity();
public _worldInverseTransform = Matrix2D.create().identity();
public _rotationMatrix: Matrix2D = Matrix2D.create();
public _translationMatrix: Matrix2D = Matrix2D.create();
public _scaleMatrix: Matrix2D = Matrix2D.create();
public _position: Vector2 = Vector2.zero;
public _scale: Vector2 = Vector2.one;
public _rotation: number = 0;
public _localPosition: Vector2 = Vector2.zero;
public _localScale: Vector2 = Vector2.one;
public _localRotation: number = 0; public _localRotation: number = 0;
public _children: Transform[]; /**
* transform.rotation相同
*/
public get localRotation(): number {
this.updateTransform();
return this._localRotation;
}
constructor(entity: Entity) { /**
super(); * transform.rotation相同
this.entity = entity; * @param value
this.scale = Vector2.one; */
this._children = []; public set localRotation(value: number) {
this.setLocalRotation(value);
} }
/** /**
@@ -289,7 +292,7 @@ module es {
return this; return this;
this._position = position; this._position = position;
if (this.parent){ if (this.parent) {
this.localPosition = Vector2Ext.transformR(this._position, this._worldToLocalTransform); this.localPosition = Vector2Ext.transformR(this._position, this._worldToLocalTransform);
} else { } else {
this.localPosition = position; this.localPosition = position;
@@ -321,7 +324,7 @@ module es {
*/ */
public setRotation(radians: number): Transform { public setRotation(radians: number): Transform {
this._rotation = radians; this._rotation = radians;
if (this.parent){ if (this.parent) {
this.localRotation = this.parent.rotation + radians; this.localRotation = this.parent.rotation + radians;
} else { } else {
this.localRotation = radians; this.localRotation = radians;
@@ -352,7 +355,7 @@ module es {
* transform.rotation相同 * transform.rotation相同
* @param radians * @param radians
*/ */
public setLocalRotation(radians: number){ public setLocalRotation(radians: number) {
this._localRotation = radians; this._localRotation = radians;
this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true; this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.rotationDirty); this.setDirty(DirtyType.rotationDirty);
@@ -374,9 +377,9 @@ module es {
*/ */
public setScale(scale: Vector2): Transform { public setScale(scale: Vector2): Transform {
this._scale = scale; this._scale = scale;
if (this.parent){ if (this.parent) {
this.localScale = Vector2.divide(scale, this.parent._scale); this.localScale = Vector2.divide(scale, this.parent._scale);
}else{ } else {
this.localScale = scale; this.localScale = scale;
} }
return this; return this;
@@ -401,23 +404,23 @@ module es {
this.position = this._position.round(); this.position = this._position.round();
} }
public updateTransform(){ public updateTransform() {
if (this.hierarchyDirty != DirtyType.clean){ if (this.hierarchyDirty != DirtyType.clean) {
if (this.parent) if (this.parent)
this.parent.updateTransform(); this.parent.updateTransform();
if (this._localDirty){ if (this._localDirty) {
if (this._localPositionDirty){ if (this._localPositionDirty) {
this._translationMatrix = Matrix2D.create().translate(this._localPosition.x, this._localPosition.y); this._translationMatrix = Matrix2D.create().translate(this._localPosition.x, this._localPosition.y);
this._localPositionDirty = false; this._localPositionDirty = false;
} }
if (this._localRotationDirty){ if (this._localRotationDirty) {
this._rotationMatrix = Matrix2D.create().rotate(this._localRotation); this._rotationMatrix = Matrix2D.create().rotate(this._localRotation);
this._localRotationDirty = false; this._localRotationDirty = false;
} }
if (this._localScaleDirty){ if (this._localScaleDirty) {
this._scaleMatrix = Matrix2D.create().scale(this._localScale.x, this._localScale.y); this._scaleMatrix = Matrix2D.create().scale(this._localScale.x, this._localScale.y);
this._localScaleDirty = false; this._localScaleDirty = false;
} }
@@ -425,7 +428,7 @@ module es {
this._localTransform = this._scaleMatrix.multiply(this._rotationMatrix); this._localTransform = this._scaleMatrix.multiply(this._rotationMatrix);
this._localTransform = this._localTransform.multiply(this._translationMatrix); this._localTransform = this._localTransform.multiply(this._translationMatrix);
if (!this.parent){ if (!this.parent) {
this._worldTransform = this._localTransform; this._worldTransform = this._localTransform;
this._rotation = this._localRotation; this._rotation = this._localRotation;
this._scale = this._localScale; this._scale = this._localScale;
@@ -435,7 +438,7 @@ module es {
this._localDirty = false; this._localDirty = false;
} }
if (this.parent){ if (this.parent) {
this._worldTransform = this._localTransform.multiply(this.parent._worldTransform); this._worldTransform = this._localTransform.multiply(this.parent._worldTransform);
this._rotation = this._localRotation + this.parent._rotation; this._rotation = this._localRotation + this.parent._rotation;
@@ -449,8 +452,8 @@ module es {
} }
} }
public setDirty(dirtyFlagType: DirtyType){ public setDirty(dirtyFlagType: DirtyType) {
if ((this.hierarchyDirty & dirtyFlagType) == 0){ if ((this.hierarchyDirty & dirtyFlagType) == 0) {
this.hierarchyDirty |= dirtyFlagType; this.hierarchyDirty |= dirtyFlagType;
switch (dirtyFlagType) { switch (dirtyFlagType) {
@@ -469,7 +472,7 @@ module es {
this._children = []; this._children = [];
// 告诉子项发生了变换 // 告诉子项发生了变换
for (let i = 0; i < this._children.length; i ++) for (let i = 0; i < this._children.length; i++)
this._children[i].setDirty(dirtyFlagType); this._children[i].setDirty(dirtyFlagType);
} }
} }
@@ -491,13 +494,13 @@ module es {
this.setDirty(DirtyType.scaleDirty); this.setDirty(DirtyType.scaleDirty);
} }
public toString(): string{ public toString(): string {
return `[Transform: parent: ${this.parent}, position: ${this.position}, rotation: ${this.rotation}, return `[Transform: parent: ${this.parent}, position: ${this.position}, rotation: ${this.rotation},
scale: ${this.scale}, localPosition: ${this._localPosition}, localRotation: ${this._localRotation}, scale: ${this.scale}, localPosition: ${this._localPosition}, localRotation: ${this._localRotation},
localScale: ${this._localScale}]`; localScale: ${this._localScale}]`;
} }
public equals(other: Transform){ public equals(other: Transform) {
return other.hashCode == this.hashCode; return other.hashCode == this.hashCode;
} }
} }
+34 -34
View File
@@ -4,43 +4,43 @@ module es {
* *
* ; * ;
*/ */
export class BitSet{ export class BitSet {
private static LONG_MASK: number = 0x3f; private static LONG_MASK: number = 0x3f;
private _bits: number[]; private _bits: number[];
constructor(nbits: number = 64){ constructor(nbits: number = 64) {
let length = nbits >> 6; let length = nbits >> 6;
if ((nbits & BitSet.LONG_MASK) != 0) if ((nbits & BitSet.LONG_MASK) != 0)
length ++; length++;
this._bits = new Array(length); this._bits = new Array(length);
} }
public and(bs: BitSet){ public and(bs: BitSet) {
let max = Math.min(this._bits.length, bs._bits.length); let max = Math.min(this._bits.length, bs._bits.length);
let i; let i;
for (let i = 0; i < max; ++i) for (let i = 0; i < max; ++i)
this._bits[i] &= bs._bits[i]; this._bits[i] &= bs._bits[i];
while (i < this._bits.length) while (i < this._bits.length)
this._bits[i ++] = 0; this._bits[i++] = 0;
} }
public andNot(bs: BitSet){ public andNot(bs: BitSet) {
let i = Math.min(this._bits.length, bs._bits.length); let i = Math.min(this._bits.length, bs._bits.length);
while(--i >= 0) while (--i >= 0)
this._bits[i] &= ~bs._bits[i]; this._bits[i] &= ~bs._bits[i];
} }
public cardinality(): number{ public cardinality(): number {
let card = 0; let card = 0;
for (let i = this._bits.length - 1; i >= 0; i --){ for (let i = this._bits.length - 1; i >= 0; i--) {
let a = this._bits[i]; let a = this._bits[i];
if (a == 0) if (a == 0)
continue; continue;
if (a == -1){ if (a == -1) {
card += 64; card += 64;
continue; continue;
} }
@@ -56,26 +56,18 @@ module es {
return card; return card;
} }
public clear(pos?: number){ public clear(pos?: number) {
if (pos != undefined){ if (pos != undefined) {
let offset = pos >> 6; let offset = pos >> 6;
this.ensure(offset); this.ensure(offset);
this._bits[offset] &= ~(1 << pos); this._bits[offset] &= ~(1 << pos);
}else{ } else {
for (let i = 0; i < this._bits.length; i ++) for (let i = 0; i < this._bits.length; i++)
this._bits[i] = 0; this._bits[i] = 0;
} }
} }
private ensure(lastElt: number){ public get(pos: number): boolean {
if (lastElt >= this._bits.length){
let nd = new Number[lastElt + 1];
nd = this._bits.copyWithin(0, 0, this._bits.length);
this._bits = nd;
}
}
public get(pos: number): boolean{
let offset = pos >> 6; let offset = pos >> 6;
if (offset >= this._bits.length) if (offset >= this._bits.length)
return false; return false;
@@ -83,9 +75,9 @@ module es {
return (this._bits[offset] & (1 << pos)) != 0; return (this._bits[offset] & (1 << pos)) != 0;
} }
public intersects(set: BitSet){ public intersects(set: BitSet) {
let i = Math.min(this._bits.length, set._bits.length); let i = Math.min(this._bits.length, set._bits.length);
while (--i >= 0){ while (--i >= 0) {
if ((this._bits[i] & set._bits[i]) != 0) if ((this._bits[i] & set._bits[i]) != 0)
return true; return true;
} }
@@ -93,8 +85,8 @@ module es {
return false; return false;
} }
public isEmpty(): boolean{ public isEmpty(): boolean {
for (let i = this._bits.length - 1; i >= 0; i --){ for (let i = this._bits.length - 1; i >= 0; i--) {
if (this._bits[i]) if (this._bits[i])
return false; return false;
} }
@@ -102,34 +94,42 @@ module es {
return true; return true;
} }
public nextSetBit(from: number){ public nextSetBit(from: number) {
let offset = from >> 6; let offset = from >> 6;
let mask = 1 << from; let mask = 1 << from;
while (offset < this._bits.length){ while (offset < this._bits.length) {
let h = this._bits[offset]; let h = this._bits[offset];
do { do {
if ((h & mask) != 0) if ((h & mask) != 0)
return from; return from;
mask <<= 1; mask <<= 1;
from ++; from++;
} while (mask != 0); } while (mask != 0);
mask = 1; mask = 1;
offset ++; offset++;
} }
return -1; return -1;
} }
public set(pos: number, value: boolean = true){ public set(pos: number, value: boolean = true) {
if (value){ if (value) {
let offset = pos >> 6; let offset = pos >> 6;
this.ensure(offset); this.ensure(offset);
this._bits[offset] |= 1 << pos; this._bits[offset] |= 1 << pos;
}else{ } else {
this.clear(pos); this.clear(pos);
} }
} }
private ensure(lastElt: number) {
if (lastElt >= this._bits.length) {
let nd = new Number[lastElt + 1];
nd = this._bits.copyWithin(0, 0, this._bits.length);
this._bits = nd;
}
}
} }
} }
+6 -6
View File
@@ -37,7 +37,7 @@ module es {
return this._components; return this._components;
} }
public markEntityListUnsorted(){ public markEntityListUnsorted() {
this._isComponentListUnsorted = true; this._isComponentListUnsorted = true;
} }
@@ -76,7 +76,7 @@ module es {
let component = this._components[i]; let component = this._components[i];
// 处理渲染层列表 // 处理渲染层列表
if (component instanceof RenderableComponent){ if (component instanceof RenderableComponent) {
this._entity.scene.removeChild(component.displayObject); this._entity.scene.removeChild(component.displayObject);
this._entity.scene.renderableComponents.remove(component); this._entity.scene.renderableComponents.remove(component);
} }
@@ -91,7 +91,7 @@ module es {
for (let i = 0; i < this._components.length; i++) { for (let i = 0; i < this._components.length; i++) {
let component = this._components[i]; let component = this._components[i];
if (component instanceof RenderableComponent){ if (component instanceof RenderableComponent) {
this._entity.scene.addChild(component.displayObject); this._entity.scene.addChild(component.displayObject);
this._entity.scene.renderableComponents.add(component); this._entity.scene.renderableComponents.add(component);
} }
@@ -117,7 +117,7 @@ module es {
if (this._componentsToAdd.length > 0) { if (this._componentsToAdd.length > 0) {
for (let i = 0, count = this._componentsToAdd.length; i < count; i++) { for (let i = 0, count = this._componentsToAdd.length; i < count; i++) {
let component = this._componentsToAdd[i]; let component = this._componentsToAdd[i];
if (component instanceof RenderableComponent){ if (component instanceof RenderableComponent) {
this._entity.scene.addChild(component.displayObject); this._entity.scene.addChild(component.displayObject);
this._entity.scene.renderableComponents.add(component); this._entity.scene.renderableComponents.add(component);
} }
@@ -148,7 +148,7 @@ module es {
this._tempBufferList.length = 0; this._tempBufferList.length = 0;
} }
if (this._isComponentListUnsorted){ if (this._isComponentListUnsorted) {
this._components.sort(ComponentList.compareUpdatableOrder.compare); this._components.sort(ComponentList.compareUpdatableOrder.compare);
this._isComponentListUnsorted = false; this._isComponentListUnsorted = false;
} }
@@ -156,7 +156,7 @@ module es {
public handleRemove(component: Component) { public handleRemove(component: Component) {
// 处理渲染层列表 // 处理渲染层列表
if (component instanceof RenderableComponent){ if (component instanceof RenderableComponent) {
this._entity.scene.removeChild(component.displayObject); this._entity.scene.removeChild(component.displayObject);
this._entity.scene.renderableComponents.remove(component); this._entity.scene.renderableComponents.remove(component);
} }
+4 -4
View File
@@ -1,15 +1,15 @@
module es { module es {
export class ComponentTypeManager{ export class ComponentTypeManager {
private static _componentTypesMask: Map<any, number> = new Map<any, number>(); private static _componentTypesMask: Map<any, number> = new Map<any, number>();
public static add(type){ public static add(type) {
if (!this._componentTypesMask.has(type)) if (!this._componentTypesMask.has(type))
this._componentTypesMask[type] = this._componentTypesMask.size; this._componentTypesMask[type] = this._componentTypesMask.size;
} }
public static getIndexFor(type){ public static getIndexFor(type) {
let v = -1; let v = -1;
if (!this._componentTypesMask.has(type)){ if (!this._componentTypesMask.has(type)) {
this.add(type); this.add(type);
v = this._componentTypesMask.get(type); v = this._componentTypesMask.get(type);
} }
+40 -40
View File
@@ -1,5 +1,5 @@
module es { module es {
export class EntityList{ export class EntityList {
public scene: Scene; public scene: Scene;
/** /**
* *
@@ -27,23 +27,23 @@ module es {
*/ */
public _tempEntityList: Entity[] = []; public _tempEntityList: Entity[] = [];
constructor(scene: Scene){ constructor(scene: Scene) {
this.scene = scene; this.scene = scene;
} }
public get count(){ public get count() {
return this._entities.length; return this._entities.length;
} }
public get buffer(){ public get buffer() {
return this._entities; return this._entities;
} }
public markEntityListUnsorted(){ public markEntityListUnsorted() {
this._isEntityListUnsorted = true; this._isEntityListUnsorted = true;
} }
public markTagUnsorted(tag: number){ public markTagUnsorted(tag: number) {
this._unsortedTags.push(tag); this._unsortedTags.push(tag);
} }
@@ -51,7 +51,7 @@ module es {
* *
* @param entity * @param entity
*/ */
public add(entity: Entity){ public add(entity: Entity) {
if (this._entitiesToAdded.indexOf(entity) == -1) if (this._entitiesToAdded.indexOf(entity) == -1)
this._entitiesToAdded.push(entity); this._entitiesToAdded.push(entity);
} }
@@ -60,14 +60,14 @@ module es {
* *
* @param entity * @param entity
*/ */
public remove(entity: Entity){ public remove(entity: Entity) {
if (!this._entitiesToRemove.contains(entity)){ if (!this._entitiesToRemove.contains(entity)) {
console.warn(`You are trying to remove an entity (${entity.name}) that you already removed`); console.warn(`You are trying to remove an entity (${entity.name}) that you already removed`);
return; return;
} }
// 防止在同一帧中添加或删除实体 // 防止在同一帧中添加或删除实体
if (this._entitiesToAdded.contains(entity)){ if (this._entitiesToAdded.contains(entity)) {
this._entitiesToAdded.remove(entity); this._entitiesToAdded.remove(entity);
return; return;
} }
@@ -79,7 +79,7 @@ module es {
/** /**
* *
*/ */
public removeAllEntities(){ public removeAllEntities() {
this._unsortedTags.length = 0; this._unsortedTags.length = 0;
this._entitiesToAdded.length = 0; this._entitiesToAdded.length = 0;
this._isEntityListUnsorted = false; this._isEntityListUnsorted = false;
@@ -88,7 +88,7 @@ module es {
// 它们仍然在_entitiesToRemove列表中,该列表将由更新列表处理。 // 它们仍然在_entitiesToRemove列表中,该列表将由更新列表处理。
this.updateLists(); this.updateLists();
for (let i = 0; i < this._entities.length; i ++){ for (let i = 0; i < this._entities.length; i++) {
this._entities[i]._isDestroyed = true; this._entities[i]._isDestroyed = true;
this._entities[i].onRemovedFromScene(); this._entities[i].onRemovedFromScene();
this._entities[i].scene = null; this._entities[i].scene = null;
@@ -106,9 +106,9 @@ module es {
return this._entities.contains(entity) || this._entitiesToAdded.contains(entity); return this._entities.contains(entity) || this._entitiesToAdded.contains(entity);
} }
public getTagList(tag: number){ public getTagList(tag: number) {
let list = this._entityDict.get(tag); let list = this._entityDict.get(tag);
if (!list){ if (!list) {
list = []; list = [];
this._entityDict.set(tag, list); this._entityDict.set(tag, list);
} }
@@ -116,31 +116,31 @@ module es {
return this._entityDict.get(tag); return this._entityDict.get(tag);
} }
public addToTagList(entity: Entity){ public addToTagList(entity: Entity) {
let list = this.getTagList(entity.tag); let list = this.getTagList(entity.tag);
if (!list.contains(entity)){ if (!list.contains(entity)) {
list.push(entity); list.push(entity);
this._unsortedTags.push(entity.tag); this._unsortedTags.push(entity.tag);
} }
} }
public removeFromTagList(entity: Entity){ public removeFromTagList(entity: Entity) {
let list = this._entityDict.get(entity.tag); let list = this._entityDict.get(entity.tag);
if (list){ if (list) {
list.remove(entity); list.remove(entity);
} }
} }
public update(){ public update() {
for (let i = 0; i < this._entities.length; i++){ for (let i = 0; i < this._entities.length; i++) {
let entity = this._entities[i]; let entity = this._entities[i];
if (entity.enabled && (entity.updateInterval == 1 || Time.frameCount % entity.updateInterval == 0)) if (entity.enabled && (entity.updateInterval == 1 || Time.frameCount % entity.updateInterval == 0))
entity.update(); entity.update();
} }
} }
public updateLists(){ public updateLists() {
if (this._entitiesToRemove.length > 0){ if (this._entitiesToRemove.length > 0) {
let temp = this._entitiesToRemove; let temp = this._entitiesToRemove;
this._entitiesToRemove = this._tempEntityList; this._entitiesToRemove = this._tempEntityList;
this._tempEntityList = temp; this._tempEntityList = temp;
@@ -157,12 +157,12 @@ module es {
this._tempEntityList.length = 0; this._tempEntityList.length = 0;
} }
if (this._entitiesToAdded.length > 0){ if (this._entitiesToAdded.length > 0) {
let temp = this._entitiesToAdded; let temp = this._entitiesToAdded;
this._entitiesToAdded = this._tempEntityList; this._entitiesToAdded = this._tempEntityList;
this._tempEntityList = temp; this._tempEntityList = temp;
this._tempEntityList.forEach(entity => { this._tempEntityList.forEach(entity => {
if (!this._entities.contains(entity)){ if (!this._entities.contains(entity)) {
this._entities.push(entity); this._entities.push(entity);
entity.scene = this.scene; entity.scene = this.scene;
@@ -178,12 +178,12 @@ module es {
this._isEntityListUnsorted = true; this._isEntityListUnsorted = true;
} }
if (this._isEntityListUnsorted){ if (this._isEntityListUnsorted) {
this._entities.sort(); this._entities.sort();
this._isEntityListUnsorted = false; this._isEntityListUnsorted = false;
} }
if (this._unsortedTags.length > 0){ if (this._unsortedTags.length > 0) {
this._unsortedTags.forEach(tag => { this._unsortedTags.forEach(tag => {
this._entityDict.get(tag).sort(); this._entityDict.get(tag).sort();
}); });
@@ -196,8 +196,8 @@ module es {
* null * null
* @param name * @param name
*/ */
public findEntity(name: string){ public findEntity(name: string) {
for (let i = 0; i < this._entities.length; i ++){ for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].name == name) if (this._entities[i].name == name)
return this._entities[i]; return this._entities[i];
} }
@@ -209,11 +209,11 @@ module es {
* ListPool.free将返回的列表放回池中 * ListPool.free将返回的列表放回池中
* @param tag * @param tag
*/ */
public entitiesWithTag(tag: number){ public entitiesWithTag(tag: number) {
let list = this.getTagList(tag); let list = this.getTagList(tag);
let returnList = ListPool.obtain<Entity>(); let returnList = ListPool.obtain<Entity>();
for (let i = 0; i < list.length; i ++) for (let i = 0; i < list.length; i++)
returnList.push(list[i]); returnList.push(list[i]);
return returnList; return returnList;
@@ -223,9 +223,9 @@ module es {
* t类型的所有实体的列表ListPool.free放回池中 * t类型的所有实体的列表ListPool.free放回池中
* @param type * @param type
*/ */
public entitiesOfType<T extends Entity>(type): T[]{ public entitiesOfType<T extends Entity>(type): T[] {
let list = ListPool.obtain<T>(); let list = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i ++){ for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i] instanceof type) if (this._entities[i] instanceof type)
list.push(this._entities[i] as T); list.push(this._entities[i] as T);
} }
@@ -242,17 +242,17 @@ module es {
* @param type * @param type
*/ */
public findComponentOfType<T extends Component>(type): T { public findComponentOfType<T extends Component>(type): T {
for (let i = 0; i < this._entities.length; i ++){ for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].enabled){ if (this._entities[i].enabled) {
let comp = this._entities[i].getComponent<T>(type); let comp = this._entities[i].getComponent<T>(type);
if (comp) if (comp)
return comp; return comp;
} }
} }
for (let i = 0; i < this._entitiesToAdded.length; i ++){ for (let i = 0; i < this._entitiesToAdded.length; i++) {
let entity = this._entitiesToAdded[i]; let entity = this._entitiesToAdded[i];
if (entity.enabled){ if (entity.enabled) {
let comp = entity.getComponent<T>(type); let comp = entity.getComponent<T>(type);
if (comp) if (comp)
return comp; return comp;
@@ -266,17 +266,17 @@ module es {
* t的场景中找到的所有组件ListPool.free放回池中 * t的场景中找到的所有组件ListPool.free放回池中
* @param type * @param type
*/ */
public findComponentsOfType<T extends Component>(type): T[]{ public findComponentsOfType<T extends Component>(type): T[] {
let comps = ListPool.obtain<T>(); let comps = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i ++){ for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].enabled) if (this._entities[i].enabled)
this._entities[i].getComponents(type, comps); this._entities[i].getComponents(type, comps);
} }
for (let i = 0; i < this._entitiesToAdded.length; i ++){ for (let i = 0; i < this._entitiesToAdded.length; i++) {
let entity = this._entitiesToAdded[i]; let entity = this._entitiesToAdded[i];
if (entity.enabled) if (entity.enabled)
entity.getComponents(type,comps); entity.getComponents(type, comps);
} }
return comps; return comps;
+26 -26
View File
@@ -2,64 +2,52 @@ module es {
export class EntityProcessorList { export class EntityProcessorList {
private _processors: EntitySystem[] = []; private _processors: EntitySystem[] = [];
public add(processor: EntitySystem){ public add(processor: EntitySystem) {
this._processors.push(processor); this._processors.push(processor);
} }
public remove(processor: EntitySystem){ public remove(processor: EntitySystem) {
this._processors.remove(processor); this._processors.remove(processor);
} }
public onComponentAdded(entity: Entity){ public onComponentAdded(entity: Entity) {
this.notifyEntityChanged(entity); this.notifyEntityChanged(entity);
} }
public onComponentRemoved(entity: Entity){ public onComponentRemoved(entity: Entity) {
this.notifyEntityChanged(entity); this.notifyEntityChanged(entity);
} }
public onEntityAdded(entity: Entity){ public onEntityAdded(entity: Entity) {
this.notifyEntityChanged(entity); this.notifyEntityChanged(entity);
} }
public onEntityRemoved(entity: Entity){ public onEntityRemoved(entity: Entity) {
this.removeFromProcessors(entity); this.removeFromProcessors(entity);
} }
protected notifyEntityChanged(entity: Entity){ public begin() {
for (let i = 0; i < this._processors.length; i ++){
this._processors[i].onChanged(entity);
}
}
protected removeFromProcessors(entity: Entity){
for (let i = 0; i < this._processors.length; i ++){
this._processors[i].remove(entity);
}
}
public begin(){
} }
public update(){ public update() {
for (let i = 0; i < this._processors.length; i++){ for (let i = 0; i < this._processors.length; i++) {
this._processors[i].update(); this._processors[i].update();
} }
} }
public lateUpdate(){ public lateUpdate() {
for (let i = 0; i < this._processors.length; i ++){ for (let i = 0; i < this._processors.length; i++) {
this._processors[i].lateUpdate(); this._processors[i].lateUpdate();
} }
} }
public end(){ public end() {
} }
public getProcessor<T extends EntitySystem>(): T{ public getProcessor<T extends EntitySystem>(): T {
for (let i = 0; i < this._processors.length; i ++){ for (let i = 0; i < this._processors.length; i++) {
let processor = this._processors[i]; let processor = this._processors[i];
if (processor instanceof EntitySystem) if (processor instanceof EntitySystem)
return processor as T; return processor as T;
@@ -67,5 +55,17 @@ module es {
return null; return null;
} }
protected notifyEntityChanged(entity: Entity) {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].onChanged(entity);
}
}
protected removeFromProcessors(entity: Entity) {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].remove(entity);
}
}
} }
} }
+11 -11
View File
@@ -1,28 +1,28 @@
module es { module es {
export class Matcher{ export class Matcher {
protected allSet = new BitSet(); protected allSet = new BitSet();
protected exclusionSet = new BitSet(); protected exclusionSet = new BitSet();
protected oneSet = new BitSet(); protected oneSet = new BitSet();
public static empty(){ public static empty() {
return new Matcher(); return new Matcher();
} }
public getAllSet(){ public getAllSet() {
return this.allSet; return this.allSet;
} }
public getExclusionSet(){ public getExclusionSet() {
return this.exclusionSet; return this.exclusionSet;
} }
public getOneSet(){ public getOneSet() {
return this.oneSet; return this.oneSet;
} }
public IsIntersted(e: Entity){ public IsIntersted(e: Entity) {
if (!this.allSet.isEmpty()){ if (!this.allSet.isEmpty()) {
for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)){ for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)) {
if (!e.componentBits.get(i)) if (!e.componentBits.get(i))
return false; return false;
} }
@@ -37,7 +37,7 @@ module es {
return true; return true;
} }
public all(...types: any[]): Matcher{ public all(...types: any[]): Matcher {
types.forEach(type => { types.forEach(type => {
this.allSet.set(ComponentTypeManager.getIndexFor(type)); this.allSet.set(ComponentTypeManager.getIndexFor(type));
}); });
@@ -45,7 +45,7 @@ module es {
return this; return this;
} }
public exclude(...types: any[]){ public exclude(...types: any[]) {
types.forEach(type => { types.forEach(type => {
this.exclusionSet.set(ComponentTypeManager.getIndexFor(type)); this.exclusionSet.set(ComponentTypeManager.getIndexFor(type));
}); });
@@ -53,7 +53,7 @@ module es {
return this; return this;
} }
public one(...types: any[]){ public one(...types: any[]) {
types.forEach(type => { types.forEach(type => {
this.oneSet.set(ComponentTypeManager.getIndexFor(type)); this.oneSet.set(ComponentTypeManager.getIndexFor(type));
}); });
+6 -7
View File
@@ -1,17 +1,16 @@
class ObjectUtils { class ObjectUtils {
/** /**
* *
* @param p any * @param p any
* @param c any , , , * @param c any , , ,
*/ */
public static clone<T>(p: any, c: T = null): T { public static clone<T>(p: any, c: T = null): T {
var c = c || <T>{}; var c = c || <T>{};
for (let i in p) { for (let i in p) {
if (typeof p[i] === 'object') { if (typeof p[i] === 'object') {
c[i] = p[i] instanceof Array ? [] : {}; c[i] = p[i] instanceof Array ? [] : {};
this.clone(p[i], c[i]); this.clone(p[i], c[i]);
} } else {
else {
c[i] = p[i]; c[i] = p[i];
} }
} }
+54 -59
View File
@@ -1,9 +1,23 @@
class StringUtils { class StringUtils {
/** /**
* *
* @param str */
* @return private static specialSigns: string[] = [
*/ '&', '&amp;',
'<', '&lt;',
'>', '&gt;',
'"', '&quot;',
"'", '&apos;',
'®', '&reg;',
'©', '&copy;',
'™', '&trade;',
];
/**
*
* @param str
* @return
*/
public static matchChineseWord(str: string): string[] { public static matchChineseWord(str: string): string[] {
//中文字符的unicode值[\u4E00-\u9FA5] //中文字符的unicode值[\u4E00-\u9FA5]
let patternA: RegExp = /[\u4E00-\u9FA5]+/gim; let patternA: RegExp = /[\u4E00-\u9FA5]+/gim;
@@ -12,7 +26,7 @@ class StringUtils {
/** /**
* *
* @param target * @param target
* @return * @return
*/ */
public static lTrim(target: string): string { public static lTrim(target: string): string {
@@ -25,7 +39,7 @@ class StringUtils {
/** /**
* *
* @param target * @param target
* @return * @return
*/ */
public static rTrim(target: string): string { public static rTrim(target: string): string {
@@ -36,7 +50,6 @@ class StringUtils {
return target.slice(0, endIndex + 1); return target.slice(0, endIndex + 1);
} }
/** /**
* 2 * 2
* @param target * @param target
@@ -69,7 +82,7 @@ class StringUtils {
* @return * @return
*/ */
public static replaceMatch(mainStr: string, targetStr: string, public static replaceMatch(mainStr: string, targetStr: string,
replaceStr: string, caseMark: boolean = false): string { replaceStr: string, caseMark: boolean = false): string {
let len: number = mainStr.length; let len: number = mainStr.length;
let tempStr: string = ""; let tempStr: string = "";
let isMatch: boolean = false; let isMatch: boolean = false;
@@ -84,35 +97,18 @@ class StringUtils {
if (isMatch) { if (isMatch) {
tempStr += replaceStr; tempStr += replaceStr;
i = i + tempTarget.length - 1; i = i + tempTarget.length - 1;
} } else {
else {
tempStr += mainStr.charAt(i); tempStr += mainStr.charAt(i);
} }
} }
return tempStr; return tempStr;
} }
/**
*
*/
private static specialSigns: string[] = [
'&', '&amp;',
'<', '&lt;',
'>', '&gt;',
'"', '&quot;',
"'", '&apos;',
'®', '&reg;',
'©', '&copy;',
'™', '&trade;',
];
/** /**
* html实体换掉字符窜中的特殊字符 * html实体换掉字符窜中的特殊字符
* @param str * @param str
* @param reversion * @param reversion
* @return * @return
*/ */
public static htmlSpecialChars(str: string, reversion: boolean = false): string { public static htmlSpecialChars(str: string, reversion: boolean = false): string {
let len: number = this.specialSigns.length; let len: number = this.specialSigns.length;
@@ -133,27 +129,27 @@ class StringUtils {
/** /**
* "0" * "0"
* *
* <pre> * <pre>
* *
* trace( StringFormat.zfill('1') ); * trace( StringFormat.zfill('1') );
* // 01 * // 01
* *
* trace( StringFormat.zfill('16', 5) ); * trace( StringFormat.zfill('16', 5) );
* // 00016 * // 00016
* *
* trace( StringFormat.zfill('-3', 3) ); * trace( StringFormat.zfill('-3', 3) );
* // -03 * // -03
* *
* </pre> * </pre>
* *
* @param str * @param str
* @param width * @param width
* str.length >= widthstr * str.length >= widthstr
* @return * @return
* *
*/ */
public static zfill(str: string, width: number = 2): string { public static zfill(str: string, width: number = 2): string {
if (!str) { if (!str) {
return str; return str;
@@ -185,7 +181,7 @@ class StringUtils {
/** /**
* *
* @param str * @param str
* @return * @return
*/ */
public static reverse(str: string): string { public static reverse(str: string): string {
@@ -198,14 +194,14 @@ class StringUtils {
/** /**
* *
* @param str * @param str
* @param start * @param start
* @param len * @param len
* @param order true从字符串头部开始计算false从字符串尾巴开始结算 * @param order true从字符串头部开始计算false从字符串尾巴开始结算
* @return * @return
*/ */
public static cutOff(str: string, start: number, public static cutOff(str: string, start: number,
len: number, order: boolean = true): string { len: number, order: boolean = true): string {
start = Math.floor(start); start = Math.floor(start);
len = Math.floor(len); len = Math.floor(len);
let length: number = str.length; let length: number = str.length;
@@ -215,8 +211,7 @@ class StringUtils {
let newStr: string; let newStr: string;
if (order) { if (order) {
newStr = str.substring(0, s) + str.substr(e, length); newStr = str.substring(0, s) + str.substr(e, length);
} } else {
else {
s = length - 1 - start - len; s = length - 1 - start - len;
e = s + len; e = s + len;
newStr = str.substring(0, s + 1) + str.substr(e + 1, length); newStr = str.substring(0, s + 1) + str.substr(e + 1, length);
+9 -14
View File
@@ -6,15 +6,15 @@ module es {
public static sharedCanvas: HTMLCanvasElement; public static sharedCanvas: HTMLCanvasElement;
public static sharedContext: CanvasRenderingContext2D; public static sharedContext: CanvasRenderingContext2D;
public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement{ public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement {
if (!this.sharedCanvas){ if (!this.sharedCanvas) {
this.sharedCanvas = egret.sys.createCanvas(); this.sharedCanvas = egret.sys.createCanvas();
this.sharedContext = this.sharedCanvas.getContext("2d"); this.sharedContext = this.sharedCanvas.getContext("2d");
} }
let w = texture.$getTextureWidth(); let w = texture.$getTextureWidth();
let h = texture.$getTextureHeight(); let h = texture.$getTextureHeight();
if (!rect){ if (!rect) {
rect = egret.$TempRectangle; rect = egret.$TempRectangle;
rect.x = 0; rect.x = 0;
rect.y = 0; rect.y = 0;
@@ -44,8 +44,7 @@ module es {
} }
renderTexture = new egret.RenderTexture(); renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture)); renderTexture.drawToTexture(new egret.Bitmap(texture));
} } else {
else {
renderTexture = <egret.RenderTexture>texture; renderTexture = <egret.RenderTexture>texture;
} }
//从RenderTexture中读取像素数据,填入canvas //从RenderTexture中读取像素数据,填入canvas
@@ -71,8 +70,7 @@ module es {
} }
return surface; return surface;
} } else {
else {
let bitmapData = texture; let bitmapData = texture;
let offsetX: number = Math.round(bitmapData.$offsetX); let offsetX: number = Math.round(bitmapData.$offsetX);
let offsetY: number = Math.round(bitmapData.$offsetY); let offsetY: number = Math.round(bitmapData.$offsetY);
@@ -90,8 +88,7 @@ module es {
let surface = this.convertImageToCanvas(texture, rect); let surface = this.convertImageToCanvas(texture, rect);
let result = surface.toDataURL(type, encoderOptions); let result = surface.toDataURL(type, encoderOptions);
return result; return result;
} } catch (e) {
catch (e) {
egret.$error(1033); egret.$error(1033);
} }
return null; return null;
@@ -117,7 +114,7 @@ module es {
success: function (res) { success: function (res) {
//todo //todo
} }
}) });
return result; return result;
} }
@@ -135,8 +132,7 @@ module es {
if (!(<egret.RenderTexture>texture).$renderBuffer) { if (!(<egret.RenderTexture>texture).$renderBuffer) {
renderTexture = new egret.RenderTexture(); renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture)); renderTexture.drawToTexture(new egret.Bitmap(texture));
} } else {
else {
renderTexture = <egret.RenderTexture>texture; renderTexture = <egret.RenderTexture>texture;
} }
//从RenderTexture中读取像素数据 //从RenderTexture中读取像素数据
@@ -147,8 +143,7 @@ module es {
let surface = this.convertImageToCanvas(texture); let surface = this.convertImageToCanvas(texture);
let result = this.sharedContext.getImageData(x, y, width, height).data; let result = this.sharedContext.getImageData(x, y, width, height).data;
return <number[]><any>result; return <number[]><any>result;
} } catch (e) {
catch (e) {
egret.$error(1039); egret.$error(1039);
} }
} }
+5 -6
View File
@@ -9,22 +9,21 @@ module es {
public static timeScale = 1; public static timeScale = 1;
/** 已传递的帧总数 */ /** 已传递的帧总数 */
public static frameCount = 0; public static frameCount = 0;
private static _lastTime = 0;
/** 自场景加载以来的总时间 */ /** 自场景加载以来的总时间 */
public static _timeSinceSceneLoad; public static _timeSinceSceneLoad;
private static _lastTime = 0;
public static update(currentTime: number){ public static update(currentTime: number) {
let dt = (currentTime - this._lastTime) / 1000; let dt = (currentTime - this._lastTime) / 1000;
this.deltaTime = dt * this.timeScale; this.deltaTime = dt * this.timeScale;
this.unscaledDeltaTime = dt; this.unscaledDeltaTime = dt;
this._timeSinceSceneLoad += dt; this._timeSinceSceneLoad += dt;
this.frameCount ++; this.frameCount++;
this._lastTime = currentTime; this._lastTime = currentTime;
} }
public static sceneChanged(){ public static sceneChanged() {
this._timeSinceSceneLoad = 0; this._timeSinceSceneLoad = 0;
} }
@@ -32,7 +31,7 @@ module es {
* 使delta的间隔值true * 使delta的间隔值true
* @param interval * @param interval
*/ */
public static checkEvery(interval: number){ public static checkEvery(interval: number) {
// 我们减去了delta,因为timeSinceSceneLoad已经包含了这个update ticks delta // 我们减去了delta,因为timeSinceSceneLoad已经包含了这个update ticks delta
return (this._timeSinceSceneLoad / interval) > ((this._timeSinceSceneLoad - this.deltaTime) / interval); return (this._timeSinceSceneLoad / interval) > ((this._timeSinceSceneLoad - this.deltaTime) / interval);
} }
+13 -10
View File
@@ -1,9 +1,9 @@
class TimeUtils { class TimeUtils {
/** /**
* ID * ID
* @param d * @param d
* @returns ID * @returns ID
*/ */
public static monthId(d: Date = null): number { public static monthId(d: Date = null): number {
d = d ? d : new Date(); d = d ? d : new Date();
let y = d.getFullYear(); let y = d.getFullYear();
@@ -35,7 +35,8 @@ class TimeUtils {
d = d ? d : new Date(); d = d ? d : new Date();
let c: Date = new Date(); let c: Date = new Date();
c.setTime(d.getTime()); c.setTime(d.getTime());
c.setDate(1); c.setMonth(0);//当年第一天 c.setDate(1);
c.setMonth(0);//当年第一天
let year: number = c.getFullYear(); let year: number = c.getFullYear();
let firstDay: number = c.getDay(); let firstDay: number = c.getDay();
@@ -51,7 +52,8 @@ class TimeUtils {
} }
let num: number = this.diffDay(d, c, false); let num: number = this.diffDay(d, c, false);
if (num < 0) { if (num < 0) {
c.setDate(1); c.setMonth(0);//当年第一天 c.setDate(1);
c.setMonth(0);//当年第一天
c.setDate(c.getDate() - 1); c.setDate(c.getDate() - 1);
return this.weekId(c, false); return this.weekId(c, false);
} }
@@ -66,7 +68,8 @@ class TimeUtils {
} }
if (first && (!max || endDay < 4)) { if (first && (!max || endDay < 4)) {
c.setFullYear(c.getFullYear() + 1); c.setFullYear(c.getFullYear() + 1);
c.setDate(1); c.setMonth(0);//当年第一天 c.setDate(1);
c.setMonth(0);//当年第一天
return this.weekId(c, false); return this.weekId(c, false);
} }
} }
@@ -151,9 +154,9 @@ class TimeUtils {
/** /**
* *
* @param time * @param time
* @param partition * @param partition
* @param showHour * @param showHour
* @return , , * @return , ,
* *
* 比如: time = 4351; secondToTime(time)返回字符串01:12:31; * 比如: time = 4351; secondToTime(time)返回字符串01:12:31;
+1 -1
View File
@@ -309,7 +309,7 @@ Array.prototype.groupBy = function (keySelector) {
if (typeof (array.reduce) === "function") { if (typeof (array.reduce) === "function") {
let keys = []; let keys = [];
return array.reduce(function (groups, element, index) { return array.reduce(function (groups, element, index) {
let key = JSON.stringify(keySelector.call(arguments[1], element, index, array)) let key = JSON.stringify(keySelector.call(arguments[1], element, index, array));
let index2 = keys.findIndex(function (x) { let index2 = keys.findIndex(function (x) {
return x === key; return x === key;
}); });
@@ -64,8 +64,8 @@ module es {
"gl_FragColor = vec4(final_colour/(z*z), 1.0);\n" + "gl_FragColor = vec4(final_colour/(z*z), 1.0);\n" +
"}"; "}";
constructor(){ constructor() {
super(PostProcessor.default_vert, GaussianBlurEffect.blur_frag,{ super(PostProcessor.default_vert, GaussianBlurEffect.blur_frag, {
screenWidth: Core.graphicsDevice.viewport.width, screenWidth: Core.graphicsDevice.viewport.width,
screenHeight: Core.graphicsDevice.viewport.height screenHeight: Core.graphicsDevice.viewport.height
}); });
@@ -29,7 +29,7 @@ module es {
"gl_FragColor = c;\n" + "gl_FragColor = c;\n" +
"}"; "}";
constructor(){ constructor() {
super(PolygonLightEffect.vertSrc, PolygonLightEffect.fragmentSrc); super(PolygonLightEffect.vertSrc, PolygonLightEffect.fragmentSrc);
} }
} }
+5 -5
View File
@@ -1,11 +1,11 @@
module es { module es {
export class GraphicsCapabilities extends egret.Capabilities { export class GraphicsCapabilities extends egret.Capabilities {
public initialize(device: GraphicsDevice){ public initialize(device: GraphicsDevice) {
this.platformInitialize(device); this.platformInitialize(device);
} }
private platformInitialize(device: GraphicsDevice){ private platformInitialize(device: GraphicsDevice) {
if (GraphicsCapabilities.runtimeType != egret.RuntimeType.WXGAME) if (GraphicsCapabilities.runtimeType != egret.RuntimeType.WXGAME)
return; return;
let capabilities = this; let capabilities = this;
@@ -13,14 +13,14 @@ module es {
let systemInfo = wx.getSystemInfoSync(); let systemInfo = wx.getSystemInfoSync();
let systemStr = systemInfo.system.toLowerCase(); let systemStr = systemInfo.system.toLowerCase();
if (systemStr.indexOf("ios") > -1){ if (systemStr.indexOf("ios") > -1) {
capabilities["os"] = "iOS"; capabilities["os"] = "iOS";
} else if(systemStr.indexOf("android") > -1){ } else if (systemStr.indexOf("android") > -1) {
capabilities["os"] = "Android"; capabilities["os"] = "Android";
} }
let language = systemInfo.language; let language = systemInfo.language;
if (language.indexOf('zh') > -1){ if (language.indexOf('zh') > -1) {
language = "zh-CN"; language = "zh-CN";
} else { } else {
language = "en-US"; language = "en-US";
+8 -7
View File
@@ -1,19 +1,20 @@
module es { module es {
export class GraphicsDevice { export class GraphicsDevice {
private _viewport: Viewport;
public get viewport(): Viewport{
return this._viewport;
}
public graphicsCapabilities: GraphicsCapabilities; public graphicsCapabilities: GraphicsCapabilities;
constructor(){ constructor() {
this.setup(); this.setup();
this.graphicsCapabilities = new GraphicsCapabilities(); this.graphicsCapabilities = new GraphicsCapabilities();
this.graphicsCapabilities.initialize(this); this.graphicsCapabilities.initialize(this);
} }
private setup(){ private _viewport: Viewport;
public get viewport(): Viewport {
return this._viewport;
}
private setup() {
this._viewport = new Viewport(0, 0, Core._instance.stage.stageWidth, Core._instance.stage.stageHeight); this._viewport = new Viewport(0, 0, Core._instance.stage.stageWidth, Core._instance.stage.stageHeight);
} }
} }
@@ -1,10 +1,5 @@
module es { module es {
export class PostProcessor { export class PostProcessor {
public enabled: boolean;
public effect: egret.Filter;
public scene: Scene;
public shape: egret.Shape;
public static default_vert = "attribute vec2 aVertexPosition;\n" + public static default_vert = "attribute vec2 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" + "attribute vec2 aTextureCoord;\n" +
"attribute vec2 aColor;\n" + "attribute vec2 aColor;\n" +
@@ -22,13 +17,17 @@ module es {
"vTextureCoord = aTextureCoord;\n" + "vTextureCoord = aTextureCoord;\n" +
"vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n" + "vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n" +
"}"; "}";
public enabled: boolean;
public effect: egret.Filter;
public scene: Scene;
public shape: egret.Shape;
constructor(effect: egret.Filter = null){ constructor(effect: egret.Filter = null) {
this.enabled = true; this.enabled = true;
this.effect = effect; this.effect = effect;
} }
public onAddedToScene(scene: Scene){ public onAddedToScene(scene: Scene) {
this.scene = scene; this.scene = scene;
this.shape = new egret.Shape(); this.shape = new egret.Shape();
this.shape.graphics.beginFill(0xFFFFFF, 1); this.shape.graphics.beginFill(0xFFFFFF, 1);
@@ -37,24 +36,25 @@ module es {
scene.addChild(this.shape); scene.addChild(this.shape);
} }
public process(){ public process() {
this.drawFullscreenQuad(); this.drawFullscreenQuad();
} }
public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number){} public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number) {
protected drawFullscreenQuad(){
this.scene.filters = [this.effect];
// this.shape.filters = [this.effect];
} }
public unload(){ public unload() {
if (this.effect){ if (this.effect) {
this.effect = null; this.effect = null;
} }
this.scene.removeChild(this.shape); this.scene.removeChild(this.shape);
this.scene = null; this.scene = null;
} }
protected drawFullscreenQuad() {
this.scene.filters = [this.effect];
// this.shape.filters = [this.effect];
}
} }
} }
@@ -1,6 +1,6 @@
module es { module es {
export class GaussianBlurPostProcessor extends PostProcessor { export class GaussianBlurPostProcessor extends PostProcessor {
public onAddedToScene(scene: Scene){ public onAddedToScene(scene: Scene) {
super.onAddedToScene(scene); super.onAddedToScene(scene);
this.effect = new GaussianBlurEffect(); this.effect = new GaussianBlurEffect();
} }
@@ -1,7 +1,7 @@
///<reference path="./Renderer.ts" /> ///<reference path="./Renderer.ts" />
module es { module es {
export class DefaultRenderer extends Renderer { export class DefaultRenderer extends Renderer {
constructor(){ constructor() {
super(0, null); super(0, null);
} }
@@ -9,7 +9,7 @@ module es {
let cam = this.camera ? this.camera : scene.camera; let cam = this.camera ? this.camera : scene.camera;
this.beginRender(cam); this.beginRender(cam);
for (let i = 0; i < scene.renderableComponents.count; i++){ for (let i = 0; i < scene.renderableComponents.count; i++) {
let renderable = scene.renderableComponents.buffer[i]; let renderable = scene.renderableComponents.buffer[i];
if (renderable.enabled && renderable.isVisibleFromCamera(cam)) if (renderable.enabled && renderable.isVisibleFromCamera(cam))
this.renderAfterStateCheck(renderable, cam); this.renderAfterStateCheck(renderable, cam);
+1 -1
View File
@@ -40,7 +40,7 @@ module es {
* IRenderables的比较器 * IRenderables的比较器
*/ */
export class RenderableComparer { export class RenderableComparer {
public compare(self: IRenderable, other: IRenderable){ public compare(self: IRenderable, other: IRenderable) {
return other.renderLayer - self.renderLayer; return other.renderLayer - self.renderLayer;
} }
} }
@@ -1,18 +1,10 @@
module es { module es {
export class PolyLight extends RenderableComponent { export class PolyLight extends RenderableComponent {
public power: number; public power: number;
protected _radius: number;
private _lightEffect; private _lightEffect;
private _indices: number[] = []; private _indices: number[] = [];
public get radius(){ constructor(radius: number, color: number, power: number) {
return this._radius;
}
public set radius(value: number){
this.setRadius(value);
}
constructor(radius: number, color: number, power: number){
super(); super();
this.radius = radius; this.radius = radius;
@@ -21,18 +13,18 @@ module es {
this.computeTriangleIndices(); this.computeTriangleIndices();
} }
private computeTriangleIndices(totalTris: number = 20){ protected _radius: number;
this._indices.length = 0;
for (let i = 0; i < totalTris; i += 2){ public get radius() {
this._indices.push(0); return this._radius;
this._indices.push(i + 2);
this._indices.push(i + 1);
}
} }
public setRadius(radius: number){ public set radius(value: number) {
if (radius != this._radius){ this.setRadius(value);
}
public setRadius(radius: number) {
if (radius != this._radius) {
this._radius = radius; this._radius = radius;
this._areBoundsDirty = true; this._areBoundsDirty = true;
} }
@@ -41,8 +33,18 @@ module es {
public render(camera: Camera) { public render(camera: Camera) {
} }
public reset(){ public reset() {
} }
private computeTriangleIndices(totalTris: number = 20) {
this._indices.length = 0;
for (let i = 0; i < totalTris; i += 2) {
this._indices.push(0);
this._indices.push(i + 2);
this._indices.push(i + 1);
}
}
} }
} }
+23 -20
View File
@@ -14,7 +14,7 @@ module es {
*/ */
public readonly renderOrder: number = 0; public readonly renderOrder: number = 0;
protected constructor(renderOrder: number, camera: Camera = null){ protected constructor(renderOrder: number, camera: Camera = null) {
this.camera = camera; this.camera = camera;
this.renderOrder = renderOrder; this.renderOrder = renderOrder;
} }
@@ -23,41 +23,44 @@ module es {
* *
* @param scene * @param scene
*/ */
public onAddedToScene(scene: Scene){} public onAddedToScene(scene: Scene) {
}
/** /**
* 使 * 使
*/ */
public unload(){ } public unload() {
}
/**
*
* @param cam
*/
protected beginRender(cam: Camera){ }
public abstract render(scene: Scene); public abstract render(scene: Scene);
/**
*
* @param renderable
* @param cam
*/
protected renderAfterStateCheck(renderable: IRenderable, cam: Camera){
renderable.render(cam);
}
/** /**
* *
* @param newWidth * @param newWidth
* @param newHeight * @param newHeight
*/ */
public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number){ public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number) {
} }
public compareTo(other: Renderer): number{ public compareTo(other: Renderer): number {
return this.renderOrder - other.renderOrder; return this.renderOrder - other.renderOrder;
} }
/**
*
* @param cam
*/
protected beginRender(cam: Camera) {
}
/**
*
* @param renderable
* @param cam
*/
protected renderAfterStateCheck(renderable: IRenderable, cam: Camera) {
renderable.render(cam);
}
} }
} }
@@ -18,17 +18,17 @@ module es {
this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height); this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height);
this._mask.graphics.endFill(); this._mask.graphics.endFill();
egret.Tween.get(this).to({ _alpha: 1}, this.fadeOutDuration * 1000, this.fadeEaseType) egret.Tween.get(this).to({_alpha: 1}, this.fadeOutDuration * 1000, this.fadeEaseType)
.call(async () => { .call(async () => {
await this.loadNextScene(); await this.loadNextScene();
}).wait(this.delayBeforeFadeInDuration).call(() => { }).wait(this.delayBeforeFadeInDuration).call(() => {
egret.Tween.get(this).to({ _alpha: 0 }, this.fadeOutDuration * 1000, this.fadeEaseType).call(() => { egret.Tween.get(this).to({_alpha: 0}, this.fadeOutDuration * 1000, this.fadeEaseType).call(() => {
this.transitionComplete(); this.transitionComplete();
}); });
}); });
} }
public render(){ public render() {
this._mask.graphics.clear(); this._mask.graphics.clear();
this._mask.graphics.beginFill(this.fadeToColor, this._alpha); this._mask.graphics.beginFill(this.fadeToColor, this._alpha);
this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height); this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height);
@@ -3,7 +3,6 @@ module es {
* SceneTransition用于从一个场景过渡到另一个场景或在一个有效果的场景中过渡 * SceneTransition用于从一个场景过渡到另一个场景或在一个有效果的场景中过渡
*/ */
export abstract class SceneTransition { export abstract class SceneTransition {
private _hasPreviousSceneRender: boolean;
/** 是否加载新场景的标志 */ /** 是否加载新场景的标志 */
public loadsNewScene: boolean; public loadsNewScene: boolean;
/** /**
@@ -11,15 +10,22 @@ module es {
* isNewSceneLoaded应该在中点设置为true * isNewSceneLoaded应该在中点设置为true
*/ */
public isNewSceneLoaded: boolean; public isNewSceneLoaded: boolean;
/** 返回新加载场景的函数 */
protected sceneLoadAction: Function;
/** 在loadNextScene执行时调用。这在进行场景间过渡时很有用,这样你就知道什么时候可以更多地使用相机或者重置任何实体 */ /** 在loadNextScene执行时调用。这在进行场景间过渡时很有用,这样你就知道什么时候可以更多地使用相机或者重置任何实体 */
public onScreenObscured: Function; public onScreenObscured: Function;
/** 当转换完成执行时调用,以便可以调用其他工作,比如启动另一个转换。 */ /** 当转换完成执行时调用,以便可以调用其他工作,比如启动另一个转换。 */
public onTransitionCompleted: Function; public onTransitionCompleted: Function;
/** 返回新加载场景的函数 */
protected sceneLoadAction: Function;
public get hasPreviousSceneRender(){ constructor(sceneLoadAction: Function) {
if (!this._hasPreviousSceneRender){ this.sceneLoadAction = sceneLoadAction;
this.loadsNewScene = sceneLoadAction != null;
}
private _hasPreviousSceneRender: boolean;
public get hasPreviousSceneRender() {
if (!this._hasPreviousSceneRender) {
this._hasPreviousSceneRender = true; this._hasPreviousSceneRender = true;
return false; return false;
} }
@@ -27,13 +33,9 @@ module es {
return true; return true;
} }
constructor(sceneLoadAction: Function) { public preRender() {
this.sceneLoadAction = sceneLoadAction;
this.loadsNewScene = sceneLoadAction != null;
} }
public preRender() { }
public render() { public render() {
} }
@@ -43,6 +45,17 @@ module es {
this.transitionComplete(); this.transitionComplete();
} }
public tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection = false): Promise<boolean> {
return new Promise((resolve) => {
let start = reverseDirection ? 1 : 0;
let end = reverseDirection ? 0 : 1;
egret.Tween.get(filter.uniforms).set({_progress: start}).to({_progress: end}, duration * 1000, easeType).call(() => {
resolve();
});
});
}
protected transitionComplete() { protected transitionComplete() {
Core._instance._sceneTransition = null; Core._instance._sceneTransition = null;
@@ -62,16 +75,5 @@ module es {
Core.scene = await this.sceneLoadAction(); Core.scene = await this.sceneLoadAction();
this.isNewSceneLoaded = true; this.isNewSceneLoaded = true;
} }
public tickEffectProgressProperty(filter: egret.CustomFilter, duration: number, easeType: Function, reverseDirection = false): Promise<boolean>{
return new Promise((resolve)=>{
let start = reverseDirection ? 1 : 0;
let end = reverseDirection ? 0 : 1;
egret.Tween.get(filter.uniforms).set({_progress: start}).to({_progress: end}, duration * 1000, easeType).call(()=>{
resolve();
});
});
}
} }
} }
@@ -1,20 +1,14 @@
module es { module es {
export class WindTransition extends SceneTransition { export class WindTransition extends SceneTransition {
public duration = 1;
public easeType = egret.Ease.quadOut;
private _mask: egret.Shape; private _mask: egret.Shape;
private _windEffect: egret.CustomFilter; private _windEffect: egret.CustomFilter;
public duration = 1;
public set windSegments(value: number) {
this._windEffect.uniforms._windSegments = value;
}
public set size(value: number) {
this._windEffect.uniforms._size = value;
}
public easeType = egret.Ease.quadOut;
constructor(sceneLoadAction: Function) { constructor(sceneLoadAction: Function) {
super(sceneLoadAction); super(sceneLoadAction);
let vertexSrc = "attribute vec2 aVertexPosition;\n" + let vertexSrc = "attribute vec2 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" + "attribute vec2 aTextureCoord;\n" +
"uniform vec2 projectionVector;\n" + "uniform vec2 projectionVector;\n" +
@@ -56,6 +50,14 @@ module es {
this._mask.filters = [this._windEffect]; this._mask.filters = [this._windEffect];
} }
public set windSegments(value: number) {
this._windEffect.uniforms._windSegments = value;
}
public set size(value: number) {
this._windEffect.uniforms._size = value;
}
public async onBeginTransition() { public async onBeginTransition() {
this.loadNextScene(); this.loadNextScene();
await this.tickEffectProgressProperty(this._windEffect, this.duration, this.easeType); await this.tickEffectProgressProperty(this._windEffect, this.duration, this.easeType);
+38 -33
View File
@@ -2,42 +2,10 @@ module es {
export class Viewport { export class Viewport {
private _x: number; private _x: number;
private _y: number; private _y: number;
private _width: number;
private _height: number;
private _minDepth: number; private _minDepth: number;
private _maxDepth: number; private _maxDepth: number;
public get height(){ constructor(x: number, y: number, width: number, height: number) {
return this._height;
}
public set height(value: number){
this._height = value;
}
public get width(){
return this._width;
}
public set width(value: number){
this._width = value;
}
public get aspectRatio(){
if ((this._height != 0) && (this._width != 0))
return (this._width / this._height);
return 0;
}
public get bounds(){
return new Rectangle(this._x, this._y, this._width, this._height);
}
public set bounds(value: Rectangle){
this._x = value.x;
this._y = value.y;
this._width = value.width;
this._height = value.height;
}
constructor(x: number, y: number, width: number, height: number){
this._x = x; this._x = x;
this._y = y; this._y = y;
this._width = width; this._width = width;
@@ -46,5 +14,42 @@ module es {
this._maxDepth = 1; this._maxDepth = 1;
} }
private _width: number;
public get width() {
return this._width;
}
public set width(value: number) {
this._width = value;
}
private _height: number;
public get height() {
return this._height;
}
public set height(value: number) {
this._height = value;
}
public get aspectRatio() {
if ((this._height != 0) && (this._width != 0))
return (this._width / this._height);
return 0;
}
public get bounds() {
return new Rectangle(this._x, this._y, this._width, this._height);
}
public set bounds(value: Rectangle) {
this._x = value.x;
this._y = value.y;
this._width = value.width;
this._height = value.height;
}
} }
} }
+6 -6
View File
@@ -11,7 +11,7 @@ module es {
* @param self * @param self
* @param flag * @param flag
*/ */
public static isFlagSet(self: number, flag: number): boolean{ public static isFlagSet(self: number, flag: number): boolean {
return (self & flag) != 0; return (self & flag) != 0;
} }
@@ -20,7 +20,7 @@ module es {
* @param self * @param self
* @param flag * @param flag
*/ */
public static isUnshiftedFlagSet(self: number, flag: number): boolean{ public static isUnshiftedFlagSet(self: number, flag: number): boolean {
flag = 1 << flag; flag = 1 << flag;
return (self & flag) != 0; return (self & flag) != 0;
} }
@@ -30,7 +30,7 @@ module es {
* @param self * @param self
* @param flag * @param flag
*/ */
public static setFlagExclusive(self: number, flag: number){ public static setFlagExclusive(self: number, flag: number) {
return 1 << flag; return 1 << flag;
} }
@@ -39,7 +39,7 @@ module es {
* @param self * @param self
* @param flag * @param flag
*/ */
public static setFlag(self: number, flag: number){ public static setFlag(self: number, flag: number) {
return (self | 1 << flag); return (self | 1 << flag);
} }
@@ -48,7 +48,7 @@ module es {
* @param self * @param self
* @param flag * @param flag
*/ */
public static unsetFlag(self: number, flag: number){ public static unsetFlag(self: number, flag: number) {
flag = 1 << flag; flag = 1 << flag;
return (self & (~flag)); return (self & (~flag));
} }
@@ -57,7 +57,7 @@ module es {
* *
* @param self * @param self
*/ */
public static invertFlags(self: number){ public static invertFlags(self: number) {
return ~self; return ~self;
} }
} }
+9 -9
View File
@@ -8,7 +8,7 @@ module es {
* *
* @param radians * @param radians
*/ */
public static toDegrees(radians: number){ public static toDegrees(radians: number) {
return radians * 57.295779513082320876798154814105; return radians * 57.295779513082320876798154814105;
} }
@@ -16,7 +16,7 @@ module es {
* *
* @param degrees * @param degrees
*/ */
public static toRadians(degrees: number){ public static toRadians(degrees: number) {
return degrees * 0.017453292519943295769236907684886; return degrees * 0.017453292519943295769236907684886;
} }
@@ -28,15 +28,15 @@ module es {
* @param rightMin * @param rightMin
* @param rightMax * @param rightMax
*/ */
public static map(value: number, leftMin: number, leftMax: number, rightMin: number, rightMax: number){ public static map(value: number, leftMin: number, leftMax: number, rightMin: number, rightMax: number) {
return rightMin + (value - leftMin) * (rightMax - rightMin) / (leftMax - leftMin); return rightMin + (value - leftMin) * (rightMax - rightMin) / (leftMax - leftMin);
} }
public static lerp(value1: number, value2: number, amount: number){ public static lerp(value1: number, value2: number, amount: number) {
return value1 + (value2 - value1) * amount; return value1 + (value2 - value1) * amount;
} }
public static clamp(value: number, min: number, max: number){ public static clamp(value: number, min: number, max: number) {
if (value < min) if (value < min)
return min; return min;
@@ -46,7 +46,7 @@ module es {
return value; return value;
} }
public static pointOnCirlce(circleCenter: Vector2, radius: number, angleInDegrees: number){ public static pointOnCirlce(circleCenter: Vector2, radius: number, angleInDegrees: number) {
let radians = MathHelper.toRadians(angleInDegrees); let radians = MathHelper.toRadians(angleInDegrees);
return new Vector2(Math.cos(radians) * radians + circleCenter.x, Math.sin(radians) * radians + circleCenter.y); return new Vector2(Math.cos(radians) * radians + circleCenter.x, Math.sin(radians) * radians + circleCenter.y);
} }
@@ -55,7 +55,7 @@ module es {
* true * true
* @param value * @param value
*/ */
public static isEven(value: number){ public static isEven(value: number) {
return value % 2 == 0; return value % 2 == 0;
} }
@@ -63,7 +63,7 @@ module es {
* 0-1 * 0-1
* @param value * @param value
*/ */
public static clamp01(value: number){ public static clamp01(value: number) {
if (value < 0) if (value < 0)
return 0; return 0;
@@ -73,7 +73,7 @@ module es {
return value; return value;
} }
public static angleBetweenVectors(from: Vector2, to: Vector2){ public static angleBetweenVectors(from: Vector2, to: Vector2) {
return Math.atan2(to.y - from.y, to.x - from.x); return Math.atan2(to.y - from.y, to.x - from.x);
} }
} }
+38 -26
View File
@@ -1,57 +1,69 @@
module es { module es {
export var matrixPool = []; export var matrixPool = [];
/** /**
* 3 * 3 * 3 * 3
*/ */
export class Matrix2D extends egret.Matrix{ export class Matrix2D extends egret.Matrix {
public get m11(): number{ public get m11(): number {
return this.a; return this.a;
} }
public set m11(value: number){
public set m11(value: number) {
this.a = value; this.a = value;
} }
public get m12(): number{
public get m12(): number {
return this.b; return this.b;
} }
public set m12(value: number){
public set m12(value: number) {
this.b = value; this.b = value;
} }
public get m21(): number{
public get m21(): number {
return this.c; return this.c;
} }
public set m21(value: number){
public set m21(value: number) {
this.c = value; this.c = value;
} }
public get m22(): number{
public get m22(): number {
return this.d; return this.d;
} }
public set m22(value: number){
public set m22(value: number) {
this.d = value; this.d = value;
} }
public get m31(): number { public get m31(): number {
return this.tx; return this.tx;
} }
public set m31(value: number){
public set m31(value: number) {
this.tx = value; this.tx = value;
} }
public get m32(): number{
public get m32(): number {
return this.ty; return this.ty;
} }
public set m32(value: number){
public set m32(value: number) {
this.ty = value; this.ty = value;
} }
/** /**
* Matrix对象 * Matrix对象
*/ */
public static create(): Matrix2D{ public static create(): Matrix2D {
let matrix = matrixPool.pop(); let matrix = matrixPool.pop();
if (!matrix) if (!matrix)
matrix = new Matrix2D(); matrix = new Matrix2D();
return matrix; return matrix;
} }
public identity(): Matrix2D{ public identity(): Matrix2D {
this.a = this.d = 1; this.a = this.d = 1;
this.b = this.c = this.tx = this.ty = 0; this.b = this.c = this.tx = this.ty = 0;
return this; return this;
@@ -64,12 +76,12 @@ module es {
} }
public scale(sx: number, sy: number): Matrix2D { public scale(sx: number, sy: number): Matrix2D {
if (sx !== 1){ if (sx !== 1) {
this.a *= sx; this.a *= sx;
this.c *= sx; this.c *= sx;
this.tx *= sx; this.tx *= sx;
} }
if (sy !== 1){ if (sy !== 1) {
this.b *= sy; this.b *= sy;
this.d *= sy; this.d *= sy;
this.ty *= sy; this.ty *= sy;
@@ -108,7 +120,7 @@ module es {
* matrix, * matrix,
* @param matrix * @param matrix
*/ */
public add(matrix: Matrix2D): Matrix2D{ public add(matrix: Matrix2D): Matrix2D {
this.m11 += matrix.m11; this.m11 += matrix.m11;
this.m12 += matrix.m12; this.m12 += matrix.m12;
@@ -134,7 +146,7 @@ module es {
return this; return this;
} }
public divide(matrix: Matrix2D): Matrix2D{ public divide(matrix: Matrix2D): Matrix2D {
this.m11 /= matrix.m11; this.m11 /= matrix.m11;
this.m12 /= matrix.m12; this.m12 /= matrix.m12;
@@ -147,15 +159,15 @@ module es {
return this; return this;
} }
public multiply(matrix: Matrix2D): Matrix2D{ public multiply(matrix: Matrix2D): Matrix2D {
let m11 = ( this.m11 * matrix.m11 ) + ( this.m12 * matrix.m21 ); let m11 = (this.m11 * matrix.m11) + (this.m12 * matrix.m21);
let m12 = ( this.m11 * matrix.m12 ) + ( this.m12 * matrix.m22 ); let m12 = (this.m11 * matrix.m12) + (this.m12 * matrix.m22);
let m21 = ( this.m21 * matrix.m11 ) + ( this.m22 * matrix.m21 ); let m21 = (this.m21 * matrix.m11) + (this.m22 * matrix.m21);
let m22 = ( this.m21 * matrix.m12 ) + ( this.m22 * matrix.m22 ); let m22 = (this.m21 * matrix.m12) + (this.m22 * matrix.m22);
let m31 = ( this.m31 * matrix.m11 ) + ( this.m32 * matrix.m21 ) + matrix.m31; let m31 = (this.m31 * matrix.m11) + (this.m32 * matrix.m21) + matrix.m31;
let m32 = ( this.m31 * matrix.m12 ) + ( this.m32 * matrix.m22 ) + matrix.m32; let m32 = (this.m31 * matrix.m12) + (this.m32 * matrix.m22) + matrix.m32;
this.m11 = m11; this.m11 = m11;
this.m12 = m12; this.m12 = m12;
@@ -169,7 +181,7 @@ module es {
return this; return this;
} }
public determinant(){ public determinant() {
return this.m11 * this.m22 - this.m12 * this.m21; return this.m11 * this.m22 - this.m12 * this.m21;
} }
+39 -37
View File
@@ -2,6 +2,7 @@ module es {
export class Rectangle extends egret.Rectangle { export class Rectangle extends egret.Rectangle {
public _tempMat: Matrix2D; public _tempMat: Matrix2D;
public _transformMat: Matrix2D; public _transformMat: Matrix2D;
/** /**
* *
*/ */
@@ -18,6 +19,7 @@ module es {
public get location() { public get location() {
return new Vector2(this.x, this.y); return new Vector2(this.x, this.y);
} }
/** 左上角的坐标 */ /** 左上角的坐标 */
public set location(value: Vector2) { public set location(value: Vector2) {
this.x = value.x; this.x = value.x;
@@ -33,6 +35,41 @@ module es {
this.height = value.y; this.height = value.y;
} }
/**
* /()
* @param minX
* @param minY
* @param maxX
* @param maxY
*/
public static fromMinMax(minX: number, minY: number, maxX: number, maxY: number) {
return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}
/**
*
* @param points
*/
public static rectEncompassingPoints(points: Vector2[]) {
// 我们需要求出x/y的最小值/最大值
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
for (let i = 0; i < points.length; i++) {
let pt = points[i];
if (pt.x < minX) minX = pt.x;
if (pt.x > maxX) maxX = pt.x;
if (pt.y < minY) minY = pt.y;
if (pt.y > maxY) maxY = pt.y;
}
return this.fromMinMax(minX, minY, maxX, maxY);
}
/** /**
* *
* @param value * @param value
@@ -58,17 +95,6 @@ module es {
return new Vector2(this.width * 0.5, this.height * 0.5); return new Vector2(this.width * 0.5, this.height * 0.5);
} }
/**
* /()
* @param minX
* @param minY
* @param maxX
* @param maxY
*/
public static fromMinMax(minX: number, minY: number, maxX: number, maxY: number) {
return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}
/** /**
* *
* @param point * @param point
@@ -142,8 +168,8 @@ module es {
return boundsPoint; return boundsPoint;
} }
public calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number){ public calculateBounds(parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2, rotation: number, width: number, height: number) {
if (rotation == 0){ if (rotation == 0) {
this.x = parentPosition.x + position.x - origin.x * scale.x; this.x = parentPosition.x + position.x - origin.x * scale.x;
this.y = parentPosition.y + position.y - origin.y * scale.y; this.y = parentPosition.y + position.y - origin.y * scale.y;
this.width = width * scale.x; this.width = width * scale.x;
@@ -183,29 +209,5 @@ module es {
this.height = maxY - minY; this.height = maxY - minY;
} }
} }
/**
*
* @param points
*/
public static rectEncompassingPoints(points: Vector2[]) {
// 我们需要求出x/y的最小值/最大值
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
for (let i = 0; i < points.length; i++) {
let pt = points[i];
if (pt.x < minX) minX = pt.x;
if (pt.x > maxX) maxX = pt.x;
if (pt.y < minY) minY = pt.y;
if (pt.y > maxY) maxY = pt.y;
}
return this.fromMinMax(minX, minY, maxX, maxY);
}
} }
} }
+81 -81
View File
@@ -1,77 +1,37 @@
module es { module es {
/** 2d 向量 */ /** 2d 向量 */
export class Vector2 { export class Vector2 {
public x: number = 0;
public y: number = 0;
private static readonly unitYVector = new Vector2(0, 1); private static readonly unitYVector = new Vector2(0, 1);
private static readonly unitXVector = new Vector2(1, 0); private static readonly unitXVector = new Vector2(1, 0);
private static readonly unitVector2 = new Vector2(1, 1); private static readonly unitVector2 = new Vector2(1, 1);
private static readonly zeroVector2 = new Vector2(0, 0); private static readonly zeroVector2 = new Vector2(0, 0);
public static get zero(){ public x: number = 0;
return Vector2.zeroVector2; public y: number = 0;
}
public static get one(){
return Vector2.unitVector2;
}
public static get unitX(){
return Vector2.unitXVector;
}
public static get unitY(){
return Vector2.unitYVector;
}
/** /**
* X和Y的二维向量 * X和Y的二维向量
* @param x x坐标 * @param x x坐标
* @param y y坐标 * @param y y坐标
*/ */
constructor(x? : number, y?: number){ constructor(x?: number, y?: number) {
this.x = x ? x : 0; this.x = x ? x : 0;
this.y = y ? y : this.x; this.y = y ? y : this.x;
} }
/** public static get zero() {
* return Vector2.zeroVector2;
* @param value
*/
public add(value: Vector2): Vector2{
this.x += value.x;
this.y += value.y;
return this;
} }
/** public static get one() {
* return Vector2.unitVector2;
* @param value
*/
public divide(value: Vector2): Vector2{
this.x /= value.x;
this.y /= value.y;
return this;
} }
/** public static get unitX() {
* return Vector2.unitXVector;
* @param value
*/
public multiply(value: Vector2): Vector2{
this.x *= value.x;
this.y *= value.y;
return this;
} }
/** public static get unitY() {
* return Vector2.unitYVector;
* @param value
*/
public subtract(value: Vector2){
this.x -= value.x;
this.y -= value.y;
return this;
} }
/** /**
@@ -79,7 +39,7 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static add(value1: Vector2, value2: Vector2){ public static add(value1: Vector2, value2: Vector2) {
let result: Vector2 = new Vector2(0, 0); let result: Vector2 = new Vector2(0, 0);
result.x = value1.x + value2.x; result.x = value1.x + value2.x;
result.y = value1.y + value2.y; result.y = value1.y + value2.y;
@@ -91,7 +51,7 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static divide(value1: Vector2, value2: Vector2){ public static divide(value1: Vector2, value2: Vector2) {
let result: Vector2 = new Vector2(0, 0); let result: Vector2 = new Vector2(0, 0);
result.x = value1.x / value2.x; result.x = value1.x / value2.x;
result.y = value1.y / value2.y; result.y = value1.y / value2.y;
@@ -103,7 +63,7 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static multiply(value1: Vector2, value2: Vector2){ public static multiply(value1: Vector2, value2: Vector2) {
let result: Vector2 = new Vector2(0, 0); let result: Vector2 = new Vector2(0, 0);
result.x = value1.x * value2.x; result.x = value1.x * value2.x;
result.y = value1.y * value2.y; result.y = value1.y * value2.y;
@@ -115,36 +75,19 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static subtract(value1: Vector2, value2: Vector2){ public static subtract(value1: Vector2, value2: Vector2) {
let result: Vector2 = new Vector2(0, 0); let result: Vector2 = new Vector2(0, 0);
result.x = value1.x - value2.x; result.x = value1.x - value2.x;
result.y = value1.y - value2.y; result.y = value1.y - value2.y;
return result; return result;
} }
/** 变成一个方向相同的单位向量 */
public normalize(){
let val = 1 / Math.sqrt((this.x * this.x) + (this.y * this.y));
this.x *= val;
this.y *= val;
}
/** 返回它的长度 */
public length(){
return Math.sqrt((this.x * this.x) + (this.y * this.y));
}
/** 对x和y值四舍五入 */
public round(): Vector2{
return new Vector2(Math.round(this.x), Math.round(this.y));
}
/** /**
* Vector2 * Vector2
* *
* @param value * @param value
*/ */
public static normalize(value: Vector2){ public static normalize(value: Vector2) {
let val = 1 / Math.sqrt((value.x * value.x) + (value.y * value.y)); let val = 1 / Math.sqrt((value.x * value.x) + (value.y * value.y));
value.x *= val; value.x *= val;
value.y *= val; value.y *= val;
@@ -156,7 +99,7 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static dot(value1: Vector2, value2: Vector2): number{ public static dot(value1: Vector2, value2: Vector2): number {
return (value1.x * value2.x) + (value1.y * value2.y); return (value1.x * value2.x) + (value1.y * value2.y);
} }
@@ -165,7 +108,7 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static distanceSquared(value1: Vector2, value2: Vector2){ public static distanceSquared(value1: Vector2, value2: Vector2) {
let v1 = value1.x - value2.x, v2 = value1.y - value2.y; let v1 = value1.x - value2.x, v2 = value1.y - value2.y;
return (v1 * v1) + (v2 * v2); return (v1 * v1) + (v2 * v2);
} }
@@ -176,7 +119,7 @@ module es {
* @param min * @param min
* @param max * @param max
*/ */
public static clamp(value1: Vector2, min: Vector2, max: Vector2){ public static clamp(value1: Vector2, min: Vector2, max: Vector2) {
return new Vector2(MathHelper.clamp(value1.x, min.x, max.x), return new Vector2(MathHelper.clamp(value1.x, min.x, max.x),
MathHelper.clamp(value1.y, min.y, max.y)); MathHelper.clamp(value1.y, min.y, max.y));
} }
@@ -187,7 +130,7 @@ module es {
* @param value2 * @param value2
* @param amount (0.01.0) * @param amount (0.01.0)
*/ */
public static lerp(value1: Vector2, value2: Vector2, amount: number){ public static lerp(value1: Vector2, value2: Vector2, amount: number) {
return new Vector2(MathHelper.lerp(value1.x, value2.x, amount), MathHelper.lerp(value1.y, value2.y, amount)); return new Vector2(MathHelper.lerp(value1.x, value2.x, amount), MathHelper.lerp(value1.y, value2.y, amount));
} }
@@ -196,7 +139,7 @@ module es {
* @param position * @param position
* @param matrix * @param matrix
*/ */
public static transform(position: Vector2, matrix: Matrix2D){ public static transform(position: Vector2, matrix: Matrix2D) {
return new Vector2((position.x * matrix.m11) + (position.y * matrix.m21) + matrix.m31, return new Vector2((position.x * matrix.m11) + (position.y * matrix.m21) + matrix.m31,
(position.x * matrix.m12) + (position.y * matrix.m22) + matrix.m32); (position.x * matrix.m12) + (position.y * matrix.m22) + matrix.m32);
} }
@@ -206,7 +149,7 @@ module es {
* @param value1 * @param value1
* @param value2 * @param value2
*/ */
public static distance(value1: Vector2, value2: Vector2){ public static distance(value1: Vector2, value2: Vector2) {
let v1 = value1.x - value2.x, v2 = value1.y - value2.y; let v1 = value1.x - value2.x, v2 = value1.y - value2.y;
return Math.sqrt((v1 * v1) + (v2 * v2)); return Math.sqrt((v1 * v1) + (v2 * v2));
} }
@@ -215,7 +158,7 @@ module es {
* *
* @param value * @param value
*/ */
public static negate(value: Vector2){ public static negate(value: Vector2) {
let result: Vector2 = new Vector2(); let result: Vector2 = new Vector2();
result.x = -value.x; result.x = -value.x;
result.y = -value.y; result.y = -value.y;
@@ -223,7 +166,64 @@ module es {
return result; return result;
} }
public equals(other: Vector2){ /**
*
* @param value
*/
public add(value: Vector2): Vector2 {
this.x += value.x;
this.y += value.y;
return this;
}
/**
*
* @param value
*/
public divide(value: Vector2): Vector2 {
this.x /= value.x;
this.y /= value.y;
return this;
}
/**
*
* @param value
*/
public multiply(value: Vector2): Vector2 {
this.x *= value.x;
this.y *= value.y;
return this;
}
/**
*
* @param value
*/
public subtract(value: Vector2) {
this.x -= value.x;
this.y -= value.y;
return this;
}
/** 变成一个方向相同的单位向量 */
public normalize() {
let val = 1 / Math.sqrt((this.x * this.x) + (this.y * this.y));
this.x *= val;
this.y *= val;
}
/** 返回它的长度 */
public length() {
return Math.sqrt((this.x * this.x) + (this.y * this.y));
}
/** 对x和y值四舍五入 */
public round(): Vector2 {
return new Vector2(Math.round(this.x), Math.round(this.y));
}
public equals(other: Vector2) {
return other.x == this.x && other.y == this.y; return other.x == this.x && other.y == this.y;
} }
} }
+1 -1
View File
@@ -4,7 +4,7 @@ module es {
public y: number; public y: number;
public z: number; public z: number;
constructor(x: number, y: number, z: number){ constructor(x: number, y: number, z: number) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
+10 -10
View File
@@ -50,8 +50,8 @@ module es {
this.checkForExitedColliders(); this.checkForExitedColliders();
} }
private checkForExitedColliders(){ private checkForExitedColliders() {
for (let i = 0; i < this._activeTriggerIntersections.length; i ++){ for (let i = 0; i < this._activeTriggerIntersections.length; i++) {
let index = this._previousTriggerIntersections.findIndex(value => { let index = this._previousTriggerIntersections.findIndex(value => {
if (value.first == this._activeTriggerIntersections[i].first && value.second == this._activeTriggerIntersections[i].second) if (value.first == this._activeTriggerIntersections[i].first && value.second == this._activeTriggerIntersections[i].second)
return true; return true;
@@ -62,12 +62,12 @@ module es {
this._previousTriggerIntersections.removeAt(index); this._previousTriggerIntersections.removeAt(index);
} }
for (let i = 0; i < this._previousTriggerIntersections.length; i ++){ for (let i = 0; i < this._previousTriggerIntersections.length; i++) {
this.notifyTriggerListeners(this._previousTriggerIntersections[i], false) this.notifyTriggerListeners(this._previousTriggerIntersections[i], false)
} }
this._previousTriggerIntersections.length = 0; this._previousTriggerIntersections.length = 0;
for (let i = 0; i < this._activeTriggerIntersections.length; i ++){ for (let i = 0; i < this._activeTriggerIntersections.length; i++) {
if (!this._previousTriggerIntersections.contains(this._activeTriggerIntersections[i])){ if (!this._previousTriggerIntersections.contains(this._activeTriggerIntersections[i])) {
this._previousTriggerIntersections.push(this._activeTriggerIntersections[i]); this._previousTriggerIntersections.push(this._activeTriggerIntersections[i]);
} }
} }
@@ -76,8 +76,8 @@ module es {
private notifyTriggerListeners(collisionPair: Pair<Collider>, isEntering: boolean) { private notifyTriggerListeners(collisionPair: Pair<Collider>, isEntering: boolean) {
collisionPair.first.entity.getComponents("ITriggerListener", this._tempTriggerList); collisionPair.first.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i ++){ for (let i = 0; i < this._tempTriggerList.length; i++) {
if (isEntering){ if (isEntering) {
this._tempTriggerList[i].onTriggerEnter(collisionPair.second, collisionPair.first); this._tempTriggerList[i].onTriggerEnter(collisionPair.second, collisionPair.first);
} else { } else {
this._tempTriggerList[i].onTriggerExit(collisionPair.second, collisionPair.first); this._tempTriggerList[i].onTriggerExit(collisionPair.second, collisionPair.first);
@@ -85,10 +85,10 @@ module es {
this._tempTriggerList.length = 0; this._tempTriggerList.length = 0;
if (collisionPair.second.entity){ if (collisionPair.second.entity) {
collisionPair.second.entity.getComponents("ITriggerListener", this._tempTriggerList); collisionPair.second.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i ++){ for (let i = 0; i < this._tempTriggerList.length; i++) {
if (isEntering){ if (isEntering) {
this._tempTriggerList[i].onTriggerEnter(collisionPair.first, collisionPair.second); this._tempTriggerList[i].onTriggerEnter(collisionPair.first, collisionPair.second);
} else { } else {
this._tempTriggerList[i].onTriggerExit(collisionPair.first, collisionPair.second); this._tempTriggerList[i].onTriggerExit(collisionPair.first, collisionPair.second);
+8 -8
View File
@@ -88,42 +88,42 @@ module es {
return vx * vx + vy * vy < cRadius * cRadius; return vx * vx + vy * vy < cRadius * cRadius;
} }
public static isRectToLine(rect: Rectangle, lineFrom: Vector2, lineTo: Vector2){ public static isRectToLine(rect: Rectangle, lineFrom: Vector2, lineTo: Vector2) {
let fromSector = this.getSector(rect.x, rect.y, rect.width, rect.height, lineFrom); let fromSector = this.getSector(rect.x, rect.y, rect.width, rect.height, lineFrom);
let toSector = this.getSector(rect.x, rect.y, rect.width, rect.height, lineTo); let toSector = this.getSector(rect.x, rect.y, rect.width, rect.height, lineTo);
if (fromSector == PointSectors.center || toSector == PointSectors.center){ if (fromSector == PointSectors.center || toSector == PointSectors.center) {
return true; return true;
} else if((fromSector & toSector) != 0){ } else if ((fromSector & toSector) != 0) {
return false; return false;
} else{ } else {
let both = fromSector | toSector; let both = fromSector | toSector;
// 线对边进行检查 // 线对边进行检查
let edgeFrom: Vector2; let edgeFrom: Vector2;
let edgeTo: Vector2; let edgeTo: Vector2;
if ((both & PointSectors.top) != 0){ if ((both & PointSectors.top) != 0) {
edgeFrom = new Vector2(rect.x, rect.y); edgeFrom = new Vector2(rect.x, rect.y);
edgeTo = new Vector2(rect.x + rect.width, rect.y); edgeTo = new Vector2(rect.x + rect.width, rect.y);
if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo))
return true; return true;
} }
if ((both & PointSectors.bottom) != 0){ if ((both & PointSectors.bottom) != 0) {
edgeFrom = new Vector2(rect.x, rect.y + rect.height); edgeFrom = new Vector2(rect.x, rect.y + rect.height);
edgeTo = new Vector2(rect.x + rect.width, rect.y + rect.height); edgeTo = new Vector2(rect.x + rect.width, rect.y + rect.height);
if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo))
return true; return true;
} }
if ((both & PointSectors.left) != 0){ if ((both & PointSectors.left) != 0) {
edgeFrom = new Vector2(rect.x, rect.y); edgeFrom = new Vector2(rect.x, rect.y);
edgeTo = new Vector2(rect.x, rect.y + rect.height); edgeTo = new Vector2(rect.x, rect.y + rect.height);
if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo))
return true; return true;
} }
if ((both & PointSectors.right) != 0){ if ((both & PointSectors.right) != 0) {
edgeFrom = new Vector2(rect.x + rect.width, rect.y); edgeFrom = new Vector2(rect.x + rect.width, rect.y);
edgeTo = new Vector2(rect.x + rect.width, rect.y + rect.height); edgeTo = new Vector2(rect.x + rect.width, rect.y + rect.height);
if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo)) if (this.isLineToLine(edgeFrom, edgeTo, lineFrom, lineTo))
+11 -11
View File
@@ -1,19 +1,19 @@
module es { module es {
export class Physics { export class Physics {
private static _spatialHash: SpatialHash;
/** 调用reset并创建一个新的SpatialHash时使用的单元格大小 */ /** 调用reset并创建一个新的SpatialHash时使用的单元格大小 */
public static spatialHashCellSize = 100; public static spatialHashCellSize = 100;
/** 接受layerMask的所有方法的默认值 */ /** 接受layerMask的所有方法的默认值 */
public static readonly allLayers: number = -1; public static readonly allLayers: number = -1;
private static _spatialHash: SpatialHash;
public static reset(){ public static reset() {
this._spatialHash = new SpatialHash(this.spatialHashCellSize); this._spatialHash = new SpatialHash(this.spatialHashCellSize);
} }
/** /**
* SpatialHash中移除所有碰撞器 * SpatialHash中移除所有碰撞器
*/ */
public static clear(){ public static clear() {
this._spatialHash.clear(); this._spatialHash.clear();
} }
@@ -24,8 +24,8 @@ module es {
* @param results * @param results
* @param layerMask * @param layerMask
*/ */
public static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask = -1){ public static overlapCircleAll(center: Vector2, randius: number, results: any[], layerMask = -1) {
if (results.length == 0){ if (results.length == 0) {
console.error("An empty results array was passed in. No results will ever be returned."); console.error("An empty results array was passed in. No results will ever be returned.");
return; return;
} }
@@ -38,7 +38,7 @@ module es {
* @param rect * @param rect
* @param layerMask * @param layerMask
*/ */
public static boxcastBroadphase(rect: Rectangle, layerMask: number = this.allLayers){ public static boxcastBroadphase(rect: Rectangle, layerMask: number = this.allLayers) {
return this._spatialHash.aabbBroadphase(rect, null, layerMask); return this._spatialHash.aabbBroadphase(rect, null, layerMask);
} }
@@ -48,7 +48,7 @@ module es {
* @param rect * @param rect
* @param layerMask * @param layerMask
*/ */
public static boxcastBroadphaseExcludingSelf(collider: Collider, rect: Rectangle, layerMask = this.allLayers){ public static boxcastBroadphaseExcludingSelf(collider: Collider, rect: Rectangle, layerMask = this.allLayers) {
return this._spatialHash.aabbBroadphase(rect, collider, layerMask); return this._spatialHash.aabbBroadphase(rect, collider, layerMask);
} }
@@ -56,7 +56,7 @@ module es {
* *
* @param collider * @param collider
*/ */
public static addCollider(collider: Collider){ public static addCollider(collider: Collider) {
Physics._spatialHash.register(collider); Physics._spatialHash.register(collider);
} }
@@ -64,7 +64,7 @@ module es {
* *
* @param collider * @param collider
*/ */
public static removeCollider(collider: Collider){ public static removeCollider(collider: Collider) {
Physics._spatialHash.remove(collider); Physics._spatialHash.remove(collider);
} }
@@ -72,7 +72,7 @@ module es {
* *
* @param collider * @param collider
*/ */
public static updateCollider(collider: Collider){ public static updateCollider(collider: Collider) {
this._spatialHash.remove(collider); this._spatialHash.remove(collider);
this._spatialHash.register(collider); this._spatialHash.register(collider);
} }
@@ -81,7 +81,7 @@ module es {
* debug绘制空间散列的内容 * debug绘制空间散列的内容
* @param secondsToDisplay * @param secondsToDisplay
*/ */
public static debugDraw(secondsToDisplay){ public static debugDraw(secondsToDisplay) {
this._spatialHash.debugDraw(secondsToDisplay, 2); this._spatialHash.debugDraw(secondsToDisplay, 2);
} }
} }
+9 -9
View File
@@ -7,7 +7,7 @@ module es {
public width: number; public width: number;
public height: number; public height: number;
constructor(width: number, height: number){ constructor(width: number, height: number) {
super(Box.buildBox(width, height), true); super(Box.buildBox(width, height), true);
this.width = width; this.width = width;
this.height = height; this.height = height;
@@ -18,7 +18,7 @@ module es {
* @param width * @param width
* @param height * @param height
*/ */
private static buildBox(width: number, height: number): Vector2[]{ private static buildBox(width: number, height: number): Vector2[] {
// 我们在(0,0)的中心周围创建点 // 我们在(0,0)的中心周围创建点
let halfWidth = width / 2; let halfWidth = width / 2;
let halfHeight = height / 2; let halfHeight = height / 2;
@@ -36,7 +36,7 @@ module es {
* @param width * @param width
* @param height * @param height
*/ */
public updateBox(width: number, height: number){ public updateBox(width: number, height: number) {
this.width = width; this.width = width;
this.height = height; this.height = height;
@@ -49,13 +49,13 @@ module es {
this.points[2] = new Vector2(halfWidth, halfHeight); this.points[2] = new Vector2(halfWidth, halfHeight);
this.points[3] = new Vector2(-halfWidth, halfHeight); this.points[3] = new Vector2(-halfWidth, halfHeight);
for (let i = 0; i < this.points.length; i ++) for (let i = 0; i < this.points.length; i++)
this._originalPoints[i] = this.points[i]; this._originalPoints[i] = this.points[i];
} }
public overlaps(other: Shape){ public overlaps(other: Shape) {
// 特殊情况,这一个高性能方式实现,其他情况则使用polygon方法检测 // 特殊情况,这一个高性能方式实现,其他情况则使用polygon方法检测
if (this.isUnrotated){ if (this.isUnrotated) {
if (other instanceof Box) if (other instanceof Box)
return this.bounds.intersects(other.bounds); return this.bounds.intersects(other.bounds);
@@ -66,9 +66,9 @@ module es {
return super.overlaps(other); return super.overlaps(other);
} }
public collidesWithShape(other: Shape, result: CollisionResult): boolean{ public collidesWithShape(other: Shape, result: CollisionResult): boolean {
// 特殊情况,这一个高性能方式实现,其他情况则使用polygon方法检测 // 特殊情况,这一个高性能方式实现,其他情况则使用polygon方法检测
if (other instanceof Box && (other as Box).isUnrotated){ if (other instanceof Box && (other as Box).isUnrotated) {
return ShapeCollisions.boxToBox(this, other, result); return ShapeCollisions.boxToBox(this, other, result);
} }
@@ -77,7 +77,7 @@ module es {
return super.collidesWithShape(other, result); return super.collidesWithShape(other, result);
} }
public containsPoint(point: Vector2){ public containsPoint(point: Vector2) {
if (this.isUnrotated) if (this.isUnrotated)
return this.bounds.contains(point.x, point.y); return this.bounds.contains(point.x, point.y);
+1 -1
View File
@@ -5,7 +5,7 @@ module es {
public normal: Vector2 = Vector2.zero; public normal: Vector2 = Vector2.zero;
public point: Vector2 = Vector2.zero; public point: Vector2 = Vector2.zero;
public invertResult(){ public invertResult() {
this.minimumTranslationVector = Vector2.negate(this.minimumTranslationVector); this.minimumTranslationVector = Vector2.negate(this.minimumTranslationVector);
this.normal = Vector2.negate(this.normal); this.normal = Vector2.negate(this.normal);
} }
+68 -69
View File
@@ -9,19 +9,7 @@ module es {
* *
*/ */
public points: Vector2[]; public points: Vector2[];
/**
* 线SAT碰撞检测squareRoots
* box只有两个边缘
*/
public get edgeNormals(){
if (this._areEdgeNormalsDirty)
this.buildEdgeNormals();
return this._edgeNormals;
}
public _areEdgeNormalsDirty = true; public _areEdgeNormalsDirty = true;
public _edgeNormals: Vector2[];
/** /**
* *
*/ */
@@ -39,61 +27,25 @@ module es {
* @param points * @param points
* @param isBox * @param isBox
*/ */
constructor(points: Vector2[], isBox?: boolean){ constructor(points: Vector2[], isBox?: boolean) {
super(); super();
this.setPoints(points); this.setPoints(points);
this.isBox = isBox; this.isBox = isBox;
} }
/** public _edgeNormals: Vector2[];
* 线
* @param points
*/
public setPoints(points: Vector2[]) {
this.points = points;
this.recalculateCenterAndEdgeNormals();
this._originalPoints = [];
for (let i = 0; i < this.points.length; i ++){
this._originalPoints.push(this.points[i]);
}
}
/** /**
* * 线SAT碰撞检测squareRoots
* * box只有两个边缘
*/ */
public recalculateCenterAndEdgeNormals() { public get edgeNormals() {
this._polygonCenter = Polygon.findPolygonCenter(this.points); if (this._areEdgeNormalsDirty)
this._areEdgeNormalsDirty = true; this.buildEdgeNormals();
return this._edgeNormals;
} }
/**
* 线
* edgeNormals getter惰性创建和更新
*/
public buildEdgeNormals(){
// 对于box 我们只需要两条边,因为另外两条边是平行的
let totalEdges = this.isBox ? 2 : this.points.length;
if (this._edgeNormals == null || this._edgeNormals.length != totalEdges)
this._edgeNormals = new Array(totalEdges);
let p2: Vector2;
for (let i = 0; i < totalEdges; i ++){
let p1 = this.points[i];
if (i + 1 >= this.points.length)
p2 = this.points[0];
else
p2 = this.points[i + 1];
let perp = Vector2Ext.perpendicular(p1, p2);
perp = Vector2.normalize(perp);
this._edgeNormals[i] = perp;
}
}
/** /**
* (n角形) * (n角形)
* @param vertCount * @param vertCount
@@ -114,9 +66,9 @@ module es {
* *
* @param points * @param points
*/ */
public static recenterPolygonVerts(points: Vector2[]){ public static recenterPolygonVerts(points: Vector2[]) {
let center = this.findPolygonCenter(points); let center = this.findPolygonCenter(points);
for (let i = 0; i < points.length; i ++) for (let i = 0; i < points.length; i++)
points[i] = Vector2.subtract(points[i], center); points[i] = Vector2.subtract(points[i], center);
} }
@@ -173,16 +125,63 @@ module es {
return closestPoint; return closestPoint;
} }
public recalculateBounds(collider: Collider){ /**
* 线
* @param points
*/
public setPoints(points: Vector2[]) {
this.points = points;
this.recalculateCenterAndEdgeNormals();
this._originalPoints = [];
for (let i = 0; i < this.points.length; i++) {
this._originalPoints.push(this.points[i]);
}
}
/**
*
*
*/
public recalculateCenterAndEdgeNormals() {
this._polygonCenter = Polygon.findPolygonCenter(this.points);
this._areEdgeNormalsDirty = true;
}
/**
* 线
* edgeNormals getter惰性创建和更新
*/
public buildEdgeNormals() {
// 对于box 我们只需要两条边,因为另外两条边是平行的
let totalEdges = this.isBox ? 2 : this.points.length;
if (this._edgeNormals == null || this._edgeNormals.length != totalEdges)
this._edgeNormals = new Array(totalEdges);
let p2: Vector2;
for (let i = 0; i < totalEdges; i++) {
let p1 = this.points[i];
if (i + 1 >= this.points.length)
p2 = this.points[0];
else
p2 = this.points[i + 1];
let perp = Vector2Ext.perpendicular(p1, p2);
perp = Vector2.normalize(perp);
this._edgeNormals[i] = perp;
}
}
public recalculateBounds(collider: Collider) {
// 如果我们没有旋转或不关心TRS我们使用localOffset作为中心,我们会从那开始 // 如果我们没有旋转或不关心TRS我们使用localOffset作为中心,我们会从那开始
this.center = collider.localOffset; this.center = collider.localOffset;
if (collider.shouldColliderScaleAndRotateWithTransform){ if (collider.shouldColliderScaleAndRotateWithTransform) {
let hasUnitScale = true; let hasUnitScale = true;
let tempMat: Matrix2D; let tempMat: Matrix2D;
let combinedMatrix = Matrix2D.create().translate(-this._polygonCenter.x, -this._polygonCenter.y); let combinedMatrix = Matrix2D.create().translate(-this._polygonCenter.x, -this._polygonCenter.y);
if (collider.entity.transform.scale != Vector2.zero){ if (collider.entity.transform.scale != Vector2.zero) {
tempMat = Matrix2D.create().scale(collider.entity.transform.scale.x, collider.entity.transform.scale.y); tempMat = Matrix2D.create().scale(collider.entity.transform.scale.x, collider.entity.transform.scale.y);
combinedMatrix = combinedMatrix.multiply(tempMat); combinedMatrix = combinedMatrix.multiply(tempMat);
hasUnitScale = false; hasUnitScale = false;
@@ -191,7 +190,7 @@ module es {
this.center = Vector2.multiply(collider.localOffset, collider.entity.transform.scale); this.center = Vector2.multiply(collider.localOffset, collider.entity.transform.scale);
} }
if (collider.entity.transform.rotation != 0){ if (collider.entity.transform.rotation != 0) {
tempMat = Matrix2D.create().rotate(collider.entity.transform.rotation); tempMat = Matrix2D.create().rotate(collider.entity.transform.rotation);
combinedMatrix = combinedMatrix.multiply(tempMat); combinedMatrix = combinedMatrix.multiply(tempMat);
@@ -222,13 +221,13 @@ module es {
this.bounds.location = this.bounds.location.add(this.position); this.bounds.location = this.bounds.location.add(this.position);
} }
public overlaps(other: Shape){ public overlaps(other: Shape) {
let result: CollisionResult = new CollisionResult(); let result: CollisionResult = new CollisionResult();
if (other instanceof Polygon) if (other instanceof Polygon)
return ShapeCollisions.polygonToPolygon(this, other, result); return ShapeCollisions.polygonToPolygon(this, other, result);
if (other instanceof Circle){ if (other instanceof Circle) {
if (ShapeCollisions.circleToPolygon(other, this, result)){ if (ShapeCollisions.circleToPolygon(other, this, result)) {
result.invertResult(); result.invertResult();
return true; return true;
} }
@@ -239,13 +238,13 @@ module es {
throw new Error(`overlaps of Pologon to ${other} are not supported`); throw new Error(`overlaps of Pologon to ${other} are not supported`);
} }
public collidesWithShape(other: Shape, result: CollisionResult): boolean{ public collidesWithShape(other: Shape, result: CollisionResult): boolean {
if (other instanceof Polygon){ if (other instanceof Polygon) {
return ShapeCollisions.polygonToPolygon(this, other, result); return ShapeCollisions.polygonToPolygon(this, other, result);
} }
if (other instanceof Circle){ if (other instanceof Circle) {
if (ShapeCollisions.circleToPolygon(other, this, result)){ if (ShapeCollisions.circleToPolygon(other, this, result)) {
result.invertResult(); result.invertResult();
return true; return true;
} }
+4 -1
View File
@@ -16,11 +16,14 @@ module es {
public bounds: Rectangle; public bounds: Rectangle;
public abstract recalculateBounds(collider: Collider); public abstract recalculateBounds(collider: Collider);
public abstract overlaps(other: Shape): boolean; public abstract overlaps(other: Shape): boolean;
public abstract collidesWithShape(other: Shape, collisionResult: CollisionResult): boolean; public abstract collidesWithShape(other: Shape, collisionResult: CollisionResult): boolean;
public abstract pointCollidesWithShape(point: Vector2, result: CollisionResult): boolean; public abstract pointCollidesWithShape(point: Vector2, result: CollisionResult): boolean;
public clone(): Shape{ public clone(): Shape {
return ObjectUtils.clone<Shape>(this); return ObjectUtils.clone<Shape>(this);
} }
} }
@@ -108,7 +108,7 @@ module es {
} }
} }
return { min: min, max: max }; return {min: min, max: max};
} }
/** /**
@@ -245,11 +245,11 @@ module es {
* @param first * @param first
* @param second * @param second
*/ */
public static circleToCircle(first: Circle, second: Circle, result: CollisionResult): boolean{ public static circleToCircle(first: Circle, second: Circle, result: CollisionResult): boolean {
let distanceSquared = Vector2.distanceSquared(first.position, second.position); let distanceSquared = Vector2.distanceSquared(first.position, second.position);
let sumOfRadii = first.radius + second.radius; let sumOfRadii = first.radius + second.radius;
let collided = distanceSquared < sumOfRadii * sumOfRadii; let collided = distanceSquared < sumOfRadii * sumOfRadii;
if (collided){ if (collided) {
result.normal = Vector2.normalize(Vector2.subtract(first.position, second.position)); result.normal = Vector2.normalize(Vector2.subtract(first.position, second.position));
let depth = sumOfRadii - Math.sqrt(distanceSquared); let depth = sumOfRadii - Math.sqrt(distanceSquared);
result.minimumTranslationVector = Vector2.multiply(new Vector2(-depth), result.normal); result.minimumTranslationVector = Vector2.multiply(new Vector2(-depth), result.normal);
@@ -267,9 +267,9 @@ module es {
* @param second * @param second
* @param result * @param result
*/ */
public static boxToBox(first: Box, second: Box, result: CollisionResult): boolean{ public static boxToBox(first: Box, second: Box, result: CollisionResult): boolean {
let minkowskiDiff = this.minkowskiDifference(first, second); let minkowskiDiff = this.minkowskiDifference(first, second);
if (minkowskiDiff.contains(0, 0)){ if (minkowskiDiff.contains(0, 0)) {
// 计算MTV。如果它是零,我们就可以称它为非碰撞 // 计算MTV。如果它是零,我们就可以称它为非碰撞
result.minimumTranslationVector = minkowskiDiff.getClosestPointOnBoundsToOrigin(); result.minimumTranslationVector = minkowskiDiff.getClosestPointOnBoundsToOrigin();
@@ -285,7 +285,7 @@ module es {
return false; return false;
} }
private static minkowskiDifference(first: Box, second: Box){ private static minkowskiDifference(first: Box, second: Box) {
// 我们需要第一个框的左上角 // 我们需要第一个框的左上角
// 碰撞器只会修改运动的位置所以我们需要用位置来计算出运动是什么。 // 碰撞器只会修改运动的位置所以我们需要用位置来计算出运动是什么。
let positionOffset = Vector2.subtract(first.position, Vector2.add(first.bounds.location, Vector2.divide(first.bounds.size, new Vector2(2)))); let positionOffset = Vector2.subtract(first.position, Vector2.add(first.bounds.location, Vector2.divide(first.bounds.size, new Vector2(2))));
+52 -52
View File
@@ -30,33 +30,6 @@ module es {
this._raycastParser = new RaycastResultParser(); this._raycastParser = new RaycastResultParser();
} }
/**
* x,y值作为世界空间的x,y值
* @param x
* @param y
*/
private cellCoords(x: number, y: number): Vector2 {
return new Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize));
}
/**
* x,y值的单元格
* createCellIfEmpty为true
* @param x
* @param y
* @param createCellIfEmpty
*/
private cellAtPosition(x: number, y: number, createCellIfEmpty: boolean = false) {
let cell: Collider[] = this._cellDict.tryGetValue(x, y);
if (!cell) {
if (createCellIfEmpty) {
cell = [];
this._cellDict.add(x, y, cell);
}
}
return cell;
}
/** /**
* SpatialHash * SpatialHash
* @param collider * @param collider
@@ -111,11 +84,11 @@ module es {
* 使SpatialHash中删除对象 * 使SpatialHash中删除对象
* @param obj * @param obj
*/ */
public removeWithBruteForce(obj: Collider){ public removeWithBruteForce(obj: Collider) {
this._cellDict.remove(obj); this._cellDict.remove(obj);
} }
public clear(){ public clear() {
this._cellDict.clear(); this._cellDict.clear();
} }
@@ -124,9 +97,9 @@ module es {
* @param secondsToDisplay * @param secondsToDisplay
* @param textScale * @param textScale
*/ */
public debugDraw(secondsToDisplay: number, textScale: number = 1){ public debugDraw(secondsToDisplay: number, textScale: number = 1) {
for (let x = this.gridBounds.x; x <= this.gridBounds.right; x ++){ for (let x = this.gridBounds.x; x <= this.gridBounds.right; x++) {
for (let y = this.gridBounds.y; y <= this.gridBounds.bottom; y ++){ for (let y = this.gridBounds.y; y <= this.gridBounds.bottom; y++) {
let cell = this.cellAtPosition(x, y); let cell = this.cellAtPosition(x, y);
if (cell && cell.length > 0) if (cell && cell.length > 0)
this.debugDrawCellDetails(x, y, cell.length, secondsToDisplay, textScale); this.debugDrawCellDetails(x, y, cell.length, secondsToDisplay, textScale);
@@ -134,17 +107,13 @@ module es {
} }
} }
private debugDrawCellDetails(x: number, y: number, cellCount: number, secondsToDisplay = 0.5, textScale = 1){
}
/** /**
* *
* @param bounds * @param bounds
* @param excludeCollider * @param excludeCollider
* @param layerMask * @param layerMask
*/ */
public aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number) : Collider[]{ public aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number): Collider[] {
this._tempHashSet.length = 0; this._tempHashSet.length = 0;
let p1 = this.cellCoords(bounds.x, bounds.y); let p1 = this.cellCoords(bounds.x, bounds.y);
@@ -164,7 +133,7 @@ module es {
if (collider == excludeCollider || !Flags.isFlagSet(layerMask, collider.physicsLayer)) if (collider == excludeCollider || !Flags.isFlagSet(layerMask, collider.physicsLayer))
continue; continue;
if (bounds.intersects(collider.bounds)){ if (bounds.intersects(collider.bounds)) {
if (this._tempHashSet.indexOf(collider) == -1) if (this._tempHashSet.indexOf(collider) == -1)
this._tempHashSet.push(collider); this._tempHashSet.push(collider);
} }
@@ -196,14 +165,14 @@ module es {
results[resultCounter] = collider; results[resultCounter] = collider;
resultCounter++; resultCounter++;
} else if (collider instanceof CircleCollider) { } else if (collider instanceof CircleCollider) {
if (collider.shape.overlaps(this._overlapTestCircle)){ if (collider.shape.overlaps(this._overlapTestCircle)) {
results[resultCounter] = collider; results[resultCounter] = collider;
resultCounter ++; resultCounter++;
} }
} else if(collider instanceof PolygonCollider) { } else if (collider instanceof PolygonCollider) {
if (collider.shape.overlaps(this._overlapTestCircle)){ if (collider.shape.overlaps(this._overlapTestCircle)) {
results[resultCounter] = collider; results[resultCounter] = collider;
resultCounter ++; resultCounter++;
} }
} else { } else {
throw new Error("overlapCircle against this collider type is not implemented!"); throw new Error("overlapCircle against this collider type is not implemented!");
@@ -216,6 +185,37 @@ module es {
return resultCounter; return resultCounter;
} }
/**
* x,y值作为世界空间的x,y值
* @param x
* @param y
*/
private cellCoords(x: number, y: number): Vector2 {
return new Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize));
}
/**
* x,y值的单元格
* createCellIfEmpty为true
* @param x
* @param y
* @param createCellIfEmpty
*/
private cellAtPosition(x: number, y: number, createCellIfEmpty: boolean = false) {
let cell: Collider[] = this._cellDict.tryGetValue(x, y);
if (!cell) {
if (createCellIfEmpty) {
cell = [];
this._cellDict.add(x, y, cell);
}
}
return cell;
}
private debugDrawCellDetails(x: number, y: number, cellCount: number, secondsToDisplay = 0.5, textScale = 1) {
}
} }
/** /**
@@ -225,15 +225,6 @@ module es {
export class NumberDictionary { export class NumberDictionary {
public _store: Map<string, Collider[]> = new Map<string, Collider[]>(); public _store: Map<string, Collider[]> = new Map<string, Collider[]>();
/**
* x和y值计算并返回散列键
* @param x
* @param y
*/
private getKey(x: number, y: number): string {
return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, true)).toString();
}
public add(x: number, y: number, list: Collider[]) { public add(x: number, y: number, list: Collider[]) {
this._store.set(this.getKey(x, y), list); this._store.set(this.getKey(x, y), list);
} }
@@ -259,6 +250,15 @@ module es {
public clear() { public clear() {
this._store.clear(); this._store.clear();
} }
/**
* x和y值计算并返回散列键
* @param x
* @param y
*/
private getKey(x: number, y: number): string {
return Long.fromNumber(x).shiftLeft(32).or(Long.fromNumber(y, true)).toString();
}
} }
export class RaycastResultParser { export class RaycastResultParser {
+10 -10
View File
@@ -6,30 +6,30 @@ module es {
public clientArea: Rectangle; public clientArea: Rectangle;
public safeArea: Rectangle; public safeArea: Rectangle;
constructor(){ constructor() {
this.clientArea = new Rectangle(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height); this.clientArea = new Rectangle(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height);
this.safeArea = this.clientArea; this.safeArea = this.clientArea;
} }
public place(size: Vector2, horizontalMargin: number, verticalMargine: number, alignment: Alignment){ public place(size: Vector2, horizontalMargin: number, verticalMargine: number, alignment: Alignment) {
let rc = new Rectangle(0, 0, size.x, size.y); let rc = new Rectangle(0, 0, size.x, size.y);
if ((alignment & Alignment.left) != 0){ if ((alignment & Alignment.left) != 0) {
rc.x = this.clientArea.x + (this.clientArea.width * horizontalMargin); rc.x = this.clientArea.x + (this.clientArea.width * horizontalMargin);
}else if((alignment & Alignment.right) != 0){ } else if ((alignment & Alignment.right) != 0) {
rc.x = this.clientArea.x + (this.clientArea.width * (1 - horizontalMargin)) - rc.width; rc.x = this.clientArea.x + (this.clientArea.width * (1 - horizontalMargin)) - rc.width;
} else if((alignment & Alignment.horizontalCenter) != 0){ } else if ((alignment & Alignment.horizontalCenter) != 0) {
rc.x = this.clientArea.x + (this.clientArea.width - rc.width) / 2 + (horizontalMargin * this.clientArea.width); rc.x = this.clientArea.x + (this.clientArea.width - rc.width) / 2 + (horizontalMargin * this.clientArea.width);
}else{ } else {
} }
if ((alignment & Alignment.top) != 0){ if ((alignment & Alignment.top) != 0) {
rc.y = this.clientArea.y + (this.clientArea.height * verticalMargine); rc.y = this.clientArea.y + (this.clientArea.height * verticalMargine);
}else if((alignment & Alignment.bottom) != 0){ } else if ((alignment & Alignment.bottom) != 0) {
rc.y = this.clientArea.y + (this.clientArea.height * (1 - verticalMargine)) - rc.height; rc.y = this.clientArea.y + (this.clientArea.height * (1 - verticalMargine)) - rc.height;
} else if((alignment & Alignment.verticalCenter) != 0){ } else if ((alignment & Alignment.verticalCenter) != 0) {
rc.y = this.clientArea.y + (this.clientArea.height - rc.height) / 2 + (verticalMargine * this.clientArea.height); rc.y = this.clientArea.y + (this.clientArea.height - rc.height) / 2 + (verticalMargine * this.clientArea.height);
}else{ } else {
} }
+76 -75
View File
@@ -1,21 +1,21 @@
namespace stopwatch { namespace stopwatch {
/** /**
* *
*/ */
export class Stopwatch { export class Stopwatch {
/** /**
* *
* undefined * undefined
*/ */
private _startSystemTime: number | undefined; private _startSystemTime: number | undefined;
/** /**
* *
* undefined * undefined
*/ */
private _stopSystemTime: number | undefined; private _stopSystemTime: number | undefined;
/** 自上次复位以来,秒表已停止的系统时间总数。 */ /** 自上次复位以来,秒表已停止的系统时间总数。 */
private _stopDuration: number = 0; private _stopDuration: number = 0;
/** /**
* *
* undefined * undefined
*/ */
@@ -25,7 +25,8 @@ namespace stopwatch {
*/ */
private _completeSlices: Slice[] = []; private _completeSlices: Slice[] = [];
constructor(private readonly getSystemTime = _defaultSystemTimeGetter) { } constructor(private readonly getSystemTime = _defaultSystemTimeGetter) {
}
public getState() { public getState() {
if (this._startSystemTime === undefined) { if (this._startSystemTime === undefined) {
@@ -37,22 +38,22 @@ namespace stopwatch {
} }
} }
public isIdle(){ public isIdle() {
return this.getState() === State.IDLE; return this.getState() === State.IDLE;
} }
public isRunning(){ public isRunning() {
return this.getState() === State.RUNNING; return this.getState() === State.RUNNING;
} }
public isStopped(){ public isStopped() {
return this.getState() === State.STOPPED; return this.getState() === State.STOPPED;
} }
/** /**
* *
*/ */
public slice(){ public slice() {
return this.recordPendingSlice(); return this.recordPendingSlice();
} }
@@ -80,20 +81,70 @@ namespace stopwatch {
/** /**
* *
*/ */
public getTime(){ public getTime() {
return this.caculateStopwatchTime(); return this.caculateStopwatchTime();
} }
/**
*
*/
public reset() {
this._startSystemTime = this._pendingSliceStartStopwatchTime = this._stopSystemTime = undefined;
this._stopDuration = 0;
this._completeSlices = [];
}
/**
* ()
* @param forceReset
*/
public start(forceReset: boolean = false) {
if (forceReset) {
this.reset();
}
if (this._stopSystemTime !== undefined) {
const systemNow = this.getSystemTime();
const stopDuration = systemNow - this._stopSystemTime;
this._stopDuration += stopDuration;
this._stopSystemTime = undefined;
} else if (this._startSystemTime === undefined) {
const systemNow = this.getSystemTime();
this._startSystemTime = systemNow;
this._pendingSliceStartStopwatchTime = 0;
}
}
/**
*
* @param recordPendingSlice
*/
public stop(recordPendingSlice: boolean = false) {
if (this._startSystemTime === undefined) {
return 0;
}
const systemTimeOfStopwatchTime = this.getSystemTimeOfCurrentStopwatchTime();
if (recordPendingSlice) {
this.recordPendingSlice(this.caculateStopwatchTime(systemTimeOfStopwatchTime));
}
this._stopSystemTime = systemTimeOfStopwatchTime;
return this.getTime();
}
/** /**
* *
* @param endStopwatchTime * @param endStopwatchTime
*/ */
private calculatePendingSlice(endStopwatchTime?: number): Slice { private calculatePendingSlice(endStopwatchTime?: number): Slice {
if (this._pendingSliceStartStopwatchTime === undefined){ if (this._pendingSliceStartStopwatchTime === undefined) {
return Object.freeze({startTime: 0, endTime: 0, duration: 0}); return Object.freeze({startTime: 0, endTime: 0, duration: 0});
} }
if (endStopwatchTime === undefined){ if (endStopwatchTime === undefined) {
endStopwatchTime = this.getTime(); endStopwatchTime = this.getTime();
} }
@@ -106,9 +157,9 @@ namespace stopwatch {
/** /**
* *
* @param endSystemTime * @param endSystemTime
*/ */
private caculateStopwatchTime(endSystemTime?: number){ private caculateStopwatchTime(endSystemTime?: number) {
if (this._startSystemTime === undefined) if (this._startSystemTime === undefined)
return 0; return 0;
@@ -122,67 +173,17 @@ namespace stopwatch {
* *
* *
*/ */
private getSystemTimeOfCurrentStopwatchTime(){ private getSystemTimeOfCurrentStopwatchTime() {
return this._stopSystemTime === undefined ? this.getSystemTime() : this._stopSystemTime; return this._stopSystemTime === undefined ? this.getSystemTime() : this._stopSystemTime;
} }
/**
*
*/
public reset(){
this._startSystemTime = this._pendingSliceStartStopwatchTime = this._stopSystemTime = undefined;
this._stopDuration = 0;
this._completeSlices = [];
}
/**
* ()
* @param forceReset
*/
public start(forceReset: boolean = false){
if (forceReset){
this.reset();
}
if (this._stopSystemTime !== undefined){
const systemNow = this.getSystemTime();
const stopDuration = systemNow - this._stopSystemTime;
this._stopDuration += stopDuration;
this._stopSystemTime = undefined;
} else if (this._startSystemTime === undefined){
const systemNow = this.getSystemTime();
this._startSystemTime = systemNow;
this._pendingSliceStartStopwatchTime = 0;
}
}
/**
*
* @param recordPendingSlice
*/
public stop(recordPendingSlice: boolean = false){
if (this._startSystemTime === undefined){
return 0;
}
const systemTimeOfStopwatchTime = this.getSystemTimeOfCurrentStopwatchTime();
if (recordPendingSlice){
this.recordPendingSlice(this.caculateStopwatchTime(systemTimeOfStopwatchTime));
}
this._stopSystemTime = systemTimeOfStopwatchTime;
return this.getTime();
}
/** /**
* / * /
* @param endStopwatchTime * @param endStopwatchTime
*/ */
private recordPendingSlice(endStopwatchTime?: number){ private recordPendingSlice(endStopwatchTime?: number) {
if (this._pendingSliceStartStopwatchTime !== undefined){ if (this._pendingSliceStartStopwatchTime !== undefined) {
if (endStopwatchTime === undefined){ if (endStopwatchTime === undefined) {
endStopwatchTime = this.getTime(); endStopwatchTime = this.getTime();
} }
@@ -196,7 +197,7 @@ namespace stopwatch {
} }
} }
} }
/** /**
* *
* *
+25 -25
View File
@@ -18,23 +18,19 @@ module es {
public static readonly barPadding = 2; public static readonly barPadding = 2;
public static readonly autoAdjustDelay = 30; public static readonly autoAdjustDelay = 30;
private static _instance; private static _instance;
public static get Instance(): TimeRuler{
if (!this._instance)
this._instance = new TimeRuler();
return this._instance;
}
private _frameKey = 'frame';
private _logKey = 'log';
/** 每帧的日志 */
private _logs: FrameLog[];
/** 当前显示帧计数 */
private sampleFrames: number;
/** 获取/设置目标样本帧。 */ /** 获取/设置目标样本帧。 */
public targetSampleFrames: number; public targetSampleFrames: number;
/** 获取/设置计时器标尺宽度。 */ /** 获取/设置计时器标尺宽度。 */
public width: number; public width: number;
public enabled: true; public enabled: true;
/** */
public showLog = false;
private _frameKey = 'frame';
private _logKey = 'log';
/** 每帧的日志 */
private _logs: FrameLog[];
/** 当前显示帧计数 */
private sampleFrames: number;
/** TimerRuler画的位置。 */ /** TimerRuler画的位置。 */
private _position: Vector2; private _position: Vector2;
/** 上一帧日志 */ /** 上一帧日志 */
@@ -56,8 +52,6 @@ module es {
* StartFrame调用的次数Draw被调用 * StartFrame调用的次数Draw被调用
*/ */
private _updateCount: number; private _updateCount: number;
/** */
public showLog = false;
private _frameAdjust: number; private _frameAdjust: number;
constructor() { constructor() {
@@ -72,9 +66,10 @@ module es {
this.onGraphicsDeviceReset(); this.onGraphicsDeviceReset();
} }
private onGraphicsDeviceReset() { public static get Instance(): TimeRuler {
let layout = new Layout(); if (!this._instance)
this._position = layout.place(new Vector2(this.width, TimeRuler.barHeight), 0, 0.01, Alignment.bottomCenter).location; this._instance = new TimeRuler();
return this._instance;
} }
/** /**
@@ -244,7 +239,7 @@ module es {
count += 1; count += 1;
egret.localStorage.setItem(this._logKey, count.toString()); egret.localStorage.setItem(this._logKey, count.toString());
this.markers.forEach(markerInfo => { this.markers.forEach(markerInfo => {
for (let i = 0; i < markerInfo.logs.length; ++i){ for (let i = 0; i < markerInfo.logs.length; ++i) {
markerInfo.logs[i].initialized = false; markerInfo.logs[i].initialized = false;
markerInfo.logs[i].snapMin = 0; markerInfo.logs[i].snapMin = 0;
markerInfo.logs[i].snapMax = 0; markerInfo.logs[i].snapMax = 0;
@@ -260,7 +255,7 @@ module es {
}); });
} }
public render(position: Vector2 = this._position, width: number = this.width){ public render(position: Vector2 = this._position, width: number = this.width) {
egret.localStorage.setItem(this._frameKey, "0"); egret.localStorage.setItem(this._frameKey, "0");
if (!this.showLog) if (!this.showLog)
@@ -269,22 +264,22 @@ module es {
let height = 0; let height = 0;
let maxTime = 0; let maxTime = 0;
this._prevLog.bars.forEach(bar => { this._prevLog.bars.forEach(bar => {
if (bar.markCount > 0){ if (bar.markCount > 0) {
height += TimeRuler.barHeight + TimeRuler.barPadding * 2; height += TimeRuler.barHeight + TimeRuler.barPadding * 2;
maxTime = Math.max(maxTime, bar.markers[bar.markCount - 1].endTime); maxTime = Math.max(maxTime, bar.markers[bar.markCount - 1].endTime);
} }
}) });
const frameSpan = 1 / 60 * 1000; const frameSpan = 1 / 60 * 1000;
let sampleSpan = this.sampleFrames * frameSpan; let sampleSpan = this.sampleFrames * frameSpan;
if (maxTime > sampleSpan){ if (maxTime > sampleSpan) {
this._frameAdjust = Math.max(0, this._frameAdjust) + 1; this._frameAdjust = Math.max(0, this._frameAdjust) + 1;
}else{ } else {
this._frameAdjust = Math.min(0, this._frameAdjust) - 1; this._frameAdjust = Math.min(0, this._frameAdjust) - 1;
} }
if (Math.max(this._frameAdjust) > TimeRuler.autoAdjustDelay){ if (Math.max(this._frameAdjust) > TimeRuler.autoAdjustDelay) {
this.sampleFrames = Math.min(TimeRuler.maxSampleFrames, this.sampleFrames); this.sampleFrames = Math.min(TimeRuler.maxSampleFrames, this.sampleFrames);
this.sampleFrames = Math.max(this.targetSampleFrames, (maxTime / frameSpan) + 1); this.sampleFrames = Math.max(this.targetSampleFrames, (maxTime / frameSpan) + 1);
@@ -297,6 +292,11 @@ module es {
// TODO: draw // TODO: draw
} }
private onGraphicsDeviceReset() {
let layout = new Layout();
this._position = layout.place(new Vector2(this.width, TimeRuler.barHeight), 0, 0.01, Alignment.bottomCenter).location;
}
} }
/** /**
@@ -320,7 +320,7 @@ module es {
public markerNests: number[] = new Array<number>(TimeRuler.maxNestCall); public markerNests: number[] = new Array<number>(TimeRuler.maxNestCall);
public nestCount: number = 0; public nestCount: number = 0;
constructor(){ constructor() {
this.markers.fill(new Marker(), 0, TimeRuler.maxSamples); this.markers.fill(new Marker(), 0, TimeRuler.maxSamples);
this.markerNests.fill(0, 0, TimeRuler.maxNestCall); this.markerNests.fill(0, 0, TimeRuler.maxNestCall);
} }
+28 -29
View File
@@ -1,7 +1,7 @@
class ArrayUtils { class ArrayUtils {
/** /**
* *
* @param ary * @param ary
* -- http://www.hiahia.org/datastructure/paixu/paixu8.3.1.1-1.htm * -- http://www.hiahia.org/datastructure/paixu/paixu8.3.1.1-1.htm
*/ */
public static bubbleSort(ary: number[]): void { public static bubbleSort(ary: number[]): void {
@@ -24,7 +24,7 @@ class ArrayUtils {
/** /**
* *
* @param ary * @param ary
*/ */
public static insertionSort(ary: number[]): void { public static insertionSort(ary: number[]): void {
let len: number = ary.length; let len: number = ary.length;
@@ -39,8 +39,8 @@ class ArrayUtils {
/** /**
* *
* @param ary * @param ary
* @param value * @param value
* @return * @return
*/ */
public static binarySearch(ary: number[], value: number): number { public static binarySearch(ary: number[], value: number): number {
@@ -59,8 +59,8 @@ class ArrayUtils {
/** /**
* *
* @param ary * @param ary
* @param num * @param num
* @return * @return
*/ */
public static findElementIndex(ary: any[], num: any): any { public static findElementIndex(ary: any[], num: any): any {
@@ -74,7 +74,7 @@ class ArrayUtils {
/** /**
* *
* @param ary * @param ary
* @return * @return
*/ */
public static getMaxElementIndex(ary: number[]): number { public static getMaxElementIndex(ary: number[]): number {
@@ -88,10 +88,10 @@ class ArrayUtils {
} }
/** /**
* *
* @param ary * @param ary
* @return * @return
*/ */
public static getMinElementIndex(ary: number[]): number { public static getMinElementIndex(ary: number[]): number {
let matchIndex: number = 0; let matchIndex: number = 0;
let len: number = ary.length; let len: number = ary.length;
@@ -104,8 +104,8 @@ class ArrayUtils {
/** /**
* "唯一性" * "唯一性"
* @param ary * @param ary
* @return * @return
* : [1, 2, 2, 3, 4] * : [1, 2, 2, 3, 4]
* : [1, 2, 3, 4] * : [1, 2, 3, 4]
*/ */
@@ -131,25 +131,24 @@ class ArrayUtils {
* A = [1, 2, 3, 4, 6] * A = [1, 2, 3, 4, 6]
* B = [0, 2, 1, 3, 4] * B = [0, 2, 1, 3, 4]
* [6, 0] * [6, 0]
* @param aryA * @param aryA
* @param aryB * @param aryB
* @return * @return
*/ */
public static getDifferAry(aryA: number[], aryB: number[]): number[] { public static getDifferAry(aryA: number[], aryB: number[]): number[] {
aryA = this.getUniqueAry(aryA); aryA = this.getUniqueAry(aryA);
aryB = this.getUniqueAry(aryB); aryB = this.getUniqueAry(aryB);
let ary: number[] = aryA.concat(aryB); let ary: number[] = aryA.concat(aryB);
let uObj: Object = new Object(); let uObj: Object = {};
let newAry: number[] = []; let newAry: number[] = [];
let count: number = ary.length; let count: number = ary.length;
for (let j: number = 0; j < count; ++j) { for (let j: number = 0; j < count; ++j) {
if (!uObj[ary[j]]) { if (!uObj[ary[j]]) {
uObj[ary[j]] = new Object(); uObj[ary[j]] = {};
uObj[ary[j]].count = 0; uObj[ary[j]].count = 0;
uObj[ary[j]].key = ary[j]; uObj[ary[j]].key = ary[j];
uObj[ary[j]].count++; uObj[ary[j]].count++;
} } else {
else {
if (uObj[ary[j]] instanceof Object) { if (uObj[ary[j]] instanceof Object) {
uObj[ary[j]].count++; uObj[ary[j]].count++;
} }
@@ -165,9 +164,9 @@ class ArrayUtils {
/** /**
* *
* @param array * @param array
* @param index1 * @param index1
* @param index2 * @param index2
*/ */
public static swap(array: any[], index1: number, index2: number): void { public static swap(array: any[], index1: number, index2: number): void {
let temp: any = array[index1]; let temp: any = array[index1];
@@ -178,7 +177,7 @@ class ArrayUtils {
/** /**
* *
* @param ary * @param ary
*/ */
public static clearList(ary: any[]): void { public static clearList(ary: any[]): void {
if (!ary) return; if (!ary) return;
@@ -190,7 +189,7 @@ class ArrayUtils {
/** /**
* *
* @param ary * @param ary
* @return * @return
*/ */
public static cloneList(ary: any[]): any[] { public static cloneList(ary: any[]): any[] {
@@ -201,9 +200,9 @@ class ArrayUtils {
/** /**
* 2 * 2
* @param ary1 1 * @param ary1 1
* @param ary2 2 * @param ary2 2
* @return * @return
*/ */
public static equals(ary1: number[], ary2: number[]): Boolean { public static equals(ary1: number[], ary2: number[]): Boolean {
if (ary1 == ary2) return true; if (ary1 == ary2) return true;
@@ -219,8 +218,8 @@ class ArrayUtils {
/** /**
* *
* @param index * @param index
* @param value * @param value
* @return * @return
*/ */
public static insert(ary: any[], index: number, value: any): any { public static insert(ary: any[], index: number, value: any): any {
+24 -24
View File
@@ -4,7 +4,7 @@ class Base64Utils {
private static _keyAll = Base64Utils._keyNum + Base64Utils._keyStr; private static _keyAll = Base64Utils._keyNum + Base64Utils._keyStr;
/** /**
* *
* @param input * @param input
*/ */
public static encode = function (input) { public static encode = function (input) {
let output = ""; let output = "";
@@ -29,32 +29,12 @@ class Base64Utils {
this._keyAll.charAt(enc3) + this._keyAll.charAt(enc4); this._keyAll.charAt(enc3) + this._keyAll.charAt(enc4);
} }
return this._keyStr.charAt(Math.floor((Math.random() * this._keyStr.length))) + output; return this._keyStr.charAt(Math.floor((Math.random() * this._keyStr.length))) + output;
} };
private static _utf8_encode(string) {
string = string.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
/** /**
* *
* @param input * @param input
* @param isNotStr * @param isNotStr
*/ */
public static decode(input, isNotStr: boolean = true) { public static decode(input, isNotStr: boolean = true) {
let output = ""; let output = "";
@@ -92,6 +72,26 @@ class Base64Utils {
return output; return output;
} }
private static _utf8_encode(string) {
string = string.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
private static _utf8_decode(utftext) { private static _utf8_decode(utftext) {
let string = ""; let string = "";
let i = 0; let i = 0;
+7 -7
View File
@@ -1,11 +1,11 @@
module es { module es {
/** 各种辅助方法来辅助绘图 */ /** 各种辅助方法来辅助绘图 */
export class DrawUtils { export class DrawUtils {
public static drawLine(shape: egret.Shape, start: Vector2, end: Vector2, color: number, thickness: number = 1){ public static drawLine(shape: egret.Shape, start: Vector2, end: Vector2, color: number, thickness: number = 1) {
this.drawLineAngle(shape, start, MathHelper.angleBetweenVectors(start, end), Vector2.distance(start, end), color, thickness); this.drawLineAngle(shape, start, MathHelper.angleBetweenVectors(start, end), Vector2.distance(start, end), color, thickness);
} }
public static drawLineAngle(shape: egret.Shape, start: Vector2, radians: number, length: number, color: number, thickness = 1){ public static drawLineAngle(shape: egret.Shape, start: Vector2, radians: number, length: number, color: number, thickness = 1) {
shape.graphics.beginFill(color); shape.graphics.beginFill(color);
shape.graphics.drawRect(start.x, start.y, 1, 1); shape.graphics.drawRect(start.x, start.y, 1, 1);
shape.graphics.endFill(); shape.graphics.endFill();
@@ -17,11 +17,11 @@ module es {
shape.rotation = radians; shape.rotation = radians;
} }
public static drawHollowRect(shape: egret.Shape, rect: Rectangle, color: number, thickness = 1){ public static drawHollowRect(shape: egret.Shape, rect: Rectangle, color: number, thickness = 1) {
this.drawHollowRectR(shape, rect.x, rect.y, rect.width, rect.height, color, thickness); this.drawHollowRectR(shape, rect.x, rect.y, rect.width, rect.height, color, thickness);
} }
public static drawHollowRectR(shape: egret.Shape, x: number, y: number, width: number, height: number, color: number, thickness = 1){ public static drawHollowRectR(shape: egret.Shape, x: number, y: number, width: number, height: number, color: number, thickness = 1) {
let tl = new Vector2(x, y).round(); let tl = new Vector2(x, y).round();
let tr = new Vector2(x + width, y).round(); let tr = new Vector2(x + width, y).round();
let br = new Vector2(x + width, y + height).round(); let br = new Vector2(x + width, y + height).round();
@@ -33,9 +33,9 @@ module es {
this.drawLine(shape, bl, tl, color, thickness); this.drawLine(shape, bl, tl, color, thickness);
} }
public static drawPixel(shape: egret.Shape, position: Vector2, color: number, size: number = 1){ public static drawPixel(shape: egret.Shape, position: Vector2, color: number, size: number = 1) {
let destRect = new Rectangle(position.x, position.y, size, size); let destRect = new Rectangle(position.x, position.y, size, size);
if (size != 1){ if (size != 1) {
destRect.x -= size * 0.5; destRect.x -= size * 0.5;
destRect.y -= size * 0.5; destRect.y -= size * 0.5;
} }
@@ -45,7 +45,7 @@ module es {
shape.graphics.endFill(); shape.graphics.endFill();
} }
public static getColorMatrix(color: number): egret.ColorMatrixFilter{ public static getColorMatrix(color: number): egret.ColorMatrixFilter {
let colorMatrix = [ let colorMatrix = [
1, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
+9 -8
View File
@@ -8,18 +8,19 @@ module es {
/** 上下文 */ /** 上下文 */
public context: any; public context: any;
constructor(func: Function, context: any){ constructor(func: Function, context: any) {
this.func = func; this.func = func;
this.context = context; this.context = context;
} }
} }
/** /**
* *
*/ */
export class Emitter<T> { export class Emitter<T> {
private _messageTable: Map<T, FuncPack[]>; private _messageTable: Map<T, FuncPack[]>;
constructor(){ constructor() {
this._messageTable = new Map<T, FuncPack[]>(); this._messageTable = new Map<T, FuncPack[]>();
} }
@@ -29,9 +30,9 @@ module es {
* @param handler * @param handler
* @param context * @param context
*/ */
public addObserver(eventType: T, handler: Function, context: any){ public addObserver(eventType: T, handler: Function, context: any) {
let list: FuncPack[] = this._messageTable.get(eventType); let list: FuncPack[] = this._messageTable.get(eventType);
if (!list){ if (!list) {
list = []; list = [];
this._messageTable.set(eventType, list); this._messageTable.set(eventType, list);
} }
@@ -46,7 +47,7 @@ module es {
* @param eventType * @param eventType
* @param handler * @param handler
*/ */
public removeObserver(eventType: T, handler: Function){ public removeObserver(eventType: T, handler: Function) {
let messageData = this._messageTable.get(eventType); let messageData = this._messageTable.get(eventType);
let index = messageData.findIndex(data => data.func == handler); let index = messageData.findIndex(data => data.func == handler);
if (index != -1) if (index != -1)
@@ -58,10 +59,10 @@ module es {
* @param eventType * @param eventType
* @param data * @param data
*/ */
public emit(eventType: T, data?: any){ public emit(eventType: T, data?: any) {
let list: FuncPack[] = this._messageTable.get(eventType); let list: FuncPack[] = this._messageTable.get(eventType);
if (list){ if (list) {
for (let i = list.length - 1; i >= 0; i --) for (let i = list.length - 1; i >= 0; i--)
list[i].func.call(list[i].context, data); list[i].func.call(list[i].context, data);
} }
} }
+13 -9
View File
@@ -1,10 +1,12 @@
module es { module es {
export class GlobalManager { export class GlobalManager {
public _enabled: boolean;
/** /**
* true则启用了GlobalManager * true则启用了GlobalManager
* OnEnabled/OnDisable * OnEnabled/OnDisable
*/ */
public get enabled(){ public get enabled() {
return this._enabled; return this._enabled;
} }
@@ -13,7 +15,7 @@ module es {
* OnEnabled/OnDisable * OnEnabled/OnDisable
* @param value * @param value
*/ */
public set enabled(value: boolean){ public set enabled(value: boolean) {
this.setEnabled(value); this.setEnabled(value);
} }
@@ -21,31 +23,33 @@ module es {
* /GlobalManager * /GlobalManager
* @param isEnabled * @param isEnabled
*/ */
public setEnabled(isEnabled: boolean){ public setEnabled(isEnabled: boolean) {
if (this._enabled != isEnabled){ if (this._enabled != isEnabled) {
this._enabled = isEnabled; this._enabled = isEnabled;
if (this._enabled){ if (this._enabled) {
this.onEnabled(); this.onEnabled();
} else { } else {
this.onDisabled(); this.onDisabled();
} }
} }
} }
public _enabled: boolean;
/** /**
* GlobalManager启用时调用 * GlobalManager启用时调用
*/ */
public onEnabled(){} public onEnabled() {
}
/** /**
* GlobalManager禁用时调用 * GlobalManager禁用时调用
*/ */
public onDisabled(){} public onDisabled() {
}
/** /**
* frame .update之前调用每一帧 * frame .update之前调用每一帧
*/ */
public update(){} public update() {
}
} }
} }
+64 -54
View File
@@ -4,11 +4,12 @@ module es {
public y = 0; public y = 0;
public touchPoint: number = -1; public touchPoint: number = -1;
public touchDown: boolean = false; public touchDown: boolean = false;
public get position(){
public get position() {
return new Vector2(this.x, this.y); return new Vector2(this.x, this.y);
} }
public reset(){ public reset() {
this.x = 0; this.x = 0;
this.y = 0; this.y = 0;
this.touchDown = false; this.touchDown = false;
@@ -19,55 +20,64 @@ module es {
export class Input { export class Input {
private static _init: boolean = false; private static _init: boolean = false;
private static _previousTouchState: TouchState = new TouchState(); private static _previousTouchState: TouchState = new TouchState();
private static _gameTouchs: TouchState[] = [];
private static _resolutionOffset: Vector2 = new Vector2(); private static _resolutionOffset: Vector2 = new Vector2();
private static _resolutionScale: Vector2 = Vector2.one;
private static _touchIndex: number = 0; private static _touchIndex: number = 0;
private static _totalTouchCount: number = 0;
/** 返回第一个触摸点的坐标 */ private static _gameTouchs: TouchState[] = [];
public static get touchPosition(){
if (!this._gameTouchs[0])
return Vector2.zero;
return this._gameTouchs[0].position;
}
/** 获取最大触摸数 */
public static get maxSupportedTouch(){
return Core._instance.stage.maxTouches;
}
/**
*
*/
public static set maxSupportedTouch(value: number){
Core._instance.stage.maxTouches = value;
this.initTouchCache();
}
/** 获取缩放值 默认为1 */
public static get resolutionScale(){
return this._resolutionScale;
}
/** 当前触摸点数量 */
public static get totalTouchCount(){
return this._totalTouchCount;
}
/** /**
* *
* touchPoint是否为-1 * touchPoint是否为-1
* touchDown * touchDown
*/ */
public static get gameTouchs(){ public static get gameTouchs() {
return this._gameTouchs; return this._gameTouchs;
} }
private static _resolutionScale: Vector2 = Vector2.one;
/** 获取缩放值 默认为1 */
public static get resolutionScale() {
return this._resolutionScale;
}
private static _totalTouchCount: number = 0;
/** 当前触摸点数量 */
public static get totalTouchCount() {
return this._totalTouchCount;
}
/** 返回第一个触摸点的坐标 */
public static get touchPosition() {
if (!this._gameTouchs[0])
return Vector2.zero;
return this._gameTouchs[0].position;
}
/** 获取最大触摸数 */
public static get maxSupportedTouch() {
return Core._instance.stage.maxTouches;
}
/**
*
*/
public static set maxSupportedTouch(value: number) {
Core._instance.stage.maxTouches = value;
this.initTouchCache();
}
/** 获取第一个触摸点距离上次距离的增量 */ /** 获取第一个触摸点距离上次距离的增量 */
public static get touchPositionDelta(){ public static get touchPositionDelta() {
let delta = Vector2.subtract(this.touchPosition, this._previousTouchState.position); let delta = Vector2.subtract(this.touchPosition, this._previousTouchState.position);
if (delta.length() > 0){ if (delta.length() > 0) {
this.setpreviousTouchState(this._gameTouchs[0]); this.setpreviousTouchState(this._gameTouchs[0]);
} }
return delta; return delta;
} }
public static initialize(){ public static initialize() {
if (this._init) if (this._init)
return; return;
@@ -81,67 +91,67 @@ module es {
this.initTouchCache(); this.initTouchCache();
} }
private static initTouchCache(){ public static scaledPosition(position: Vector2) {
let scaledPos = new Vector2(position.x - this._resolutionOffset.x, position.y - this._resolutionOffset.y);
return Vector2.multiply(scaledPos, this.resolutionScale);
}
private static initTouchCache() {
this._totalTouchCount = 0; this._totalTouchCount = 0;
this._touchIndex = 0; this._touchIndex = 0;
this._gameTouchs.length = 0; this._gameTouchs.length = 0;
for (let i = 0; i < this.maxSupportedTouch; i ++){ for (let i = 0; i < this.maxSupportedTouch; i++) {
this._gameTouchs.push(new TouchState()); this._gameTouchs.push(new TouchState());
} }
} }
private static touchBegin(evt: egret.TouchEvent){ private static touchBegin(evt: egret.TouchEvent) {
if (this._touchIndex < this.maxSupportedTouch){ if (this._touchIndex < this.maxSupportedTouch) {
this._gameTouchs[this._touchIndex].touchPoint = evt.touchPointID; this._gameTouchs[this._touchIndex].touchPoint = evt.touchPointID;
this._gameTouchs[this._touchIndex].touchDown = evt.touchDown; this._gameTouchs[this._touchIndex].touchDown = evt.touchDown;
this._gameTouchs[this._touchIndex].x = evt.stageX; this._gameTouchs[this._touchIndex].x = evt.stageX;
this._gameTouchs[this._touchIndex].y = evt.stageY; this._gameTouchs[this._touchIndex].y = evt.stageY;
if (this._touchIndex == 0){ if (this._touchIndex == 0) {
this.setpreviousTouchState(this._gameTouchs[0]); this.setpreviousTouchState(this._gameTouchs[0]);
} }
this._touchIndex ++; this._touchIndex++;
this._totalTouchCount ++; this._totalTouchCount++;
} }
} }
private static touchMove(evt: egret.TouchEvent){ private static touchMove(evt: egret.TouchEvent) {
if (evt.touchPointID == this._gameTouchs[0].touchPoint){ if (evt.touchPointID == this._gameTouchs[0].touchPoint) {
this.setpreviousTouchState(this._gameTouchs[0]); this.setpreviousTouchState(this._gameTouchs[0]);
} }
let touchIndex = this._gameTouchs.findIndex(touch => touch.touchPoint == evt.touchPointID); let touchIndex = this._gameTouchs.findIndex(touch => touch.touchPoint == evt.touchPointID);
if (touchIndex != -1){ if (touchIndex != -1) {
let touchData = this._gameTouchs[touchIndex]; let touchData = this._gameTouchs[touchIndex];
touchData.x = evt.stageX; touchData.x = evt.stageX;
touchData.y = evt.stageY; touchData.y = evt.stageY;
} }
} }
private static touchEnd(evt: egret.TouchEvent){ private static touchEnd(evt: egret.TouchEvent) {
let touchIndex = this._gameTouchs.findIndex(touch => touch.touchPoint == evt.touchPointID); let touchIndex = this._gameTouchs.findIndex(touch => touch.touchPoint == evt.touchPointID);
if (touchIndex != -1){ if (touchIndex != -1) {
let touchData = this._gameTouchs[touchIndex]; let touchData = this._gameTouchs[touchIndex];
touchData.reset(); touchData.reset();
if (touchIndex == 0) if (touchIndex == 0)
this._previousTouchState.reset(); this._previousTouchState.reset();
this._totalTouchCount --; this._totalTouchCount--;
if (this.totalTouchCount == 0){ if (this.totalTouchCount == 0) {
this._touchIndex = 0; this._touchIndex = 0;
} }
} }
} }
private static setpreviousTouchState(touchState: TouchState){ private static setpreviousTouchState(touchState: TouchState) {
this._previousTouchState = new TouchState(); this._previousTouchState = new TouchState();
this._previousTouchState.x = touchState.position.x; this._previousTouchState.x = touchState.position.x;
this._previousTouchState.y = touchState.position.y; this._previousTouchState.y = touchState.position.y;
this._previousTouchState.touchPoint = touchState.touchPoint; this._previousTouchState.touchPoint = touchState.touchPoint;
this._previousTouchState.touchDown = touchState.touchDown; this._previousTouchState.touchDown = touchState.touchDown;
} }
public static scaledPosition(position: Vector2){
let scaledPos = new Vector2(position.x - this._resolutionOffset.x, position.y - this._resolutionOffset.y);
return Vector2.multiply(scaledPos, this.resolutionScale);
}
} }
} }
+37 -51
View File
@@ -4,12 +4,6 @@ class KeyboardUtils {
*/ */
public static TYPE_KEY_DOWN: number = 0; public static TYPE_KEY_DOWN: number = 0;
public static TYPE_KEY_UP: number = 1; public static TYPE_KEY_UP: number = 1;
//存放按下注册数据的字典
private static keyDownDict: Object;
//存放按起注册数据的字典
private static keyUpDict: Object;
/** /**
* *
*/ */
@@ -39,7 +33,6 @@ class KeyboardUtils {
public static X: string = "X"; public static X: string = "X";
public static Y: string = "Y"; public static Y: string = "Y";
public static Z: string = "Z"; public static Z: string = "Z";
public static ESC: string = "Esc"; public static ESC: string = "Esc";
public static F1: string = "F1"; public static F1: string = "F1";
public static F2: string = "F2"; public static F2: string = "F2";
@@ -53,7 +46,6 @@ class KeyboardUtils {
public static F10: string = "F10"; public static F10: string = "F10";
public static F11: string = "F11"; public static F11: string = "F11";
public static F12: string = "F12"; public static F12: string = "F12";
public static NUM_1: string = "1"; public static NUM_1: string = "1";
public static NUM_2: string = "2"; public static NUM_2: string = "2";
public static NUM_3: string = "3"; public static NUM_3: string = "3";
@@ -64,7 +56,6 @@ class KeyboardUtils {
public static NUM_8: string = "8"; public static NUM_8: string = "8";
public static NUM_9: string = "9"; public static NUM_9: string = "9";
public static NUM_0: string = "0"; public static NUM_0: string = "0";
public static TAB: string = "Tab"; public static TAB: string = "Tab";
public static CTRL: string = "Ctrl"; public static CTRL: string = "Ctrl";
public static ALT: string = "Alt"; public static ALT: string = "Alt";
@@ -73,25 +64,24 @@ class KeyboardUtils {
public static ENTER: string = "Enter"; public static ENTER: string = "Enter";
public static SPACE: string = "Space"; public static SPACE: string = "Space";
public static BACK_SPACE: string = "Back Space"; public static BACK_SPACE: string = "Back Space";
public static INSERT: string = "Insert"; public static INSERT: string = "Insert";
public static DELETE: string = "Page Down"; public static DELETE: string = "Page Down";
public static HOME: string = "Home"; public static HOME: string = "Home";
public static END: string = "Page Down"; public static END: string = "Page Down";
public static PAGE_UP: string = "Page Up"; public static PAGE_UP: string = "Page Up";
public static PAGE_DOWN: string = "Page Down"; public static PAGE_DOWN: string = "Page Down";
public static LEFT: string = "Left"; public static LEFT: string = "Left";
public static RIGHT: string = "Right"; public static RIGHT: string = "Right";
public static UP: string = "Up"; public static UP: string = "Up";
public static DOWN: string = "Down"; public static DOWN: string = "Down";
public static PAUSE_BREAK: string = "Pause Break"; public static PAUSE_BREAK: string = "Pause Break";
public static NUM_LOCK: string = "Num Lock"; public static NUM_LOCK: string = "Num Lock";
public static SCROLL_LOCK: string = "Scroll Lock"; public static SCROLL_LOCK: string = "Scroll Lock";
public static WINDOWS: string = "Windows"; public static WINDOWS: string = "Windows";
//存放按下注册数据的字典
private static keyDownDict: Object;
//存放按起注册数据的字典
private static keyUpDict: Object;
public static init(): void { public static init(): void {
this.keyDownDict = {}; this.keyDownDict = {};
@@ -100,6 +90,37 @@ class KeyboardUtils {
document.addEventListener("keyup", this.onKeyUpHander); document.addEventListener("keyup", this.onKeyUpHander);
} }
/**
*
* @param key
* @param fun
* @param type TYPE_KEY_DOWNTYPE_KEY_UP
*/
public static registerKey(key: string, fun: Function, thisObj: any, type: number = 0, ...args): void {
var keyDict: Object = type ? this.keyUpDict : this.keyDownDict;
keyDict[key] = {"fun": fun, args: args, "thisObj": thisObj};
}
/**
*
* @param key
* @param type
*/
public static unregisterKey(key: string, type: number = 0): void {
var keyDict: Object = type ? this.keyUpDict : this.keyDownDict;
delete keyDict[key];
}
/**
*
*/
public static destroy(): void {
this.keyDownDict = null;
this.keyUpDict = null;
document.removeEventListener("keydown", this.onKeyDonwHander);
document.removeEventListener("keyup", this.onKeyUpHander);
}
private static onKeyDonwHander(event: KeyboardEvent): void { private static onKeyDonwHander(event: KeyboardEvent): void {
if (!this.keyDownDict) return; if (!this.keyDownDict) return;
var key: string = this.keyCodeToString(event.keyCode); var key: string = this.keyCodeToString(event.keyCode);
@@ -112,7 +133,6 @@ class KeyboardUtils {
} }
} }
private static onKeyUpHander(event: KeyboardEvent): void { private static onKeyUpHander(event: KeyboardEvent): void {
if (!this.keyUpDict) return; if (!this.keyUpDict) return;
var key: string = this.keyCodeToString(event.keyCode); var key: string = this.keyCodeToString(event.keyCode);
@@ -125,33 +145,10 @@ class KeyboardUtils {
} }
} }
/**
*
* @param key
* @param fun
* @param type TYPE_KEY_DOWNTYPE_KEY_UP
*/
public static registerKey(key: string, fun: Function, thisObj: any, type: number = 0, ...args): void {
var keyDict: Object = type ? this.keyUpDict : this.keyDownDict;
keyDict[key] = { "fun": fun, args: args, "thisObj": thisObj };
}
/**
*
* @param key
* @param type
*/
public static unregisterKey(key: string, type: number = 0): void {
var keyDict: Object = type ? this.keyUpDict : this.keyDownDict;
delete keyDict[key];
}
/** /**
* keyCode或charCode获取相应的字符串代号 * keyCode或charCode获取相应的字符串代号
* @param keyCode * @param keyCode
* @return * @return
*/ */
private static keyCodeToString(keyCode: number): string { private static keyCodeToString(keyCode: number): string {
switch (keyCode) { switch (keyCode) {
@@ -225,15 +222,4 @@ class KeyboardUtils {
return String.fromCharCode(keyCode); return String.fromCharCode(keyCode);
} }
} }
/**
*
*/
public static destroy(): void {
this.keyDownDict = null;
this.keyUpDict = null;
document.removeEventListener("keydown", this.onKeyDonwHander);
document.removeEventListener("keyup", this.onKeyUpHander);
}
} }
+6 -6
View File
@@ -9,10 +9,10 @@ module es {
* 使cacheCount对象填充缓存 * 使cacheCount对象填充缓存
* @param cacheCount * @param cacheCount
*/ */
public static warmCache(cacheCount: number){ public static warmCache(cacheCount: number) {
cacheCount -= this._objectQueue.length; cacheCount -= this._objectQueue.length;
if (cacheCount > 0){ if (cacheCount > 0) {
for (let i = 0; i < cacheCount; i ++){ for (let i = 0; i < cacheCount; i++) {
this._objectQueue.unshift([]); this._objectQueue.unshift([]);
} }
} }
@@ -22,7 +22,7 @@ module es {
* cacheCount项目 * cacheCount项目
* @param cacheCount * @param cacheCount
*/ */
public static trimCache(cacheCount){ public static trimCache(cacheCount) {
while (cacheCount > this._objectQueue.length) while (cacheCount > this._objectQueue.length)
this._objectQueue.shift(); this._objectQueue.shift();
} }
@@ -30,7 +30,7 @@ module es {
/** /**
* *
*/ */
public static clearCache(){ public static clearCache() {
this._objectQueue.length = 0; this._objectQueue.length = 0;
} }
@@ -48,7 +48,7 @@ module es {
* *
* @param obj * @param obj
*/ */
public static free<T>(obj: Array<T>){ public static free<T>(obj: Array<T>) {
this._objectQueue.unshift(obj); this._objectQueue.unshift(obj);
obj.length = 0; obj.length = 0;
} }
+7 -6
View File
@@ -13,24 +13,25 @@ const nextTick = fn => {
class LockUtils { class LockUtils {
private _keyX: string; private _keyX: string;
private _keyY: string; private _keyY: string;
constructor(key){
constructor(key) {
this._keyX = `mutex_key_${key}_X`; this._keyX = `mutex_key_${key}_X`;
this._keyY = `mutex_key_${key}_Y`; this._keyY = `mutex_key_${key}_Y`;
} }
public lock(){ public lock() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fn = () => { const fn = () => {
setItem(this._keyX, THREAD_ID); setItem(this._keyX, THREAD_ID);
if (!getItem(this._keyY) === null){ if (!getItem(this._keyY) === null) {
// restart // restart
nextTick(fn); nextTick(fn);
} }
setItem(this._keyY, THREAD_ID); setItem(this._keyY, THREAD_ID);
if (getItem(this._keyX) !== THREAD_ID){ if (getItem(this._keyX) !== THREAD_ID) {
// delay // delay
setTimeout(()=>{ setTimeout(() => {
if (getItem(this._keyY) !== THREAD_ID){ if (getItem(this._keyY) !== THREAD_ID) {
// restart // restart
nextTick(fn); nextTick(fn);
return; return;
+3 -3
View File
@@ -6,16 +6,16 @@ module es {
public first: T; public first: T;
public second: T; public second: T;
constructor(first: T, second: T){ constructor(first: T, second: T) {
this.first = first; this.first = first;
this.second = second; this.second = second;
} }
public clear(){ public clear() {
this.first = this.second = null; this.first = this.second = null;
} }
public equals(other: Pair<T>){ public equals(other: Pair<T>) {
return this.first == other.first && this.second == other.second; return this.first == other.first && this.second == other.second;
} }
} }
+20 -21
View File
@@ -43,36 +43,32 @@ class RandomUtils {
} }
/** /**
* a - b之间的随机数 Math.max(a, b) * a - b之间的随机数 Math.max(a, b)
* @param a * @param a
* @param b * @param b
* @return a < b, [a, b) * @return a < b, [a, b)
*/ */
public static randnum(a: number, b: number): number { public static randnum(a: number, b: number): number {
return this.random() * (b - a) + a; return this.random() * (b - a) + a;
} }
/** /**
* *
* @param array * @param array
* @return * @return
*/ */
public static shuffle(array: any[]): any[] { public static shuffle(array: any[]): any[] {
array.sort(this._randomCompare); array.sort(this._randomCompare);
return array; return array;
} }
private static _randomCompare(a: Object, b: Object): number {
return (this.random() > .5) ? 1 : -1;
}
/** /**
* *
* @param sequence vectorlength属性 * @param sequence vectorlength属性
* *
* @return * @return
* *
*/ */
public static choice(sequence: any): any { public static choice(sequence: any): any {
if (!sequence.hasOwnProperty("length")) if (!sequence.hasOwnProperty("length"))
throw new Error('无法对此对象执行此操作'); throw new Error('无法对此对象执行此操作');
@@ -83,7 +79,6 @@ class RandomUtils {
return sequence[index]; return sequence[index];
} }
/** /**
* æ ? * æ ?
* <pre> * <pre>
@@ -125,10 +120,14 @@ class RandomUtils {
/** /**
* *
* @param chance * @param chance
* @return * @return
*/ */
public static boolean(chance: number = .5): boolean { public static boolean(chance: number = .5): boolean {
return (this.random() < chance) ? true : false; return (this.random() < chance) ? true : false;
} }
private static _randomCompare(a: Object, b: Object): number {
return (this.random() > .5) ? 1 : -1;
}
} }
+1 -1
View File
@@ -5,7 +5,7 @@ module es {
* @param first * @param first
* @param point * @param point
*/ */
public static union(first: Rectangle, point: Vector2){ public static union(first: Rectangle, point: Vector2) {
let rect = new Rectangle(point.x, point.y, 0, 0); let rect = new Rectangle(point.x, point.y, 0, 0);
// let rectResult = first.union(rect); // let rectResult = first.union(rect);
let result = new Rectangle(); let result = new Rectangle();
+26 -26
View File
@@ -11,12 +11,25 @@ module es {
private _triPrev: number[] = new Array<number>(12); private _triPrev: number[] = new Array<number>(12);
private _triNext: number[] = new Array<number>(12); private _triNext: number[] = new Array<number>(12);
public static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean {
if (Vector2Ext.cross(Vector2.subtract(point, a), Vector2.subtract(b, a)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, b), Vector2.subtract(c, b)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, c), Vector2.subtract(a, c)) < 0)
return false;
return true;
}
/** /**
* CCWarePointsCCW参数传递为false * CCWarePointsCCW参数传递为false
* @param points * @param points
* @param arePointsCCW * @param arePointsCCW
*/ */
public triangulate(points: Vector2[], arePointsCCW: boolean = true){ public triangulate(points: Vector2[], arePointsCCW: boolean = true) {
let count = points.length; let count = points.length;
// 设置前一个链接和下一个链接 // 设置前一个链接和下一个链接
@@ -29,29 +42,29 @@ module es {
let index = 0; let index = 0;
// 继续移除所有的三角形,直到只剩下一个三角形 // 继续移除所有的三角形,直到只剩下一个三角形
while (count > 3 && iterations < 500){ while (count > 3 && iterations < 500) {
iterations ++; iterations++;
let isEar = true; let isEar = true;
let a = points[this._triPrev[index]]; let a = points[this._triPrev[index]];
let b = points[index]; let b = points[index];
let c = points[this._triNext[index]]; let c = points[this._triNext[index]];
if (Vector2Ext.isTriangleCCW(a, b, c)){ if (Vector2Ext.isTriangleCCW(a, b, c)) {
let k = this._triNext[this._triNext[index]]; let k = this._triNext[this._triNext[index]];
do { do {
if (Triangulator.testPointTriangle(points[k], a, b, c)){ if (Triangulator.testPointTriangle(points[k], a, b, c)) {
isEar = false; isEar = false;
break; break;
} }
k = this._triNext[k]; k = this._triNext[k];
} while (k != this._triPrev[index]); } while (k != this._triPrev[index]);
}else{ } else {
isEar = false; isEar = false;
} }
if (isEar){ if (isEar) {
this.triangleIndices.push(this._triPrev[index]); this.triangleIndices.push(this._triPrev[index]);
this.triangleIndices.push(index); this.triangleIndices.push(index);
this.triangleIndices.push(this._triNext[index]); this.triangleIndices.push(this._triNext[index]);
@@ -59,11 +72,11 @@ module es {
// 删除vert通过重定向相邻vert的上一个和下一个链接,从而减少vertext计数 // 删除vert通过重定向相邻vert的上一个和下一个链接,从而减少vertext计数
this._triNext[this._triPrev[index]] = this._triNext[index]; this._triNext[this._triPrev[index]] = this._triNext[index];
this._triPrev[this._triNext[index]] = this._triPrev[index]; this._triPrev[this._triNext[index]] = this._triPrev[index];
count --; count--;
// 接下来访问前一个vert // 接下来访问前一个vert
index = this._triPrev[index]; index = this._triPrev[index];
}else{ } else {
index = this._triNext[index]; index = this._triNext[index];
} }
} }
@@ -76,19 +89,19 @@ module es {
this.triangleIndices.reverse(); this.triangleIndices.reverse();
} }
private initialize(count: number){ private initialize(count: number) {
this.triangleIndices.length = 0; this.triangleIndices.length = 0;
if (this._triNext.length < count){ if (this._triNext.length < count) {
this._triNext.reverse(); this._triNext.reverse();
this._triNext = new Array<number>(Math.max(this._triNext.length * 2, count)); this._triNext = new Array<number>(Math.max(this._triNext.length * 2, count));
} }
if (this._triPrev.length < count){ if (this._triPrev.length < count) {
this._triPrev.reverse(); this._triPrev.reverse();
this._triPrev = new Array<number>(Math.max(this._triPrev.length * 2, count)); this._triPrev = new Array<number>(Math.max(this._triPrev.length * 2, count));
} }
for (let i = 0; i < count;i ++){ for (let i = 0; i < count; i++) {
this._triPrev[i] = i - 1; this._triPrev[i] = i - 1;
this._triNext[i] = i + 1; this._triNext[i] = i + 1;
} }
@@ -96,18 +109,5 @@ module es {
this._triPrev[0] = count - 1; this._triPrev[0] = count - 1;
this._triNext[count - 1] = 0; this._triNext[count - 1] = 0;
} }
public static testPointTriangle(point: Vector2, a: Vector2, b: Vector2, c: Vector2): boolean{
if (Vector2Ext.cross(Vector2.subtract(point, a), Vector2.subtract(b, a)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, b), Vector2.subtract(c, b)) < 0)
return false;
if (Vector2Ext.cross(Vector2.subtract(point, c), Vector2.subtract(a, c)) < 0)
return false;
return true;
}
} }
} }

Some files were not shown because too many files have changed in this diff Show More