Merge branch 'master' into develop

# Conflicts:
#	demo/libs/framework/framework.min.js
#	demo/src/game/MainScene.ts
#	source/bin/framework.min.js
This commit is contained in:
YHH
2020-08-07 08:51:19 +08:00
143 changed files with 35441 additions and 16863 deletions
+3
View File
@@ -1,3 +1,6 @@
/source/node_modules
/demo/bin-debug
/demo/bin-release
/.idea
/.vscode
/demo_wxgame
-15
View File
@@ -1,15 +0,0 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
}
]
}
+33 -20
View File
@@ -3,26 +3,11 @@
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/esengine/egret-framework.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/esengine/egret-framework/context:javascript)
```
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/esengine/egret-framework.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/esengine/egret-framework/context:javascript)
```
这是一套用于egret的游戏框架,里面包含ECS框架用于管理场景实体,一些常用2D碰撞检测及A*寻路。如果您还需要包含其他的AI系统可以查看作者其他库(行为树、简易FSM、实用AI)。
这是一套用于egret的游戏框架,里面包含ECS框架用于管理场景实体,MVC框架用于管理ui界面(fairygui),一些常用2D碰撞检测及A*寻路。如果您还需要包含其他的AI系统可以查看作者其他库(行为树、简易FSM、实用AI)。
## 当前版本功能
## 版本计划功能
- [x] 简易ECS框架
- [x] A*寻路(AStar)
- [x] 常用碰撞检测
- [x] 数学库
- [x] 简易矩阵类
- [x] 简易2d 向量类
- [x] 掩码实用类
- [x] BreadthFirst 寻路算法
- [x] Dijkstra 寻路算法
- [x] 事件处理器
- [x] ECS
- [x] 组件列表
- [x] 碰撞组件
- [x] 移动组件
@@ -38,9 +23,37 @@
- [x] 系统列表
- [x] 被动系统
- [x] 协调系统
- [ ] 数学库
- [ ] 贝塞尔曲线
- [ ] 快速随机数类
- [x] A*寻路(AStar)
- [x] 常用碰撞检测
- [x] 数学库
- [x] 简易矩阵类
- [x] 简易2d 向量类
- [x] 掩码实用类
- [x] 贝塞尔曲线
- [x] 快速随机数类
- [x] BreadthFirst 寻路算法
- [x] Dijkstra 寻路算法
- [x] 事件处理器
## 关于egret用ecs框架(typescript/javascript
ecs 是功能强大的实体组件系统。typescript与其他语言不同,因此我对ecs的设计尽可能的支持typescript特性。虽然ecs拥有标准实体组件系统,但在细节上有很大不同。创建标准ecs通常处于原始速度、缓存位置和其他性能原因。使用typescript,我们没有struct,因为没有必要匹配标准实体组件系统的设计方式,因为我们对内存布局没有那种控制。
ecs更灵活,可以更好的集中、组织、排序和过滤游戏中的对象。ecs让您拥有轻量级实体和组件,这些组件可以由系统批量处理。
例如,您在制作一个射手,您可能会有几十到几百个子弹,这些作为轻量级实体由系统批量处理。
所以ecs在设计当中拥有四种重要类型:世界(Scene),过滤器(Matcher),系统(System)和实体(Entity)
## 世界(Scene
Scene是ecs包含系统和实体最外面的容器。
## 实体(Entity
实体只由系统处理。
## 组件(Component)
组件应该只包含数据而没有逻辑代码。对数据进行逻辑是系统的工作。
## 系统(System
ecs中的系统会不断的更新实体。系统使用过滤器选择某些实体,然后仅更新那些选择的实体。
## 作者其他库(egret
+1
View File
@@ -0,0 +1 @@
theme: jekyll-theme-slate
+2
View File
@@ -0,0 +1,2 @@
# Default ignored files
/workspace.xml
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/demo.iml" filepath="$PROJECT_DIR$/.idea/demo.iml" />
</modules>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
+1833 -1043
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+1 -2
View File
@@ -11,12 +11,11 @@
"libs/long/long.js"
],
"game": [
"bin-debug/game/CoreEmitterType.js",
"bin-debug/AssetAdapter.js",
"bin-debug/LoadingUI.js",
"bin-debug/Main.js",
"bin-debug/Platform.js",
"bin-debug/ThemeAdapter.js",
"bin-debug/LoadingUI.js",
"bin-debug/game/MainScene.js",
"bin-debug/game/PlayerController.js",
"bin-debug/game/SimplePooled.js",
+3
View File
@@ -44,6 +44,9 @@ export class WxgamePlugin implements plugins.Command {
if (filename == 'main.js') {
content += "\n;window.Main = Main;"
}
if (filename == 'libs/long/long.js' || filename == 'libs/long/long.min.js'){
content += "window.Long = long;"
}
this.md5Obj[path.basename(filename)] = this.md5(content)
file.contents = new Buffer(content);
}
+18 -64
View File
@@ -27,71 +27,29 @@
//
//////////////////////////////////////////////////////////////////////////////////////
class Main extends eui.UILayer {
public static emitter: Emitter<CoreEmitterType>;
public static manager: SceneManager;
protected createChildren(): void {
super.createChildren();
egret.lifecycle.addLifecycleListener((context) => {
// custom lifecycle plugin
})
egret.lifecycle.onPause = () => {
egret.ticker.pause();
}
egret.lifecycle.onResume = () => {
egret.ticker.resume();
}
//inject the custom material parser
//注入自定义的素材解析器
let assetAdapter = new AssetAdapter();
egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
Main.manager = new SceneManager(this.stage);
Main.emitter = new Emitter<CoreEmitterType>();
this.addEventListener(egret.Event.ENTER_FRAME, this.updateFrame, this);
class Main extends es.Core {
protected initialize() {
this.runGame();
}
private updateFrame(evt: egret.Event){
Main.emitter.emit(CoreEmitterType.Update, evt);
private runGame() {
this.loadResource();
}
private async runGame() {
await this.loadResource();
this.createGameScene();
}
private async loadResource() {
try {
const loadingView = new LoadingUI();
this.stage.addChild(loadingView);
await RES.loadConfig("resource/default.res.json", "resource/");
await this.loadTheme();
await RES.loadGroup("preload", 0, loadingView);
this.stage.removeChild(loadingView);
}
catch (e) {
console.error(e);
}
}
private loadTheme() {
return new Promise((resolve, reject) => {
// load skin theme configuration file, you can manually modify the file. And replace the default skin.
//加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
let theme = new eui.Theme("resource/default.thm.json", this.stage);
theme.addEventListener(eui.UIEvent.COMPLETE, () => {
resolve();
}, this);
})
private loadResource() {
const loadingView = new LoadingUI();
this.stage.addChild(loadingView);
RES.loadConfig("resource/default.res.json", "resource/").then(()=>{
RES.loadGroup("preload", 0, loadingView).then(()=>{
this.stage.removeChild(loadingView);
this.createGameScene();
}).catch(err => {
console.error(err);
});
}).catch(err =>{
console.error(err);
});
}
/**
@@ -99,10 +57,6 @@ class Main extends eui.UILayer {
* Create scene interface
*/
protected createGameScene(): void {
SceneManager.scene = new MainScene();
// Main.emitter.addObserver(CoreEmitterType.Update, ()=>{
// console.log("update emitter");
// });
es.Core.scene = new scene.MainScene();
}
}
-3
View File
@@ -1,3 +0,0 @@
enum CoreEmitterType {
Update,
}
+83 -79
View File
@@ -1,86 +1,90 @@
class MainScene extends Scene {
constructor() {
super();
module scene {
export class MainScene extends es.Scene {
constructor() {
super();
// this.addEntityProcessor(new SpawnerSystem(new Matcher()));
this.astarTest();
this.dijkstraTest();
this.breadthfirstTest();
}
public async onStart() {
let sprite = new Sprite(RES.getRes("checkbox_select_disabled_png"));
let bg = this.createEntity("bg");
bg.addComponent(new SpriteRenderer()).setSprite(sprite).setColor(0xff0000);
bg.addComponent(new PlayerController());
bg.addComponent(new Mover());
bg.addComponent(new BoxCollider());
bg.position = new Vector2(300, 300);
for (let i = 0; i < 1; i++) {
let sprite = new Sprite(RES.getRes("checkbox_select_disabled_png"));
let player2 = this.createEntity("player2");
player2.addComponent(new SpriteRenderer()).setSprite(sprite);
player2.position = new Vector2(200, 200);
player2.addComponent(new BoxCollider());
// this.addEntityProcessor(new SpawnerSystem(new Matcher()));
this.astarTest();
this.dijkstraTest();
this.breadthfirstTest();
}
this.camera.follow(bg, CameraStyle.lockOn);
public async onStart() {
let sprite = new es.Sprite(RES.getRes("checkbox_select_disabled_png"));
let bg = this.createEntity("bg");
bg.addComponent(new es.SpriteRenderer()).setSprite(sprite).setColor(0xff0000);
bg.addComponent(new component.PlayerController());
bg.addComponent(new es.Mover());
bg.addComponent(new es.ScrollingSpriteRenderer(sprite));
bg.addComponent(new es.BoxCollider());
bg.position = new es.Vector2(Math.random() * 200, Math.random() * 200);
let pool = new ComponentPool<SimplePooled>(SimplePooled);
let c1 = pool.obtain();
let c2 = pool.obtain();
pool.free(c1);
let c1b = pool.obtain();
for (let i = 0; i < 20; i++) {
let sprite = new es.Sprite(RES.getRes("checkbox_select_disabled_png"));
let player2 = this.createEntity("player2");
player2.addComponent(new es.SpriteRenderer()).setSprite(sprite);
player2.position = new es.Vector2(Math.random() * 1000, Math.random() * 1000);
player2.addComponent(new es.BoxCollider());
}
console.log(c1 != c2);
console.log(c1 == c1b);
this.camera.follow(bg, es.CameraStyle.lockOn);
let button = new eui.Button();
button.label = "切换场景";
this.addChild(button);
button.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
SceneManager.startSceneTransition(new FadeTransition(() => {
return new MainScene();
}));
}, this);
let pool = new es.ComponentPool<component.SimplePooled>(component.SimplePooled);
let c1 = pool.obtain();
let c2 = pool.obtain();
pool.free(c1);
let c1b = pool.obtain();
console.log(c1 != c2);
console.log(c1 == c1b);
let button = new eui.Button();
button.label = "切换场景";
this.addChild(button);
button.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
es.Core.startSceneTransition(new es.FadeTransition(() => {
return new MainScene();
}));
}, this);
}
public breadthfirstTest() {
let graph = new es.UnweightedGraph<string>();
graph.addEdgesForNode("a", ["b"]); // a->b
graph.addEdgesForNode("b", ["a", "c", "d"]); // b->a b->c b->d
graph.addEdgesForNode("c", ["a"]); // c->a
graph.addEdgesForNode("d", ["e", "a"]); // d->e d->a
graph.addEdgesForNode("e", ["b"]); // e->b
// 计算从c到e的路径
let path = es.BreadthFirstPathfinder.search(graph, "c", "e");
console.log(path);
}
public dijkstraTest() {
let graph = new es.WeightedGridGraph(20, 20);
graph.weightedNodes.push(new es.Vector2(3, 3));
graph.weightedNodes.push(new es.Vector2(3, 4));
graph.weightedNodes.push(new es.Vector2(4, 3));
graph.weightedNodes.push(new es.Vector2(4, 4));
let path = graph.search(new es.Vector2(3, 4), new es.Vector2(15, 17));
console.log(path);
}
public astarTest() {
let graph = new es.AstarGridGraph(30, 30);
// graph.weightedNodes.push(new Vector2(3, 3));
// graph.weightedNodes.push(new Vector2(3, 4));
// graph.weightedNodes.push(new Vector2(4, 3));
// graph.weightedNodes.push(new Vector2(4, 4));
let startTime = egret.getTimer();
let path = graph.search(new es.Vector2(1, 1), new es.Vector2(29, 29));
console.log(egret.getTimer() - startTime);
}
}
public breadthfirstTest() {
let graph = new UnweightedGraph<string>();
graph.addEdgesForNode("a", ["b"]); // a->b
graph.addEdgesForNode("b", ["a", "c", "d"]); // b->a b->c b->d
graph.addEdgesForNode("c", ["a"]); // c->a
graph.addEdgesForNode("d", ["e", "a"]); // d->e d->a
graph.addEdgesForNode("e", ["b"]); // e->b
// 计算从c到e的路径
let path = BreadthFirstPathfinder.search(graph, "c", "e");
console.log(path);
}
public dijkstraTest() {
let graph = new WeightedGridGraph(20, 20);
graph.weightedNodes.push(new Vector2(3, 3));
graph.weightedNodes.push(new Vector2(3, 4));
graph.weightedNodes.push(new Vector2(4, 3));
graph.weightedNodes.push(new Vector2(4, 4));
let path = graph.search(new Vector2(3, 4), new Vector2(15, 17));
console.log(path);
}
public astarTest() {
let graph = new AstarGridGraph(20, 20);
graph.weightedNodes.push(new Vector2(3, 3));
graph.weightedNodes.push(new Vector2(3, 4));
graph.weightedNodes.push(new Vector2(4, 3));
graph.weightedNodes.push(new Vector2(4, 4));
let path = graph.search(new Vector2(3, 4), new Vector2(15, 17));
console.log(path);
}
}
}
+55 -45
View File
@@ -1,56 +1,66 @@
class PlayerController extends Component {
private down: boolean = false;
private touchPoint: Vector2 = Vector2.zero;
private mover: Mover;
private spriteRenderer: SpriteRenderer;
module component {
import Component = es.Component;
import Vector2 = es.Vector2;
import Mover = es.Mover;
import SpriteRenderer = es.SpriteRenderer;
import Time = es.Time;
import Input = es.Input;
import CollisionResult = es.CollisionResult;
public onAddedToEntity(){
this.entity.scene.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegin, this);
this.entity.scene.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchBegin, this);
this.entity.scene.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.touchEnd, this);
}
export class PlayerController extends Component {
private down: boolean = false;
private touchPoint: Vector2 = Vector2.zero;
private mover: Mover;
private spriteRenderer: SpriteRenderer;
private touchBegin(evt: egret.TouchEvent){
this.down = true;
this.touchPoint = new Vector2(evt.stageX, evt.stageY);
}
public onAddedToEntity(){
this.entity.scene.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegin, this);
this.entity.scene.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchBegin, this);
this.entity.scene.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.touchEnd, this);
}
private touchEnd(evt: egret.TouchEvent){
this.down = false;
this.touchPoint = new Vector2(evt.stageX, evt.stageY);
}
private touchBegin(evt: egret.TouchEvent){
this.down = true;
this.touchPoint = new Vector2(evt.stageX, evt.stageY);
}
public update(){
if (!this.mover)
this.mover = this.entity.getComponent<Mover>(Mover);
private touchEnd(evt: egret.TouchEvent){
this.down = false;
this.touchPoint = new Vector2(evt.stageX, evt.stageY);
}
if (!this.spriteRenderer)
this.spriteRenderer = this.entity.getComponent<SpriteRenderer>(SpriteRenderer);
public update(){
if (!this.mover)
this.mover = this.entity.getComponent<Mover>(Mover);
if (!this.mover)
return;
if (!this.spriteRenderer)
this.spriteRenderer = this.entity.getComponent<SpriteRenderer>(SpriteRenderer);
if (!SpriteRenderer)
return;
if (!this.mover)
return;
if (this.down){
// let camera = SceneManager.scene.camera;
// let moveLeft: number = 0;
// let moveRight: number = 0;
// let speed = 100;
// let worldPos = Input.touchPosition;
// if (worldPos.x < this.spriteRenderer.x){
// moveLeft = -1;
// } else if(worldPos.x > this.spriteRenderer.x){
// moveLeft = 1;
// }
if (!SpriteRenderer)
return;
// if (worldPos.y < this.spriteRenderer.y){
// moveRight = -1;
// } else if(worldPos.y > this.spriteRenderer.y){
// moveRight = 1;
// }
this.mover.move(new Vector2(-1, -1));
if (this.down){
let moveLeft: number = 0;
let moveRight: number = 0;
let speed = 100;
let worldPos = this.entity.scene.camera.mouseToWorldPoint();
if (worldPos.x < this.spriteRenderer.transform.position.x){
moveLeft = -1;
} else if(worldPos.x > this.spriteRenderer.transform.position.x){
moveLeft = 1;
}
if (worldPos.y < this.spriteRenderer.transform.position.y){
moveRight = -1;
} else if(worldPos.y > this.spriteRenderer.transform.position.y){
moveRight = 1;
}
let collisionResult = new CollisionResult();
this.mover.move(new Vector2(moveLeft * speed * Time.deltaTime, moveRight * speed * Time.deltaTime), collisionResult);
}
}
}
}
}
+8 -4
View File
@@ -1,5 +1,9 @@
class SimplePooled extends PooledComponent {
public reset(){
module component {
import PooledComponent = es.PooledComponent;
export class SimplePooled extends PooledComponent {
public reset(){
}
}
}
}
+32 -30
View File
@@ -1,35 +1,37 @@
class SpawnComponent extends Component implements ITriggerListener {
public cooldown = -1;
public minInterval = 2;
public maxInterval = 60;
public enemyType = EnemyType.worm;
public numSpawned = 0;
public numAlive = 0;
module component {
export class SpawnComponent extends es.Component implements es.ITriggerListener {
public cooldown = -1;
public minInterval = 2;
public maxInterval = 60;
public enemyType = EnemyType.worm;
public numSpawned = 0;
public numAlive = 0;
constructor(enemyType: EnemyType) {
super();
this.enemyType = enemyType;
constructor(enemyType: EnemyType) {
super();
this.enemyType = enemyType;
}
public initialize() {
// console.log("initialize");
}
public update() {
// console.log("update");
}
public onTriggerEnter(other: es.Collider, local: es.Collider){
if (other == local)
console.log("repeat collider");
console.log("enter collider");
}
public onTriggerExit(other: es.Collider, local: es.Collider){
console.log("exit collider");
}
}
public initialize() {
// console.log("initialize");
}
public update() {
// console.log("update");
}
public onTriggerEnter(other: Collider, local: Collider){
if (other == local)
console.log("repeat collider")
console.log("enter collider");
}
public onTriggerExit(other: Collider, local: Collider){
console.log("exit collider");
export enum EnemyType {
worm
}
}
enum EnemyType {
worm
}
+31 -29
View File
@@ -1,34 +1,36 @@
class SpawnerSystem extends EntityProcessingSystem {
constructor(matcher: Matcher){
super(matcher);
}
public processEntity(entity: Entity){
let spawner = entity.getComponent<SpawnComponent>(SpawnComponent);
if (!spawner)
return;
if (spawner.numAlive <= 0)
spawner.enabled = true;
if (!spawner.enabled)
return;
console.log("cooldown", spawner.cooldown);
if (spawner.cooldown == -1){
spawner.cooldown = Math.random() * 60;
spawner.cooldown /= 4;
module system {
export class SpawnerSystem extends es.EntityProcessingSystem {
constructor(matcher: es.Matcher){
super(matcher);
}
spawner.cooldown -= Time.deltaTime;
if (spawner.cooldown <= 0){
spawner.cooldown = Math.random() * 60;
// CreateEnemy
spawner.numSpawned ++;
spawner.numAlive ++;
public processEntity(entity: es.Entity){
let spawner = entity.getComponent<component.SpawnComponent>(component.SpawnComponent);
if (!spawner)
return;
if (spawner.numAlive > 0)
spawner.enabled = false;
if (spawner.numAlive <= 0)
spawner.enabled = true;
if (!spawner.enabled)
return;
console.log("cooldown", spawner.cooldown);
if (spawner.cooldown == -1){
spawner.cooldown = Math.random() * 60;
spawner.cooldown /= 4;
}
spawner.cooldown -= es.Time.deltaTime;
if (spawner.cooldown <= 0){
spawner.cooldown = Math.random() * 60;
// CreateEnemy
spawner.numSpawned ++;
spawner.numAlive ++;
if (spawner.numAlive > 0)
spawner.enabled = false;
}
}
}
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ egret_native.egretStart = function () {
//The following is automatically modified, please do not modify
//----auto option start----
entryClassName: "Main",
frameRate: 30,
frameRate: 60,
scaleMode: "fixedWidth",
contentWidth: 640,
contentHeight: 1136,
+1
View File
@@ -2,6 +2,7 @@
"compilerOptions": {
"target": "es5",
"outDir": "bin-debug",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"lib": [
+11 -11
View File
@@ -1,13 +1,13 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "gulp",
"task": "build",
"group": "build",
"problemMatcher": []
}
]
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "gulp",
"task": "build",
"group": "build",
"problemMatcher": []
}
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"typescript.tsdk": "./node_modules/typescript/lib"
}
+1833 -1043
View File
File diff suppressed because it is too large Load Diff
+8253 -4571
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
+3 -3
View File
@@ -8,10 +8,10 @@ const tsProject = ts.createProject('tsconfig.json');
gulp.task('buildJs', () => {
return tsProject.src()
.pipe(tsProject())
.js.pipe(inject.replace('var framework;', ''))
.pipe(inject.prepend('window.framework = {};\n'))
.js.pipe(inject.replace('var es;', ''))
.pipe(inject.prepend('window.es = {};\n'))
.pipe(inject.replace('var __extends =', 'window.__extends ='))
.pipe(minify({ ext: { min: ".min.js" } }))
.pipe(minify({ext: {min: ".min.js"}}))
.pipe(gulp.dest('./bin'));
});
+3945
View File
File diff suppressed because it is too large Load Diff
@@ -1,89 +1,103 @@
///<reference path="./PriorityQueueNode.ts" />
/**
* IAstarGraph和开始/
*/
class AStarPathfinder {
public static search<T>(graph: IAstarGraph<T>, start: T, goal: T){
let foundPath = false;
let cameFrom = new Map<T, T>();
cameFrom.set(start, start);
module es {
/**
* IAstarGraph和开始/
*/
export class AStarPathfinder {
/**
* null
* @param graph
* @param start
* @param goal
*/
public static search<T>(graph: IAstarGraph<T>, start: T, goal: T) {
let foundPath = false;
let cameFrom = new Map<T, T>();
cameFrom.set(start, start);
let costSoFar = new Map<T, number>();
let frontier = new PriorityQueue<AStarNode<T>>(1000);
frontier.enqueue(new AStarNode<T>(start), 0);
let costSoFar = new Map<T, number>();
let frontier = new PriorityQueue<AStarNode<T>>(1000);
frontier.enqueue(new AStarNode<T>(start), 0);
costSoFar.set(start, 0);
costSoFar.set(start, 0);
while (frontier.count > 0){
let current = frontier.dequeue();
while (frontier.count > 0) {
let current = frontier.dequeue();
if (JSON.stringify(current.data) == JSON.stringify(goal)){
foundPath = true;
break;
if (JSON.stringify(current.data) == JSON.stringify(goal)) {
foundPath = true;
break;
}
graph.getNeighbors(current.data).forEach(next => {
let newCost = costSoFar.get(current.data) + graph.cost(current.data, next);
if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) {
costSoFar.set(next, newCost);
let priority = newCost + graph.heuristic(next, goal);
frontier.enqueue(new AStarNode<T>(next), priority);
cameFrom.set(next, current.data);
}
});
}
graph.getNeighbors(current.data).forEach(next => {
let newCost = costSoFar.get(current.data) + graph.cost(current.data, next);
if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){
costSoFar.set(next, newCost);
let priority = newCost + graph.heuristic(next, goal);
frontier.enqueue(new AStarNode<T>(next), priority);
cameFrom.set(next, current.data);
}
});
return foundPath ? this.recontructPath(cameFrom, start, goal) : null;
}
return foundPath ? this.recontructPath(cameFrom, start, goal) : 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;
}
private static hasKey<T>(map: Map<T, number>, compareKey: T) {
let iterator = map.keys();
let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return true;
}
return false;
}
private static getKey<T>(map: Map<T, T>, compareKey: T) {
let iterator = map.keys();
let valueIterator = map.values();
let r: IteratorResult<T>;
let v: IteratorResult<T>;
while (r = iterator.next(), v = valueIterator.next(), !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return v.value;
}
return null;
}
}
private static hasKey<T>(map: Map<T, number>, compareKey: T){
let iterator = map.keys();
let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return true;
/**
* 使PriorityQueue需要的额外字段将原始数据封装在一个小类中
*/
export class AStarNode<T> extends PriorityQueueNode {
public data: T;
constructor(data: T) {
super();
this.data = data;
}
return false;
}
private static getKey<T>(map: Map<T, T>, compareKey: T){
let iterator = map.keys();
let valueIterator = map.values();
let r: IteratorResult<T>;
let v: IteratorResult<T>;
while (r = iterator.next(), v = valueIterator.next(), !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return v.value;
}
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;
}
}
/**
* 使PriorityQueue需要的额外字段将原始数据封装在一个小类中
*/
class AStarNode<T> extends PriorityQueueNode {
public data: T;
constructor(data: T){
super();
this.data = data;
}
}
@@ -1,67 +1,74 @@
/**
* A*使
* walls添加到walls HashSetweightedNodes
*/
class AstarGridGraph implements IAstarGraph<Vector2> {
public dirs: Vector2[] = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, 1)
];
public walls: Vector2[] = [];
public weightedNodes: Vector2[] = [];
public defaultWeight: number = 1;
public weightedNodeWeight = 5;
private _width;
private _height;
private _neighbors: Vector2[] = new Array(4);
constructor(width: number, height: number){
this._width = width;
this._height = height;
}
module es {
/**
*
* @param node
* A*使
* walls添加到walls HashSetweightedNodes
*/
public isNodeInBounds(node: Vector2): boolean {
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height;
export class AstarGridGraph implements IAstarGraph<Vector2> {
public dirs: Vector2[] = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, 1)
];
public walls: Vector2[] = [];
public weightedNodes: Vector2[] = [];
public defaultWeight: number = 1;
public weightedNodeWeight = 5;
private _width;
private _height;
private _neighbors: Vector2[] = new Array(4);
constructor(width: number, height: number) {
this._width = width;
this._height = height;
}
/**
*
* @param node
*/
public isNodeInBounds(node: Vector2): boolean {
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height;
}
/**
* walls是不可逾越的
* @param node
*/
public isNodePassable(node: Vector2): boolean {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
/**
* AStarPathfinder.search的快捷方式
* @param start
* @param goal
*/
public search(start: Vector2, goal: Vector2) {
return AStarPathfinder.search(this, start, goal);
}
public getNeighbors(node: Vector2): Vector2[] {
this._neighbors.length = 0;
this.dirs.forEach(dir => {
let next = new Vector2(node.x + dir.x, node.y + dir.y);
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
public cost(from: Vector2, to: Vector2): number {
return this.weightedNodes.find((p) => JSON.stringify(p) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight;
}
public heuristic(node: Vector2, goal: Vector2) {
return Math.abs(node.x - goal.x) + Math.abs(node.y - goal.y);
}
}
/**
*
* @param node
*/
public isNodePassable(node: Vector2): boolean {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
public search(start: Vector2, goal: Vector2){
return AStarPathfinder.search(this, start, goal);
}
public getNeighbors(node: Vector2): Vector2[] {
this._neighbors.length = 0;
this.dirs.forEach(dir => {
let next = new Vector2(node.x + dir.x, node.y + dir.y);
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
public cost(from: Vector2, to: Vector2): number {
return this.weightedNodes.find((p)=> JSON.stringify(p) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight;
}
public heuristic(node: Vector2, goal: Vector2) {
return Math.abs(node.x - goal.x) + Math.abs(node.y - goal.y);
}
}
}
+26 -5
View File
@@ -1,5 +1,26 @@
interface IAstarGraph<T> {
getNeighbors(node: T): Array<T>;
cost(from: T, to: T): number;
heuristic(node: T, goal: T);
}
module es {
/**
* graph的接口AstarPathfinder.search方法
*/
export interface IAstarGraph<T> {
/**
* getNeighbors方法应该返回从传入的节点可以到达的任何相邻节点
* @param node
*/
getNeighbors(node: T): Array<T>;
/**
* from到to的成本
* @param from
* @param to
*/
cost(from: T, to: T): number;
/**
* node到to的启发式WeightedGridGraph了解常用的Manhatten方法
* @param node
* @param goal
*/
heuristic(node: T, goal: T);
}
}
+213 -127
View File
@@ -1,150 +1,236 @@
class PriorityQueue<T extends PriorityQueueNode> {
private _numNodes: number;
private _nodes: T[];
private _numNodesEverEnqueued;
module es {
/**
* 使 O(1)
* 使5-10
* IPriorityQueue.contains()
*/
export class PriorityQueue<T extends PriorityQueueNode> {
private _numNodes: number;
private _nodes: T[];
private _numNodesEverEnqueued;
constructor(maxNodes: number) {
this._numNodes = 0;
this._nodes = new Array(maxNodes + 1);
this._numNodesEverEnqueued = 0;
}
/**
*
* @param maxNodes (undefined的行为)
*/
constructor(maxNodes: number) {
this._numNodes = 0;
this._nodes = new Array(maxNodes + 1);
this._numNodesEverEnqueued = 0;
}
public clear() {
this._nodes.splice(1, this._numNodes);
this._numNodes = 0;
}
/**
*
* O(1)
*/
public get count() {
return this._numNodes;
}
public get count() {
return this._numNodes;
}
/**
* (Count == MaxSize)undefined的行为
* O(1)
*/
public get maxSize() {
return this._nodes.length - 1;
}
public contains(node: T): boolean {
return (this._nodes[node.queueIndex] == node);
}
/**
*
* O(n)
*/
public clear() {
this._nodes.splice(1, this._numNodes);
this._numNodes = 0;
}
public enqueue(node: T, priority: number) {
node.priority = priority;
this._numNodes++;
this._nodes[this._numNodes] = node;
node.queueIndex = this._numNodes;
node.insertionIndex = this._numNodesEverEnqueued++;
this.cascadeUp(this._nodes[this._numNodes]);
}
/**
* (O(1))
* O (1)
* @param node
*/
public contains(node: T): boolean {
if (!node) {
console.error("node cannot be null");
return false;
}
public dequeue(): T {
let returnMe = this._nodes[1];
this.remove(returnMe);
return returnMe;
}
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?");
return false;
}
public remove(node: T) {
if (node.queueIndex == this._numNodes) {
this._nodes[this._numNodes] = null;
return (this._nodes[node.queueIndex] == node);
}
/**
*
* undefinedundefined
* O(log n)
* @param node
* @param priority
*/
public enqueue(node: T, priority: number) {
node.priority = priority;
this._numNodes++;
this._nodes[this._numNodes] = node;
node.queueIndex = this._numNodes;
node.insertionIndex = this._numNodesEverEnqueued++;
this.cascadeUp(this._nodes[this._numNodes]);
}
/**
* (;)undefined
* O(log n)
*/
public dequeue(): T {
let returnMe = this._nodes[1];
this.remove(returnMe);
return returnMe;
}
/**
* Contains()
* O(log n)
* @param node
*/
public remove(node: T) {
if (node.queueIndex == this._numNodes) {
this._nodes[this._numNodes] = null;
this._numNodes--;
return;
}
let formerLastNode = this._nodes[this._numNodes];
this.swap(node, formerLastNode);
delete this._nodes[this._numNodes];
this._numNodes--;
return;
this.onNodeUpdated(formerLastNode);
}
let formerLastNode = this._nodes[this._numNodes];
this.swap(node, formerLastNode);
delete this._nodes[this._numNodes];
this._numNodes--;
/**
* /
*/
public isValidQueue(): boolean {
for (let i = 1; i < this._nodes.length; i++) {
if (this._nodes[i]) {
let childLeftIndex = 2 * i;
if (childLeftIndex < this._nodes.length && this._nodes[childLeftIndex] &&
this.hasHigherPriority(this._nodes[childLeftIndex], this._nodes[i]))
return false;
this.onNodeUpdated(formerLastNode);
}
public isValidQueue(): boolean {
for (let i = 1; i < this._nodes.length; i++) {
if (this._nodes[i]) {
let childLeftIndex = 2 * i;
if (childLeftIndex < this._nodes.length && this._nodes[childLeftIndex] &&
this.hasHigherPriority(this._nodes[childLeftIndex], this._nodes[i]))
return false;
let childRightIndex = childLeftIndex + 1;
if (childRightIndex < this._nodes.length && this._nodes[childRightIndex] &&
this.hasHigherPriority(this._nodes[childRightIndex], this._nodes[i]))
return false;
}
}
return true;
}
private onNodeUpdated(node: T) {
let parentIndex = Math.floor(node.queueIndex / 2);
let parentNode = this._nodes[parentIndex];
if (parentIndex > 0 && this.hasHigherPriority(node, parentNode)) {
this.cascadeUp(node);
} else {
this.cascadeDown(node);
}
}
private cascadeDown(node: T) {
let newParent: T;
let finalQueueIndex = node.queueIndex;
while (true) {
newParent = node;
let childLeftIndex = 2 * finalQueueIndex;
if (childLeftIndex > this._numNodes) {
node.queueIndex = finalQueueIndex;
this._nodes[finalQueueIndex] = node;
break;
}
let childLeft = this._nodes[childLeftIndex];
if (this.hasHigherPriority(childLeft, newParent)) {
newParent = childLeft;
}
let childRightIndex = childLeftIndex + 1;
if (childRightIndex <= this._numNodes) {
let childRight = this._nodes[childRightIndex];
if (this.hasHigherPriority(childRight, newParent)) {
newParent = childRight;
let childRightIndex = childLeftIndex + 1;
if (childRightIndex < this._nodes.length && this._nodes[childRightIndex] &&
this.hasHigherPriority(this._nodes[childRightIndex], this._nodes[i]))
return false;
}
}
if (newParent != node) {
this._nodes[finalQueueIndex] = newParent;
return true;
}
let temp = newParent.queueIndex;
newParent.queueIndex = finalQueueIndex;
finalQueueIndex = temp;
private onNodeUpdated(node: T) {
// 将更新后的节点按适当的方式向上或向下冒泡
let parentIndex = Math.floor(node.queueIndex / 2);
let parentNode = this._nodes[parentIndex];
if (parentIndex > 0 && this.hasHigherPriority(node, parentNode)) {
this.cascadeUp(node);
} else {
node.queueIndex = finalQueueIndex;
this._nodes[finalQueueIndex] = node;
break;
// 注意,如果parentNode == node(即节点是根),则将调用CascadeDown。
this.cascadeDown(node);
}
}
}
private cascadeUp(node: T) {
let parent = Math.floor(node.queueIndex / 2);
while (parent >= 1) {
let parentNode = this._nodes[parent];
if (this.hasHigherPriority(parentNode, node))
break;
private cascadeDown(node: T) {
// 又名Heapify-down
let newParent: T;
let finalQueueIndex = node.queueIndex;
while (true) {
newParent = node;
let childLeftIndex = 2 * finalQueueIndex;
this.swap(node, parentNode);
// 检查左子节点的优先级是否高于当前节点
if (childLeftIndex > this._numNodes) {
// 这可以放在循环之外,但是我们必须检查newParent != node两次
node.queueIndex = finalQueueIndex;
this._nodes[finalQueueIndex] = node;
break;
}
parent = Math.floor(node.queueIndex / 2);
let childLeft = this._nodes[childLeftIndex];
if (this.hasHigherPriority(childLeft, newParent)) {
newParent = childLeft;
}
// 检查右子节点的优先级是否高于当前节点或左子节点
let childRightIndex = childLeftIndex + 1;
if (childRightIndex <= this._numNodes) {
let childRight = this._nodes[childRightIndex];
if (this.hasHigherPriority(childRight, newParent)) {
newParent = childRight;
}
}
// 如果其中一个子节点具有更高(更小)的优先级,则交换并继续级联
if (newParent != node) {
// 将新的父节点移动到它的新索引
// 节点将被移动一次,这样做比调用Swap()少一个赋值操作。
this._nodes[finalQueueIndex] = newParent;
let temp = newParent.queueIndex;
newParent.queueIndex = finalQueueIndex;
finalQueueIndex = temp;
} else {
// 参见上面的笔记
node.queueIndex = finalQueueIndex;
this._nodes[finalQueueIndex] = node;
break;
}
}
}
/**
*
* @param node
*/
private cascadeUp(node: T) {
// 又名Heapify-up
let parent = Math.floor(node.queueIndex / 2);
while (parent >= 1) {
let parentNode = this._nodes[parent];
if (this.hasHigherPriority(parentNode, node))
break;
// 节点具有较低的优先级值,因此将其向上移动到堆中
// 出于某种原因,使用Swap()比使用单独的操作更快,如CascadeDown()
this.swap(node, parentNode);
parent = Math.floor(node.queueIndex / 2);
}
}
private swap(node1: T, node2: T) {
// 交换节点
this._nodes[node1.queueIndex] = node2;
this._nodes[node2.queueIndex] = node1;
// 交换他们的indicies
let temp = node1.queueIndex;
node1.queueIndex = node2.queueIndex;
node2.queueIndex = temp;
}
/**
* higher的优先级高于lowertruefalse
* HasHigherPriority()()false
* @param higher
* @param lower
*/
private hasHigherPriority(higher: T, lower: T) {
return (higher.priority < lower.priority ||
(higher.priority == lower.priority && higher.insertionIndex < lower.insertionIndex));
}
}
private swap(node1: T, node2: T) {
this._nodes[node1.queueIndex] = node2;
this._nodes[node2.queueIndex] = node1;
let temp = node1.queueIndex;
node1.queueIndex = node2.queueIndex;
node2.queueIndex = temp;
}
private hasHigherPriority(higher: T, lower: T) {
return (higher.priority < lower.priority ||
(higher.priority == lower.priority && higher.insertionIndex < lower.insertionIndex));
}
}
}
@@ -1,14 +1,16 @@
class PriorityQueueNode {
/**
*
*/
public priority: number = 0;
/**
* 使-
*/
public insertionIndex: number = 0;
/**
* 使-
*/
public queueIndex: number = 0;
}
module es {
export class PriorityQueueNode {
/**
*
*/
public priority: number = 0;
/**
* 使-
*/
public insertionIndex: number = 0;
/**
* 使-
*/
public queueIndex: number = 0;
}
}
@@ -1,41 +1,43 @@
/**
* IUnweightedGraph和开始/
*/
class BreadthFirstPathfinder {
public static search<T>(graph: IUnweightedGraph<T>, start: T, goal: T): T[]{
let foundPath = false;
let frontier = [];
frontier.unshift(start);
module es {
/**
* IUnweightedGraph和开始/
*/
export class BreadthFirstPathfinder {
public static search<T>(graph: IUnweightedGraph<T>, start: T, goal: T): T[] {
let foundPath = false;
let frontier = [];
frontier.unshift(start);
let cameFrom = new Map<T, T>();
cameFrom.set(start, start);
let cameFrom = new Map<T, T>();
cameFrom.set(start, start);
while (frontier.length > 0){
let current = frontier.shift();
if (JSON.stringify(current) == JSON.stringify(goal)){
foundPath = true;
break;
while (frontier.length > 0) {
let current = frontier.shift();
if (JSON.stringify(current) == JSON.stringify(goal)) {
foundPath = true;
break;
}
graph.getNeighbors(current).forEach(next => {
if (!this.hasKey(cameFrom, next)) {
frontier.unshift(next);
cameFrom.set(next, current);
}
});
}
graph.getNeighbors(current).forEach(next => {
if (!this.hasKey(cameFrom, next)){
frontier.unshift(next);
cameFrom.set(next, current);
}
});
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) {
let iterator = map.keys();
let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return true;
}
private static hasKey<T>(map: Map<T, T>, compareKey: T){
let iterator = map.keys();
let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return true;
return false;
}
return false;
}
}
}
@@ -1,7 +1,9 @@
interface IUnweightedGraph<T>{
/**
* getNeighbors方法应该返回从传入的节点可以到达的任何相邻节点
* @param node
*/
getNeighbors(node: T): T[];
}
module es {
export interface IUnweightedGraph<T> {
/**
* getNeighbors方法应该返回从传入的节点可以到达的任何相邻节点
* @param node
*/
getNeighbors(node: T): T[];
}
}
@@ -1,16 +1,18 @@
/**
*
*
*/
class UnweightedGraph<T> implements IUnweightedGraph<T> {
public edges: Map<T, T[]> = new Map<T, T[]>();
module es {
/**
*
*
*/
export class UnweightedGraph<T> implements IUnweightedGraph<T> {
public edges: Map<T, T[]> = new Map<T, T[]>();
public addEdgesForNode(node: T, edges: T[]){
this.edges.set(node, edges);
return this;
}
public addEdgesForNode(node: T, edges: T[]) {
this.edges.set(node, edges);
return this;
}
public getNeighbors(node: T){
return this.edges.get(node);
public getNeighbors(node: T) {
return this.edges.get(node);
}
}
}
}
@@ -1,61 +1,63 @@
///<reference path="../../../Math/Vector2.ts" />
/**
* BreadthFirstPathfinder
*/
class UnweightedGridGraph implements IUnweightedGraph<Vector2> {
private static readonly CARDINAL_DIRS: Vector2[] = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, -1)
];
module es {
/**
* BreadthFirstPathfinder
*/
export class UnweightedGridGraph implements IUnweightedGraph<Vector2> {
private static readonly CARDINAL_DIRS: Vector2[] = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, -1)
];
private static readonly COMPASS_DIRS = [
new Vector2(1, 0),
new Vector2(1, -1),
new Vector2(0, -1),
new Vector2(-1, -1),
new Vector2(-1, 0),
new Vector2(-1, 1),
new Vector2(0, 1),
new Vector2(1, 1),
];
private static readonly COMPASS_DIRS = [
new Vector2(1, 0),
new Vector2(1, -1),
new Vector2(0, -1),
new Vector2(-1, -1),
new Vector2(-1, 0),
new Vector2(-1, 1),
new Vector2(0, 1),
new Vector2(1, 1),
];
public walls: Vector2[] = [];
public walls: Vector2[] = [];
private _width: number;
private _hegiht: number;
private _width: number;
private _hegiht: number;
private _dirs: Vector2[];
private _neighbors: Vector2[] = new Array(4);
private _dirs: Vector2[];
private _neighbors: Vector2[] = new Array(4);
constructor(width: number, height: number, allowDiagonalSearch: boolean = false) {
this._width = width;
this._hegiht = height;
this._dirs = allowDiagonalSearch ? UnweightedGridGraph.COMPASS_DIRS : UnweightedGridGraph.CARDINAL_DIRS;
constructor(width: number, height: number, allowDiagonalSearch: boolean = false) {
this._width = width;
this._hegiht = height;
this._dirs = allowDiagonalSearch ? UnweightedGridGraph.COMPASS_DIRS : UnweightedGridGraph.CARDINAL_DIRS;
}
public isNodeInBounds(node: Vector2): boolean {
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._hegiht;
}
public isNodePassable(node: Vector2): boolean {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
public getNeighbors(node: Vector2) {
this._neighbors.length = 0;
this._dirs.forEach(dir => {
let next = new Vector2(node.x + dir.x, node.y + dir.y);
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
public search(start: Vector2, goal: Vector2): Vector2[] {
return BreadthFirstPathfinder.search(this, start, goal);
}
}
public isNodeInBounds(node: Vector2): boolean {
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._hegiht;
}
public isNodePassable(node: Vector2): boolean {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
public getNeighbors(node: Vector2) {
this._neighbors.length = 0;
this._dirs.forEach(dir => {
let next = new Vector2(node.x + dir.x, node.y + dir.y);
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
public search(start: Vector2, goal: Vector2): Vector2[] {
return BreadthFirstPathfinder.search(this, start, goal);
}
}
}
@@ -1,14 +1,16 @@
interface IWeightedGraph<T>{
/**
*
* @param node
*/
getNeighbors(node: T): T[];
module es {
export interface IWeightedGraph<T> {
/**
*
* @param node
*/
getNeighbors(node: T): T[];
/**
*
* @param from
* @param to
*/
cost(from: T, to: T): number;
}
/**
*
* @param from
* @param to
*/
cost(from: T, to: T): number;
}
}
@@ -1,67 +1,69 @@
///<reference path="../../../Math/Vector2.ts" />
/**
*
*/
class WeightedGridGraph implements IWeightedGraph<Vector2> {
public static readonly CARDINAL_DIRS = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, 1)
];
module es {
/**
*
*/
export class WeightedGridGraph implements IWeightedGraph<Vector2> {
public static readonly CARDINAL_DIRS = [
new Vector2(1, 0),
new Vector2(0, -1),
new Vector2(-1, 0),
new Vector2(0, 1)
];
private static readonly COMPASS_DIRS = [
new Vector2(1, 0),
new Vector2(1, -1),
new Vector2(0, -1),
new Vector2(-1, -1),
new Vector2(-1, 0),
new Vector2(-1, 1),
new Vector2(0, 1),
new Vector2(1, 1),
];
private static readonly COMPASS_DIRS = [
new Vector2(1, 0),
new Vector2(1, -1),
new Vector2(0, -1),
new Vector2(-1, -1),
new Vector2(-1, 0),
new Vector2(-1, 1),
new Vector2(0, 1),
new Vector2(1, 1),
];
public walls: Vector2[] = [];
public weightedNodes: Vector2[] = [];
public defaultWeight = 1;
public weightedNodeWeight = 5;
public walls: Vector2[] = [];
public weightedNodes: Vector2[] = [];
public defaultWeight = 1;
public weightedNodeWeight = 5;
private _width: number;
private _height: number;
private _dirs: Vector2[];
private _neighbors: Vector2[] = new Array(4);
private _width: number;
private _height: number;
private _dirs: Vector2[];
private _neighbors: Vector2[] = new Array(4);
constructor(width: number, height: number, allowDiagonalSearch: boolean = false){
this._width = width;
this._height = height;
this._dirs = allowDiagonalSearch ? WeightedGridGraph.COMPASS_DIRS : WeightedGridGraph.CARDINAL_DIRS;
constructor(width: number, height: number, allowDiagonalSearch: boolean = false) {
this._width = width;
this._height = height;
this._dirs = allowDiagonalSearch ? WeightedGridGraph.COMPASS_DIRS : WeightedGridGraph.CARDINAL_DIRS;
}
public isNodeInBounds(node: Vector2) {
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height;
}
public isNodePassable(node: Vector2): boolean {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
public search(start: Vector2, goal: Vector2) {
return WeightedPathfinder.search(this, start, goal);
}
public getNeighbors(node: Vector2): Vector2[] {
this._neighbors.length = 0;
this._dirs.forEach(dir => {
let next = new Vector2(node.x + dir.x, node.y + dir.y);
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
public cost(from: Vector2, to: Vector2): number {
return this.weightedNodes.find(t => JSON.stringify(t) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight;
}
}
public isNodeInBounds(node: Vector2){
return 0 <= node.x && node.x < this._width && 0 <= node.y && node.y < this._height;
}
public isNodePassable(node: Vector2): boolean {
return !this.walls.firstOrDefault(wall => JSON.stringify(wall) == JSON.stringify(node));
}
public search(start: Vector2, goal: Vector2){
return WeightedPathfinder.search(this, start, goal);
}
public getNeighbors(node: Vector2): Vector2[]{
this._neighbors.length = 0;
this._dirs.forEach(dir => {
let next = new Vector2(node.x + dir.x, node.y + dir.y);
if (this.isNodeInBounds(next) && this.isNodePassable(next))
this._neighbors.push(next);
});
return this._neighbors;
}
public cost(from: Vector2, to: Vector2): number{
return this.weightedNodes.find(t => JSON.stringify(t) == JSON.stringify(to)) ? this.weightedNodeWeight : this.defaultWeight;
}
}
}
@@ -1,83 +1,85 @@
class WeightedNode<T> extends PriorityQueueNode {
public data: T;
module es {
export class WeightedNode<T> extends PriorityQueueNode {
public data: T;
constructor(data: T){
super();
this.data = data;
constructor(data: T) {
super();
this.data = data;
}
}
}
class WeightedPathfinder {
public static search<T>(graph: IWeightedGraph<T>, start: T, goal: T){
let foundPath = false;
export class WeightedPathfinder {
public static search<T>(graph: IWeightedGraph<T>, start: T, goal: T) {
let foundPath = false;
let cameFrom = new Map<T, T>();
cameFrom.set(start, start);
let cameFrom = new Map<T, T>();
cameFrom.set(start, start);
let costSoFar = new Map<T, number>();
let frontier = new PriorityQueue<WeightedNode<T>>(1000);
frontier.enqueue(new WeightedNode<T>(start), 0);
let costSoFar = new Map<T, number>();
let frontier = new PriorityQueue<WeightedNode<T>>(1000);
frontier.enqueue(new WeightedNode<T>(start), 0);
costSoFar.set(start, 0);
costSoFar.set(start, 0);
while (frontier.count > 0){
let current = frontier.dequeue();
if (JSON.stringify(current.data) == JSON.stringify(goal)){
foundPath = true;
break;
while (frontier.count > 0) {
let current = frontier.dequeue();
if (JSON.stringify(current.data) == JSON.stringify(goal)) {
foundPath = true;
break;
}
graph.getNeighbors(current.data).forEach(next => {
let newCost = costSoFar.get(current.data) + graph.cost(current.data, next);
if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)) {
costSoFar.set(next, newCost);
let priprity = newCost;
frontier.enqueue(new WeightedNode<T>(next), priprity);
cameFrom.set(next, current.data);
}
});
}
graph.getNeighbors(current.data).forEach(next => {
let newCost = costSoFar.get(current.data) + graph.cost(current.data, next);
if (!this.hasKey(costSoFar, next) || newCost < costSoFar.get(next)){
costSoFar.set(next, newCost);
let priprity = newCost;
frontier.enqueue(new WeightedNode<T>(next), priprity);
cameFrom.set(next, current.data);
}
});
}
return foundPath ? this.recontructPath(cameFrom, start, goal) : null;
}
private static hasKey<T>(map: Map<T, number>, compareKey: T){
let iterator = map.keys();
let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return true;
return foundPath ? this.recontructPath(cameFrom, start, goal) : null;
}
return false;
}
public static recontructPath<T>(cameFrom: Map<T, T>, start: T, goal: T): T[] {
let path = [];
let current = goal;
path.push(goal);
private static getKey<T>(map: Map<T, T>, compareKey: T){
let iterator = map.keys();
let valueIterator = map.values();
let r: IteratorResult<T>;
let v: IteratorResult<T>;
while (r = iterator.next(), v = valueIterator.next(), !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return v.value;
while (current != start) {
current = this.getKey(cameFrom, current);
path.push(current);
}
path.reverse();
return path;
}
return null;
}
private static hasKey<T>(map: Map<T, number>, compareKey: T) {
let iterator = map.keys();
let r: IteratorResult<T>;
while (r = iterator.next() , !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return true;
}
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);
return false;
}
path.reverse();
private static getKey<T>(map: Map<T, T>, compareKey: T) {
let iterator = map.keys();
let valueIterator = map.values();
let r: IteratorResult<T>;
let v: IteratorResult<T>;
while (r = iterator.next(), v = valueIterator.next(), !r.done) {
if (JSON.stringify(r.value) == JSON.stringify(compareKey))
return v.value;
}
return path;
return null;
}
}
}
}
+24
View File
@@ -0,0 +1,24 @@
module es {
export class Debug {
private static _debugDrawItems: DebugDrawItem[] = [];
public static drawHollowRect(rectanle: Rectangle, color: number, duration = 0) {
this._debugDrawItems.push(new DebugDrawItem(rectanle, color, duration));
}
public static render() {
if (this._debugDrawItems.length > 0) {
let debugShape = new egret.Shape();
if (Core.scene) {
Core.scene.addChild(debugShape);
}
for (let i = this._debugDrawItems.length - 1; i >= 0; i--) {
let item = this._debugDrawItems[i];
if (item.draw(debugShape))
this._debugDrawItems.removeAt(i);
}
}
}
}
}
+6 -4
View File
@@ -1,4 +1,6 @@
class DebugDefaults {
public static verletParticle = 0xDC345E;
public static verletConstraintEdge = 0x433E36;
}
module es {
export class DebugDefaults {
public static verletParticle = 0xDC345E;
public static verletConstraintEdge = 0x433E36;
}
}
+49
View File
@@ -0,0 +1,49 @@
module es {
export enum DebugDrawType {
line,
hollowRectangle,
pixel,
text
}
export class DebugDrawItem {
public rectangle: Rectangle;
public color: number;
public duration: number;
public drawType: DebugDrawType;
public text: string;
public start: Vector2;
public end: Vector2;
public x: number;
public y: number;
public size: number;
constructor(rectangle: Rectangle, color: number, duration: number) {
this.rectangle = rectangle;
this.color = color;
this.duration = duration;
this.drawType = DebugDrawType.hollowRectangle;
}
public draw(shape: egret.Shape): boolean {
switch (this.drawType) {
case DebugDrawType.line:
DrawUtils.drawLine(shape, this.start, this.end, this.color);
break;
case DebugDrawType.hollowRectangle:
DrawUtils.drawHollowRect(shape, this.rectangle, this.color);
break;
case DebugDrawType.pixel:
DrawUtils.drawPixel(shape, new Vector2(this.x, this.y), this.color, this.size);
break;
case DebugDrawType.text:
break;
}
this.duration -= Time.deltaTime;
return this.duration < 0;
}
}
}
+133 -71
View File
@@ -1,75 +1,137 @@
abstract class Component extends egret.DisplayObjectContainer {
public entity: Entity;
private _enabled: boolean = true;
public updateInterval: number = 1;
/** 允许用户为实体存入信息 */
public userData: any;
module es {
/**
*
* - onAddedToEntity
* - OnEnabled
*
*
* - onRemovedFromEntity
*/
export abstract class Component extends egret.HashObject {
/**
*
*/
public entity: Entity;
/**
*
*/
public updateInterval: number = 1;
public get enabled(){
return this.entity ? this.entity.enabled && this._enabled : this._enabled;
}
public set enabled(value: boolean){
this.setEnabled(value);
}
public setEnabled(isEnabled: boolean){
if (this._enabled != isEnabled){
this._enabled = isEnabled;
if (this._enabled){
this.onEnabled();
}else{
this.onDisabled();
}
/**
* 访 this.entity.transform
*/
public get transform(): Transform {
return this.entity.transform;
}
return this;
private _enabled: boolean = true;
/**
* onEnabled/onDisable
*/
public get enabled() {
return this.entity ? this.entity.enabled && this._enabled : this._enabled;
}
/**
* onEnabled/onDisable
* @param value
*/
public set enabled(value: boolean) {
this.setEnabled(value);
}
private _updateOrder = 0;
/** 更新此实体上组件的顺序 */
public get updateOrder() {
return this._updateOrder;
}
/** 更新此实体上组件的顺序 */
public set updateOrder(value: number) {
this.setUpdateOrder(value);
}
/**
* 西访
*/
public initialize() {
}
/**
*
*/
public onAddedToEntity() {
}
/**
*
*/
public onRemovedFromEntity() {
}
/**
*
* @param comp
*/
public onEntityTransformChanged(comp: transform.Component) {
}
/**
*
*/
public debugRender() {
}
/**
*
*/
public onEnabled() {
}
/**
*
*/
public onDisabled() {
}
/**
*
*/
public update() {
}
public setEnabled(isEnabled: boolean) {
if (this._enabled != isEnabled) {
this._enabled = isEnabled;
if (this._enabled) {
this.onEnabled();
} else {
this.onDisabled();
}
}
return this;
}
public setUpdateOrder(updateOrder: number) {
if (this._updateOrder != updateOrder) {
this._updateOrder = updateOrder;
}
return this;
}
/**
*
*/
public clone(): Component {
let component = ObjectUtils.clone<Component>(this);
component.entity = null;
return component;
}
}
public initialize(){
}
public onAddedToEntity(){
}
public onRemovedFromEntity(){
}
public onEnabled(){
}
public onDisabled(){
}
public update(){
}
public debugRender(){
}
/**
*
* @param comp
*/
public onEntityTransformChanged(comp: TransformComponent){
}
/** 内部使用 运行时不应该调用 */
public registerComponent(){
this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this), false);
this.entity.scene.entityProcessors.onComponentAdded(this.entity);
}
public deregisterComponent(){
this.entity.componentBits.set(ComponentTypeManager.getIndexFor(this));
this.entity.scene.entityProcessors.onComponentRemoved(this.entity);
}
}
}
+460 -211
View File
@@ -1,235 +1,484 @@
///<reference path="../Component.ts"/>
class Camera extends Component {
private _zoom;
private _origin: Vector2 = Vector2.zero;
private _minimumZoom = 0.3;
private _maximumZoom = 3;
private _position: Vector2 = Vector2.zero;
/**
* cameraWindow
*
*/
public followLerp = 0.1;
public deadzone: Rectangle = new Rectangle();
/** 锁定偏移量 默认中心 */
public focusOffset: Vector2 = new Vector2();
/** 是否地图锁定 如果锁定则需要设置mapSize属性 */
public mapLockEnabled: boolean = false;
/** 设置地图大小 默认从0 0左上角开始 只需要输入地图宽高 */
public mapSize: Vector2 = new Vector2();
/** 跟随的实体 设置后镜头将锁定目标为中心 */
public targetEntity: Entity;
private _worldSpaceDeadZone: Rectangle = new Rectangle();
private _desiredPositionDelta: Vector2 = new Vector2();
private _targetCollider: Collider;
/** 相机模式 */
public cameraStyle: CameraStyle = CameraStyle.lockOn;
public get zoom(){
if (this._zoom == 0)
return 1;
if (this._zoom < 1)
return MathHelper.map(this._zoom, this._minimumZoom, 1, -1, 0);
return MathHelper.map(this._zoom, 1, this._maximumZoom, 0, 1);
module es {
export enum CameraStyle {
lockOn,
cameraWindow,
}
public set zoom(value: number){
this.setZoom(value);
export class CameraInset {
public left: number = 0;
public right: number = 0;
public top: number = 0;
public bottom: number = 0;
}
public get minimumZoom(){
return this._minimumZoom;
}
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();
public set minimumZoom(value: number){
this.setMinimumZoom(value);
}
constructor(targetEntity: Entity = null, cameraStyle: CameraStyle = CameraStyle.lockOn) {
super();
public get maximumZoom(){
return this._maximumZoom;
}
public set maximumZoom(value: number){
this.setMaximumZoom(value);
}
public get origin(){
return this._origin;
}
public set origin(value: Vector2){
if (this._origin != value){
this._origin = value;
}
}
public get position(){
return this._position;
}
public set position(value: Vector2){
this._position = value;
}
public get x(){
return this._position.x;
}
public set x(value: number){
this._position.x = value;
}
public get y(){
return this._position.y;
}
public set y(value: number){
this._position.y = value;
}
constructor() {
super();
this.width = SceneManager.stage.stageWidth;
this.height = SceneManager.stage.stageHeight;
this.setZoom(0);
}
public onSceneSizeChanged(newWidth: number, newHeight: number){
let oldOrigin = this._origin;
this.origin = new Vector2(newWidth / 2, newHeight / 2);
this.entity.position = Vector2.add(this.entity.position, Vector2.subtract(this._origin, oldOrigin));
}
public setMinimumZoom(minZoom: number): Camera{
if (this._zoom < minZoom)
this._zoom = this.minimumZoom;
this._minimumZoom = minZoom;
return this;
}
public setMaximumZoom(maxZoom: number): Camera {
if (this._zoom > maxZoom)
this._zoom = maxZoom;
this._maximumZoom = maxZoom;
return this;
}
public setZoom(zoom: number): Camera{
let newZoom = MathHelper.clamp(zoom, -1, 1);
if (newZoom == 0){
this._zoom = 1;
} else if(newZoom < 0){
this._zoom = MathHelper.map(newZoom, -1, 0, this._minimumZoom, 1);
} else {
this._zoom = MathHelper.map(newZoom, 0, 1, 1, this._maximumZoom);
this._targetEntity = targetEntity;
this._cameraStyle = cameraStyle;
this.setZoom(0);
}
SceneManager.scene.scaleX = this._zoom;
SceneManager.scene.scaleY = this._zoom;
return this;
}
public setRotation(rotation: number): Camera {
SceneManager.scene.rotation = rotation;
return this;
}
public setPosition(position: Vector2){
this.entity.position = position;
return this;
}
public follow(targetEntity: Entity, cameraStyle: CameraStyle = CameraStyle.cameraWindow){
this.targetEntity = targetEntity;
this.cameraStyle = cameraStyle;
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
switch (this.cameraStyle){
case CameraStyle.cameraWindow:
let w = cameraBounds.width / 6;
let h = cameraBounds.height / 3;
this.deadzone = new Rectangle((cameraBounds.width - w) / 2, (cameraBounds.height - h) / 2, w, h);
break;
case CameraStyle.lockOn:
this.deadzone = new Rectangle(cameraBounds.width / 2, cameraBounds.height / 2, 10, 10);
break;
/**
* entity.transform.position的快速访问
*/
public get position() {
return this.entity.transform.position;
}
}
public update(){
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
let halfScreen = Vector2.multiply(new Vector2(cameraBounds.width, cameraBounds.height), new Vector2(0.5));
this._worldSpaceDeadZone.x = this.position.x - halfScreen.x + this.deadzone.x + this.focusOffset.x;
this._worldSpaceDeadZone.y = this.position.y - halfScreen.y + this.deadzone.y + this.focusOffset.y;
this._worldSpaceDeadZone.width = this.deadzone.width;
this._worldSpaceDeadZone.height = this.deadzone.height;
if (this.targetEntity)
this.updateFollow();
this.position = Vector2.lerp(this.position, Vector2.add(this.position, this._desiredPositionDelta), this.followLerp);
this.entity.roundPosition();
if (this.mapLockEnabled){
this.position = this.clampToMapSize(this.position);
this.entity.roundPosition();
/**
* entity.transform.position的快速访问
* @param value
*/
public set position(value: Vector2) {
this.entity.transform.position = value;
}
}
private clampToMapSize(position: Vector2){
let cameraBounds = new Rectangle(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
let halfScreen = Vector2.multiply(new Vector2(cameraBounds.width, cameraBounds.height), new Vector2(0.5));
let cameraMax = new Vector2(this.mapSize.x - halfScreen.x, this.mapSize.y - halfScreen.y);
/**
* entity.transform.rotation的快速访问
*/
public get rotation(): number {
return this.entity.transform.rotation;
}
return Vector2.clamp(position, halfScreen, cameraMax);
}
/**
* entity.transform.rotation的快速访问
* @param value
*/
public set rotation(value: number) {
this.entity.transform.rotation = value;
}
private updateFollow(){
this._desiredPositionDelta.x = this._desiredPositionDelta.y = 0;
public _zoom;
if (this.cameraStyle == CameraStyle.lockOn){
let targetX = this.targetEntity.position.x;
let targetY = this.targetEntity.position.y;
/**
* -11minimumZoom转换为maximumZoom
* /使-11
*/
public get zoom() {
if (this._zoom == 0)
return 1;
if (this._worldSpaceDeadZone.x > targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
else if(this._worldSpaceDeadZone.x < targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
if (this._zoom < 1)
return MathHelper.map(this._zoom, this._minimumZoom, 1, -1, 0);
if (this._worldSpaceDeadZone.y < targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
else if(this._worldSpaceDeadZone.y > targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
} else {
if (!this._targetCollider){
this._targetCollider = this.targetEntity.getComponent<Collider>(Collider);
if (!this._targetCollider)
return;
return MathHelper.map(this._zoom, 1, this._maximumZoom, 0, 1);
}
/**
* -11minimumZoom转换为maximumZoom
* /使-11
* @param value
*/
public set zoom(value: number) {
this.setZoom(value);
}
public _minimumZoom = 0.3;
/**
* 0-number.max0.3
*/
public get minimumZoom() {
return this._minimumZoom;
}
/**
* 0-number.max0.3
* @param value
*/
public set minimumZoom(value: number) {
this.setMinimumZoom(value);
}
public _maximumZoom = 3;
/**
* 0-number.max3
*/
public get maximumZoom() {
return this._maximumZoom;
}
/**
* 0-number.max3
* @param value
*/
public set maximumZoom(value: number) {
this.setMaximumZoom(value);
}
public _bounds: Rectangle = new Rectangle();
/**
* -
*/
public get bounds() {
if (this._areMatrixedDirty)
this.updateMatrixes();
if (this._areBoundsDirty) {
// 旋转或非旋转的边界都需要左上角和右下角
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,
Core.graphicsDevice.viewport.height - this._inset.bottom));
if (this.entity.transform.rotation != 0) {
// 特别注意旋转的边界。我们需要找到绝对的最小/最大值并从中创建边界
let topRight = this.screenToWorldPoint(new Vector2(Core.graphicsDevice.viewport.width - this._inset.right,
this._inset.top));
let bottomLeft = this.screenToWorldPoint(new Vector2(this._inset.left,
Core.graphicsDevice.viewport.height - this._inset.bottom));
let minX = Math.min(topLeft.x, bottomRight.x, topRight.x, bottomLeft.x);
let maxX = Math.max(topLeft.x, bottomRight.x, topRight.x, bottomLeft.x);
let minY = Math.min(topLeft.y, bottomRight.y, topRight.y, bottomLeft.y);
let maxY = Math.max(topLeft.y, bottomRight.y, topRight.y, bottomLeft.y);
this._bounds.location = new Vector2(minX, minY);
this._bounds.width = maxX - minX;
this._bounds.height = maxY - minY;
} else {
this._bounds.location = topLeft;
this._bounds.width = bottomRight.x - topLeft.x;
this._bounds.height = bottomRight.y - topLeft.y;
}
this._areBoundsDirty = false;
}
let targetBounds = this.targetEntity.getComponent<Collider>(Collider).bounds;
if (!this._worldSpaceDeadZone.containsRect(targetBounds)){
if (this._worldSpaceDeadZone.left > targetBounds.left)
this._desiredPositionDelta.x = targetBounds.left - this._worldSpaceDeadZone.left;
else if(this._worldSpaceDeadZone.right < targetBounds.right)
this._desiredPositionDelta.x = targetBounds.right - this._worldSpaceDeadZone.right;
return this._bounds;
}
if (this._worldSpaceDeadZone.bottom < targetBounds.bottom)
this._desiredPositionDelta.y = targetBounds.bottom - this._worldSpaceDeadZone.bottom;
else if(this._worldSpaceDeadZone.top > targetBounds.top)
this._desiredPositionDelta.y = targetBounds.top - this._worldSpaceDeadZone.top;
public _transformMatrix: Matrix2D = new Matrix2D().identity();
/**
*
*/
public get transformMatrix(): Matrix2D {
if (this._areMatrixedDirty)
this.updateMatrixes();
return this._transformMatrix;
}
public _inverseTransformMatrix: Matrix2D = new Matrix2D().identity();
/**
*
*/
public get inverseTransformMatrix(): Matrix2D {
if (this._areMatrixedDirty)
this.updateMatrixes();
return this._inverseTransformMatrix;
}
public _origin: Vector2 = Vector2.zero;
public get origin() {
return this._origin;
}
public set origin(value: Vector2) {
if (this._origin != value) {
this._origin = value;
this._areMatrixedDirty = true;
}
}
/**
*
* @param newWidth
* @param newHeight
*/
public onSceneSizeChanged(newWidth: number, newHeight: number) {
let oldOrigin = this._origin;
this.origin = new Vector2(newWidth / 2, newHeight / 2);
this.entity.transform.position = Vector2.add(this.entity.transform.position, Vector2.subtract(this._origin, oldOrigin));
}
/**
*
* @param left
* @param right
* @param top
* @param bottom
*/
public setInset(left: number, right: number, top: number, bottom: number): Camera {
this._inset = new CameraInset();
this._inset.left = left;
this._inset.right = right;
this._inset.top = top;
this._inset.bottom = bottom;
this._areBoundsDirty = true;
return this;
}
/**
* entity.transform.setPosition快速访问
* @param position
*/
public setPosition(position: Vector2) {
this.entity.transform.setPosition(position.x, position.y);
return this;
}
/**
* entity.transform.setRotation的快速访问
* @param rotation
*/
public setRotation(rotation: number): Camera {
this.entity.transform.setRotation(rotation);
return this;
}
/**
* -11minimumZoom转换为maximumZoom
* /使-11
* @param zoom
*/
public setZoom(zoom: number): Camera {
let newZoom = MathHelper.clamp(zoom, -1, 1);
if (newZoom == 0) {
this._zoom = 1;
} else if (newZoom < 0) {
this._zoom = MathHelper.map(newZoom, -1, 0, this._minimumZoom, 1);
} else {
this._zoom = MathHelper.map(newZoom, 0, 1, 1, this._maximumZoom);
}
this._areMatrixedDirty = true;
return this;
}
/**
* 0-number.max 0.3
* @param minZoom
*/
public setMinimumZoom(minZoom: number): Camera {
if (minZoom <= 0) {
console.error("minimumZoom must be greater than zero");
return;
}
if (this._zoom < minZoom)
this._zoom = this.minimumZoom;
this._minimumZoom = minZoom;
return this;
}
/**
* 0-number.max 3
* @param maxZoom
*/
public setMaximumZoom(maxZoom: number): Camera {
if (maxZoom <= 0) {
console.error("maximumZoom must be greater than zero");
return;
}
if (this._zoom > maxZoom)
this._zoom = maxZoom;
this._maximumZoom = maxZoom;
return this;
}
public onEntityTransformChanged(comp: transform.Component) {
this._areMatrixedDirty = true;
}
public zoomIn(deltaZoom: number) {
this.zoom += deltaZoom;
}
public zoomOut(deltaZoom: number) {
this.zoom -= deltaZoom;
}
/**
*
* @param worldPosition
*/
public worldToScreenPoint(worldPosition: Vector2): Vector2 {
this.updateMatrixes();
worldPosition = Vector2.transform(worldPosition, this._transformMatrix);
return worldPosition;
}
/**
*
* @param screenPosition
*/
public screenToWorldPoint(screenPosition: Vector2): Vector2 {
this.updateMatrixes();
screenPosition = Vector2.transform(screenPosition, this._inverseTransformMatrix);
return screenPosition;
}
/**
*
*/
public mouseToWorldPoint(): Vector2 {
return this.screenToWorldPoint(Input.touchPosition);
}
public onAddedToEntity() {
this.follow(this._targetEntity, this._cameraStyle);
}
public update() {
let halfScreen = Vector2.multiply(new Vector2(this.bounds.width, this.bounds.height), new Vector2(0.5));
this._worldSpaceDeadZone.x = this.position.x - halfScreen.x * Core.scene.scaleX + this.deadzone.x + this.focusOffset.x;
this._worldSpaceDeadZone.y = this.position.y - halfScreen.y * Core.scene.scaleY + this.deadzone.y + this.focusOffset.y;
this._worldSpaceDeadZone.width = this.deadzone.width;
this._worldSpaceDeadZone.height = this.deadzone.height;
if (this._targetEntity)
this.updateFollow();
this.position = Vector2.lerp(this.position, Vector2.add(this.position, this._desiredPositionDelta), this.followLerp);
this.entity.transform.roundPosition();
if (this.mapLockEnabled) {
this.position = this.clampToMapSize(this.position);
this.entity.transform.roundPosition();
}
}
/**
*
* @param position
*/
public clampToMapSize(position: Vector2) {
let halfScreen = Vector2.multiply(new Vector2(this.bounds.width, this.bounds.height), new Vector2(0.5));
let cameraMax = new Vector2(this.mapSize.x - halfScreen.x, this.mapSize.y - halfScreen.y);
return Vector2.clamp(position, halfScreen, cameraMax);
}
public updateFollow() {
this._desiredPositionDelta.x = this._desiredPositionDelta.y = 0;
if (this._cameraStyle == CameraStyle.lockOn) {
let targetX = this._targetEntity.transform.position.x;
let targetY = this._targetEntity.transform.position.y;
if (this._worldSpaceDeadZone.x > targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
else if (this._worldSpaceDeadZone.x < targetX)
this._desiredPositionDelta.x = targetX - this._worldSpaceDeadZone.x;
if (this._worldSpaceDeadZone.y < targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
else if (this._worldSpaceDeadZone.y > targetY)
this._desiredPositionDelta.y = targetY - this._worldSpaceDeadZone.y;
} else {
if (!this._targetCollider) {
this._targetCollider = this._targetEntity.getComponent<Collider>(Collider);
if (!this._targetCollider)
return;
}
let targetBounds = this._targetEntity.getComponent<Collider>(Collider).bounds;
if (!this._worldSpaceDeadZone.containsRect(targetBounds)) {
if (this._worldSpaceDeadZone.left > targetBounds.left)
this._desiredPositionDelta.x = targetBounds.left - this._worldSpaceDeadZone.left;
else if (this._worldSpaceDeadZone.right < targetBounds.right)
this._desiredPositionDelta.x = targetBounds.right - this._worldSpaceDeadZone.right;
if (this._worldSpaceDeadZone.bottom < targetBounds.bottom)
this._desiredPositionDelta.y = targetBounds.bottom - this._worldSpaceDeadZone.bottom;
else if (this._worldSpaceDeadZone.top > targetBounds.top)
this._desiredPositionDelta.y = targetBounds.top - this._worldSpaceDeadZone.top;
}
}
}
public follow(targetEntity: Entity, cameraStyle: CameraStyle = CameraStyle.cameraWindow) {
this._targetEntity = targetEntity;
this._cameraStyle = cameraStyle;
switch (this._cameraStyle) {
case CameraStyle.cameraWindow:
let w = this.bounds.width / 6;
let h = this.bounds.height / 3;
this.deadzone = new Rectangle((this.bounds.width - w) / 2, (this.bounds.height - h) / 2, w, h);
break;
case CameraStyle.lockOn:
this.deadzone = new Rectangle(this.bounds.width / 2, this.bounds.height / 2, 10, 10);
break;
}
}
/**
*
* @param width
* @param height
*/
public setCenteredDeadzone(width: number, height: number) {
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;
}
}
}
enum CameraStyle {
lockOn,
cameraWindow,
}
+20 -18
View File
@@ -1,22 +1,24 @@
class ComponentPool<T extends PooledComponent>{
private _cache: T[];
private _type: any;
module es {
export class ComponentPool<T extends PooledComponent> {
private _cache: T[];
private _type: any;
constructor(typeClass: any){
this._type = typeClass;
this._cache = [];
}
constructor(typeClass: any) {
this._type = typeClass;
this._cache = [];
}
public obtain(): T{
try {
return this._cache.length > 0 ? this._cache.shift() : new this._type();
} catch(err){
throw new Error(this._type + err);
public obtain(): T {
try {
return this._cache.length > 0 ? this._cache.shift() : new this._type();
} catch (err) {
throw new Error(this._type + err);
}
}
public free(component: T) {
component.reset();
this._cache.push(component);
}
}
public free(component: T){
component.reset();
this._cache.push(component);
}
}
}
@@ -0,0 +1,10 @@
module es {
/**
*
*/
export class IUpdatableComparer {
public compare(a: Component, b: Component) {
return a.updateOrder - b.updateOrder;
}
}
}
+21 -28
View File
@@ -1,32 +1,25 @@
///<reference path="./RenderableComponent.ts" />
class Mesh extends RenderableComponent {
private _mesh: egret.Mesh;
module es {
export class Mesh extends RenderableComponent {
private _mesh: egret.Mesh;
constructor(){
super();
constructor() {
super();
this._mesh = new egret.Mesh();
this._mesh = new egret.Mesh();
}
public setTexture(texture: egret.Texture): Mesh {
this._mesh.texture = texture;
this._mesh.$renderNode = new egret.sys.RenderNode();
return this;
}
public reset() {
}
render(camera: es.Camera) {
}
}
public setTexture(texture: egret.Texture): Mesh{
this._mesh.texture = texture;
return this;
}
public onAddedToEntity(){
this.addChild(this._mesh);
}
public onRemovedFromEntity(){
this.removeChild(this._mesh);
}
public render(camera: Camera){
this.x = this.entity.position.x - camera.position.x + camera.origin.x;
this.y = this.entity.position.y - camera.position.y + camera.origin.y;
}
public reset() {
}
}
}
@@ -1,74 +1,85 @@
///<reference path="./Collider.ts" />
class BoxCollider extends Collider {
public get width(){
return (this.shape as Box).width;
}
module es {
export class BoxCollider extends Collider {
/**
* RenderableComponent在实体上
*/
constructor() {
super();
public set width(value: number){
this.setWidth(value);
}
/**
* BoxCollider的宽度
* @param width
*/
public setWidth(width: number): BoxCollider{
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (width != box.width){
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, box.height);
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
// 我们在这里插入一个1x1框作为占位符,直到碰撞器在下一阵被添加到实体并可以获得更精确的自动调整大小数据
this.shape = new Box(1, 1);
this._colliderRequiresAutoSizing = true;
}
return this;
}
public get height(){
return (this.shape as Box).height;
}
public set height(value: number){
this.setHeight(value);
}
/**
* BoxCollider的高度
* @param height
*/
public setHeight(height: number){
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (height != box.height){
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(box.width, height);
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
}
}
/**
* RenderableComponent在实体上
*/
constructor(){
super();
// 我们在这里插入一个1x1框作为占位符,直到碰撞器在下一阵被添加到实体并可以获得更精确的自动调整大小数据
this.shape = new Box(1, 1);
this._colliderRequiresAutoSizing = true;
}
public setSize(width: number, height: number){
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (width != box.width || height != box.height){
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, height);
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
public get width() {
return (this.shape as Box).width;
}
return this;
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的大小
* @param width
* @param height
*/
public setSize(width: number, height: number) {
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (width != box.width || height != box.height) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, height);
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
}
return this;
}
/**
* BoxCollider的宽度
* @param width
*/
public setWidth(width: number): BoxCollider {
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (width != box.width) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(width, box.height);
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
}
return this;
}
/**
* BoxCollider的高度
* @param height
*/
public setHeight(height: number) {
this._colliderRequiresAutoSizing = false;
let box = this.shape as Box;
if (height != box.height) {
// 更新框,改变边界,如果我们需要更新物理系统中的边界
box.updateBox(box.width, height);
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
}
}
public toString() {
return `[BoxCollider: bounds: ${this.bounds}]`;
}
}
}
}
@@ -0,0 +1,48 @@
module es {
export class CircleCollider extends Collider {
/**
*
*
* @param radius
*/
constructor(radius?: number) {
super();
if (radius)
this._colliderRequiresAutoSizing = true;
// 我们在这里插入一个1px的圆圈作为占位符
// 直到碰撞器被添加到实体并可以获得更精确的自动调整大小数据的下一帧
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
*/
public setRadius(radius: number): CircleCollider {
this._colliderRequiresAutoSizing = false;
let circle = this.shape as Circle;
if (radius != circle.radius) {
circle.radius = radius;
circle._originalRadius = radius;
if (this.entity && this._isParentEntityAddedToScene)
Physics.updateCollider(this);
}
return this;
}
public toString() {
return `[CircleCollider: bounds: ${this.bounds}, radius: ${(this.shape as Circle).radius}]`
}
}
}
@@ -1,146 +1,238 @@
abstract class Collider extends Component{
/** 对撞机的基本形状 */
public shape: Shape;
/** 在处理冲突时,physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法。 */
public physicsLayer = 1 << 0;
/** 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件 */
public isTrigger: boolean;
/**
*
* 使
*/
public registeredPhysicsBounds: Rectangle = new Rectangle();
/** 如果为true,碰撞器将根据附加的变换缩放和旋转 */
public shouldColliderScaleAndRotateWithTransform = true;
/** 默认为所有层。 */
public collidesWithLayers = Physics.allLayers;
module es {
export abstract class Collider extends Component {
/**
*
*/
public shape: Shape;
/**
*
*/
public isTrigger: boolean;
/**
* physicsLayer可以用作过滤器Flags类有帮助位掩码的方法
*/
public physicsLayer = 1 << 0;
/**
* 使
*
*/
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;
public _localOffsetLength: number;
/** 标记来跟踪我们的实体是否被添加到场景中 */
protected _isParentEntityAddedToScene;
protected _colliderRequiresAutoSizing;
protected _localOffset: Vector2 = new Vector2(0, 0);
/** 标记来记录我们是否注册了物理系统 */
protected _isColliderRegistered;
/**
*
*/
public get absolutePosition(): Vector2 {
return Vector2.add(this.entity.transform.position, this._localOffset);
}
public get bounds(): Rectangle {
// this.shape.recalculateBounds(this);
let bds = this.entity.getBounds();
return new Rectangle(bds.x, bds.y, bds.width, bds.height);
}
/**
* transform.rotation
*/
public get rotation(): number {
if (this.shouldColliderScaleAndRotateWithTransform && this.entity)
return this.entity.transform.rotation;
public get localOffset(){
return new Vector2(this.x, this.y);
}
return 0;
}
/**
* localOffset添加到实体
*/
public set localOffset(value: Vector2){
this.setLocalOffset(value);
}
public get bounds(): Rectangle {
if (this._isPositionDirty || this._isRotationDirty) {
this.shape.recalculateBounds(this);
this._isPositionDirty = this._isRotationDirty = false;
}
public setLocalOffset(offset: Vector2){
if (this._localOffset != offset){
this.unregisterColliderWithPhysicsSystem();
this.$setX(offset.x);
this.$setY(offset.y);
this._localOffsetLength = this._localOffset.length();
return this.shape.bounds;
}
protected _localOffset: Vector2 = Vector2.zero;
/**
* localOffset添加到实体
* /
*/
public get localOffset(): Vector2 {
return this._localOffset;
}
/**
* localOffset添加到实体
* /
* @param value
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
/**
* localOffset添加到实体
*
* @param offset
*/
public setLocalOffset(offset: Vector2): Collider {
if (this._localOffset != offset) {
this.unregisterColliderWithPhysicsSystem();
this._localOffset = offset;
this._localOffsetLength = this._localOffset.length();
this._isPositionDirty = true;
this.registerColliderWithPhysicsSystem();
}
return this;
}
/**
* true
* @param shouldColliderScaleAndRotationWithTransform
*/
public setShouldColliderScaleAndRotateWithTransform(shouldColliderScaleAndRotationWithTransform: boolean): Collider {
this.shouldColliderScaleAndRotateWithTransform = shouldColliderScaleAndRotationWithTransform;
this._isPositionDirty = this._isRotationDirty = true;
return this;
}
public onAddedToEntity() {
if (this._colliderRequiresAutoSizing) {
if (!(this instanceof BoxCollider || this instanceof CircleCollider)) {
console.error("Only box and circle colliders can be created automatically");
return;
}
let renderable = this.entity.getComponent<RenderableComponent>(RenderableComponent);
if (renderable) {
let renderableBounds = renderable.bounds;
// 这里我们需要大小*反尺度,因为当我们自动调整碰撞器的大小时,它需要没有缩放的渲染
let width = renderableBounds.width / this.entity.scale.x;
let height = renderableBounds.height / this.entity.scale.y;
// 圆碰撞器需要特别注意原点
if (this instanceof CircleCollider) {
this.radius = Math.max(width, height) * 0.5;
} else {
this.width = width;
this.height = height;
}
// 获取渲染的中心,将其转移到本地坐标,并使用它作为碰撞器的localOffset
this.localOffset = Vector2.subtract(renderableBounds.center, this.entity.transform.position);
} else {
console.warn("Collider has no shape and no RenderableComponent. Can't figure out how to size it.");
}
}
this._isParentEntityAddedToScene = true;
this.registerColliderWithPhysicsSystem();
}
}
/**
* ()
*/
public registerColliderWithPhysicsSystem(){
// 如果在将我们添加到实体之前更改了origin等属性,则实体可以为null
if (this._isParentEntityAddedToScene && !this._isColliderRegistered){
Physics.addCollider(this);
this._isColliderRegistered = true;
public onRemovedFromEntity() {
this.unregisterColliderWithPhysicsSystem();
this._isParentEntityAddedToScene = false;
}
}
/**
* ()
*/
public unregisterColliderWithPhysicsSystem(){
if (this._isParentEntityAddedToScene && this._isColliderRegistered){
Physics.removeCollider(this);
}
this._isColliderRegistered = false;
}
/**
*
* @param other
*/
public overlaps(other: Collider){
return this.shape.overlaps(other.shape);
}
/**
* ()true
* @param collider
* @param motion
*/
public collidesWith(collider: Collider, motion: Vector2){
// 改变形状的位置,使它在移动后的位置,这样我们可以检查重叠
let oldPosition = this.shape.position;
this.shape.position = Vector2.add(this.shape.position, motion);
let result = this.shape.collidesWithShape(collider.shape);
if (result)
result.collider = collider;
// 将图形位置返回到检查前的位置
this.shape.position = oldPosition;
return result;
}
public onAddedToEntity(){
if (this._colliderRequiresAutoSizing){
if (!(this instanceof BoxCollider)){
console.error("Only box and circle colliders can be created automatically");
public onEntityTransformChanged(comp: transform.Component) {
switch (comp) {
case transform.Component.position:
this._isPositionDirty = true;
break;
case transform.Component.scale:
this._isPositionDirty = true;
break;
case transform.Component.rotation:
this._isRotationDirty = true;
break;
}
let bounds = this.entity.getBounds();
let renderbaleBounds = new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
if (this._isColliderRegistered)
Physics.updateCollider(this);
}
// 这里我们需要大小*反尺度,因为当我们自动调整碰撞器的大小时,它需要没有缩放的渲染
let width = renderbaleBounds.width / this.entity.scale.x;
let height = renderbaleBounds.height / this.entity.scale.y;
public onEnabled() {
this.registerColliderWithPhysicsSystem();
this._isPositionDirty = this._isRotationDirty = true;
}
if (this instanceof BoxCollider){
let boxCollider = this as BoxCollider;
boxCollider.width = width;
boxCollider.height = height;
public onDisabled() {
this.unregisterColliderWithPhysicsSystem();
}
// 获取渲染的中心,将其转移到本地坐标,并使用它作为碰撞器的localOffset
this.localOffset = Vector2.subtract(renderbaleBounds.center, this.entity.position);
/**
* ()
*/
public registerColliderWithPhysicsSystem() {
// 如果在将我们添加到实体之前更改了origin等属性,则实体可以为null
if (this._isParentEntityAddedToScene && !this._isColliderRegistered) {
Physics.addCollider(this);
this._isColliderRegistered = true;
}
}
this._isParentEntityAddedToScene = true;
this.registerColliderWithPhysicsSystem();
}
public onRemovedFromEntity(){
this.unregisterColliderWithPhysicsSystem();
this._isParentEntityAddedToScene = false;
}
/**
* ()
*/
public unregisterColliderWithPhysicsSystem() {
if (this._isParentEntityAddedToScene && this._isColliderRegistered) {
Physics.removeCollider(this);
}
this._isColliderRegistered = false;
}
public onEnabled(){
this.registerColliderWithPhysicsSystem();
}
/**
*
* @param other
*/
public overlaps(other: Collider): boolean {
return this.shape.overlaps(other.shape);
}
public onDisabled(){
this.unregisterColliderWithPhysicsSystem();
}
/**
* ()true
* @param collider
* @param motion
* @param result
*/
public collidesWith(collider: Collider, motion: Vector2, result: CollisionResult): boolean {
// 改变形状的位置,使它在移动后的位置,这样我们可以检查重叠
let oldPosition = this.entity.position;
this.entity.position = this.entity.position.add(motion);
public onEntityTransformChanged(comp: TransformComponent){
if (this._isColliderRegistered)
Physics.updateCollider(this);
let didCollide = this.shape.collidesWithShape(collider.shape, result);
if (didCollide)
result.collider = collider;
// 将图形位置返回到检查前的位置
this.entity.position = oldPosition;
return didCollide;
}
public clone(): Component {
let collider = ObjectUtils.clone<Collider>(this);
collider.entity = null;
if (this.shape)
collider.shape = this.shape.clone();
return collider;
}
}
}
}
@@ -0,0 +1,26 @@
module es {
/**
*
*/
export class PolygonCollider extends Collider {
/**
* localOffset的差异为居中
* @param points
*/
constructor(points: Vector2[]) {
super();
// 第一点和最后一点决不能相同。我们想要一个开放的多边形
let isPolygonClosed = points[0] == points[points.length - 1];
// 最后一个移除
if (isPolygonClosed)
points.splice(points.length - 1, 1);
let center = Polygon.findPolygonCenter(points);
this.setLocalOffset(center);
Polygon.recenterPolygonVerts(points);
this.shape = new Polygon(points);
}
}
}
@@ -1,4 +1,23 @@
interface ITriggerListener {
onTriggerEnter(other: Collider, local: Collider);
onTriggerExit(other: Collider, local: Collider);
}
module es {
/**
* /退
* ITriggerListener方法将在实现接口的触发器实体上的任何组件上调用
* Mover类一起工作
*/
export interface ITriggerListener {
/**
*
* Mover/ProjectileMover方法处理使
* @param other
* @param local
*/
onTriggerEnter(other: Collider, local: Collider);
/**
*
* @param other
* @param local
*/
onTriggerExit(other: Collider, local: Collider);
}
}
+72 -65
View File
@@ -1,82 +1,89 @@
/**
*
* ITriggerListener接口用于管理对移动过程中违反的任何触发器的回调
* move方法
*
* ITriggerListener
*/
class Mover extends Component {
private _triggerHelper: ColliderTriggerHelper;
public onAddedToEntity(){
this._triggerHelper = new ColliderTriggerHelper(this.entity);
}
module es {
/**
*
* @param motion
*
* ITriggerListener接口用于管理对移动过程中违反的任何触发器的回调
* move方法
*
* ITriggerListener
*/
public calculateMovement(motion: Vector2){
let collisionResult = new CollisionResult();
export class Mover extends Component {
private _triggerHelper: ColliderTriggerHelper;
if (!this.entity.getComponent(Collider) || !this._triggerHelper){
return null;
public onAddedToEntity() {
this._triggerHelper = new ColliderTriggerHelper(this.entity);
}
let colliders: Collider[] = this.entity.getComponents(Collider);
for (let i = 0; i < colliders.length; i ++){
let collider = colliders[i];
/**
*
* @param motion
* @param collisionResult
*/
public calculateMovement(motion: Vector2, collisionResult: CollisionResult): boolean {
if (!this.entity.getComponent(Collider) || !this._triggerHelper) {
return false;
}
// 不检测触发器
if (collider.isTrigger)
continue;
// 移动所有的非触发碰撞器并获得最近的碰撞
let colliders: Collider[] = this.entity.getComponents(Collider);
for (let i = 0; i < colliders.length; i++) {
let collider = colliders[i];
// 获取我们在新位置可能发生碰撞的任何东西
let bounds = collider.bounds;
bounds.x += motion.x;
bounds.y += motion.y;
let boxcastResult = Physics.boxcastBroadphaseExcludingSelf(collider, bounds, collider.collidesWithLayers);
bounds = boxcastResult.bounds;
let neighbors = boxcastResult.tempHashSet;
for (let j = 0; j < neighbors.length; j ++){
let neighbor = neighbors[j];
// 不检测触发器
if (neighbor.isTrigger)
// 不检测触发器 在我们移动后会重新访问它
if (collider.isTrigger)
continue;
let _internalcollisionResult = collider.collidesWith(neighbor, motion);
if (_internalcollisionResult){
// 如果碰撞 则退回之前的移动量
motion = Vector2.subtract(motion, _internalcollisionResult.minimumTranslationVector);
// 获取我们在新位置可能发生碰撞的任何东西
let bounds = collider.bounds;
bounds.x += motion.x;
bounds.y += motion.y;
let neighbors = Physics.boxcastBroadphaseExcludingSelf(collider, bounds, collider.collidesWithLayers);
// 如果我们碰到多个对象,为了简单起见,只取第一个。
if (_internalcollisionResult.collider){
collisionResult = _internalcollisionResult;
for (let j = 0; j < neighbors.length; j++) {
let neighbor = neighbors[j];
// 不检测触发器
if (neighbor.isTrigger)
continue;
let _internalcollisionResult: CollisionResult = new CollisionResult();
if (collider.collidesWith(neighbor, motion, _internalcollisionResult)) {
// 如果碰撞 则退回之前的移动量
motion = motion.subtract(_internalcollisionResult.minimumTranslationVector);
// 如果我们碰到多个对象,为了简单起见,只取第一个。
if (_internalcollisionResult.collider != null) {
collisionResult = _internalcollisionResult;
}
}
}
}
ListPool.free(colliders);
return collisionResult.collider != null;
}
ListPool.free(colliders);
/**
* calculatemomovement应用到实体并更新triggerHelper
* @param motion
*/
public applyMovement(motion: Vector2) {
// 移动实体到它的新位置,如果我们有一个碰撞,否则移动全部数量。当碰撞发生时,运动被更新
this.entity.position = Vector2.add(this.entity.position, motion);
return {collisionResult: collisionResult, motion: motion};
// 对所有是触发器的碰撞器与所有宽相位碰撞器进行重叠检查。任何重叠都会导致触发事件。
if (this._triggerHelper)
this._triggerHelper.update();
}
/**
* calculateMovement和applyMovement来移动考虑碰撞的实体;
* @param motion
* @param collisionResult
*/
public move(motion: Vector2, collisionResult: CollisionResult) {
this.calculateMovement(motion, collisionResult);
this.applyMovement(motion);
return collisionResult.collider != null;
}
}
public applyMovement(motion: Vector2){
this.entity.position = Vector2.add(this.entity.position, motion);
if (this._triggerHelper)
this._triggerHelper.update();
}
public move(motion: Vector2){
let movementResult = this.calculateMovement(motion);
let collisionResult = movementResult.collisionResult;
motion = movementResult.motion;
this.applyMovement(motion);
return collisionResult;
}
}
}
@@ -0,0 +1,58 @@
module es {
/**
* itriggerlistener报告冲突的移动器
*
*/
export class ProjectileMover extends Component {
private _tempTriggerList: ITriggerListener[] = [];
private _collider: Collider;
public onAddedToEntity() {
this._collider = this.entity.getComponent<Collider>(Collider);
if (!this._collider)
console.warn("ProjectileMover has no Collider. ProjectilMover requires a Collider!");
}
/**
*
* @param motion
*/
public move(motion: Vector2): boolean {
if (!this._collider)
return false;
let didCollide = false;
// 获取我们在新位置可能发生碰撞的任何东西
this.entity.position = Vector2.add(this.entity.position, motion);
// 获取任何可能在新位置发生碰撞的东西
let neighbors = Physics.boxcastBroadphase(this._collider.bounds, this._collider.collidesWithLayers);
for (let i = 0; i < neighbors.length; i++) {
let neighbor = neighbors[i];
if (this._collider.overlaps(neighbor) && neighbor.enabled) {
didCollide = true;
this.notifyTriggerListeners(this._collider, neighbor);
}
}
return didCollide;
}
private notifyTriggerListeners(self: Collider, other: Collider) {
// 通知我们重叠的碰撞器实体上的任何侦听器
other.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i++) {
this._tempTriggerList[i].onTriggerEnter(self, other);
}
this._tempTriggerList.length = 0;
// 通知此实体上的任何侦听器
this.entity.getComponents("ITriggerListener", this._tempTriggerList);
for (let i = 0; i < this._tempTriggerList.length; i++) {
this._tempTriggerList[i].onTriggerEnter(other, self);
}
this._tempTriggerList.length = 0;
}
}
}
+6 -4
View File
@@ -1,4 +1,6 @@
/** 回收实例的组件类型。 */
abstract class PooledComponent extends Component {
public abstract reset();
}
module es {
/** 回收实例的组件类型。 */
export abstract class PooledComponent extends Component {
public abstract reset();
}
}
+176 -40
View File
@@ -1,56 +1,192 @@
///<reference path="./PooledComponent.ts" />
/**
*
*/
abstract class RenderableComponent extends PooledComponent implements IRenderable {
private _isVisible: boolean;
protected _areBoundsDirty = true;
protected _bounds: Rectangle = new Rectangle();
protected _localOffset: Vector2 = Vector2.zero;
module es {
/**
*
*/
export abstract class RenderableComponent extends Component implements IRenderable {
/**
* egret显示对象
*/
public displayObject: egret.DisplayObject = new egret.DisplayObject();
/**
*
*/
public color: number = 0x000000;
protected _areBoundsDirty = true;
public color: number = 0x000000;
/**
* renderableComponent的宽度
* bounds属性则需要实现这个
*/
public get width() {
return this.bounds.width;
}
public get width(){
return this.getWidth();
}
/**
* renderableComponent的高度
* bounds属性则需要实现这个
*/
public get height() {
return this.bounds.height;
}
public get height(){
return this.getHeight();
}
protected _localOffset: Vector2 = Vector2.zero;
public get isVisible(){
return this._isVisible;
}
/**
*
*/
public get localOffset(): Vector2 {
return this._localOffset;
}
public set isVisible(value: boolean){
this._isVisible = value;
/**
*
* @param value
*/
public set localOffset(value: Vector2) {
this.setLocalOffset(value);
}
if (this._isVisible)
this.onBecameVisible();
else
this.onBecameInvisible();
}
protected _renderLayer: number = 0;
public get bounds(): Rectangle{
return new Rectangle(this.getBounds().x, this.getBounds().y, this.getBounds().width, this.getBounds().height);
}
/**
*
*/
public get renderLayer(): number {
return this._renderLayer;
}
protected getWidth(){
return this.bounds.width;
}
public set renderLayer(value: number) {
protected getHeight(){
return this.bounds.height;
}
}
protected onBecameVisible(){}
protected _bounds: Rectangle = new Rectangle();
protected onBecameInvisible(){}
/**
* AABB,
*/
public get bounds(): Rectangle {
if (this._areBoundsDirty) {
this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, Vector2.zero,
this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height);
this._areBoundsDirty = false;
}
public abstract render(camera: Camera);
return this._bounds;
}
public isVisibleFromCamera(camera: Camera): boolean{
this.isVisible = camera.getBounds().intersects(this.getBounds());
return this.isVisible;
private _isVisible: boolean;
/**
* onBecameVisible/onBecameInvisible方法
*/
public get isVisible() {
return this._isVisible;
}
/**
* onBecameVisible/onBecameInvisible方法
* @param value
*/
public set isVisible(value: boolean) {
if (this._isVisible != value) {
this._isVisible = value;
if (this._isVisible)
this.onBecameVisible();
else
this.onBecameInvisible();
}
}
public onEntityTransformChanged(comp: transform.Component) {
this._areBoundsDirty = true;
}
/**
* 使
* @param camera
*/
public abstract render(camera: Camera);
/**
* renderableComponent的边界与camera.bounds相交 true
* isVisible标志的状态开关
* 使
* @param camera
*/
public isVisibleFromCamera(camera: Camera): boolean {
this.isVisible = camera.bounds.intersects(this.bounds);
return this.isVisible;
}
/**
*
* @param renderLayer
*/
public setRenderLayer(renderLayer: number): RenderableComponent {
if (renderLayer != this._renderLayer) {
let oldRenderLayer = this._renderLayer;
this._renderLayer = renderLayer;
// 如果该组件拥有一个实体,那么是由ComponentList管理,需要通知它改变了渲染层
if (this.entity && this.entity.scene)
this.entity.scene.renderableComponents.updateRenderableRenderLayer(this, oldRenderLayer, this._renderLayer);
}
return this;
}
/**
*
* @param color
*/
public setColor(color: number): RenderableComponent {
this.color = color;
return this;
}
/**
*
* @param offset
*/
public setLocalOffset(offset: Vector2): RenderableComponent {
if (this._localOffset != offset) {
this._localOffset = offset;
}
return this;
}
/**
*
*/
public sync(camera: Camera) {
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.scaleX = this.entity.scale.x;
this.displayObject.scaleY = this.entity.scale.y;
this.displayObject.rotation = this.entity.rotation;
}
public toString() {
return `[RenderableComponent] renderLayer: ${this.renderLayer}`;
}
/**
* renderableComponent进入相机框架时调用
* isVisibleFromCamera进行剔除检查
*/
protected onBecameVisible() {
this.displayObject.visible = this.isVisible;
}
/**
* renderableComponent离开相机框架时调用
* isVisibleFromCamera进行剔除检查
*/
protected onBecameInvisible() {
this.displayObject.visible = this.isVisible;
}
}
}
@@ -1,37 +1,38 @@
///<reference path="./TiledSpriteRenderer.ts"/>
class ScrollingSpriteRenderer extends TiledSpriteRenderer {
public scrollSpeedX = 15;
public scroolSpeedY = 0;
private _scrollX = 0;
private _scrollY = 0;
module es {
export class ScrollingSpriteRenderer extends TiledSpriteRenderer {
/**
* x自动滚动速度(/s为单位)
*/
public scrollSpeedX = 15;
/**
* y速度(/s为单位)
*/
public scroolSpeedY = 0;
public update(){
this._scrollX += this.scrollSpeedX * Time.deltaTime;
this._scrollY += this.scroolSpeedY * Time.deltaTime;
this.sourceRect.x = this._scrollX;
this.sourceRect.y = this._scrollY;
public get textureScale(): Vector2 {
return this._textureScale;
}
public set textureScale(value: Vector2){
this._textureScale = value;
// 重新计算我们的inverseTextureScale和源矩形大小
this._inverseTexScale = new Vector2(1 / this._textureScale.x, 1 / this._textureScale.y);
}
private _scrollX = 0;
private _scrollY = 0;
constructor(sprite: Sprite) {
super(sprite);
}
public update() {
this._scrollX += this.scrollSpeedX * Time.deltaTime;
this._scrollY += this.scroolSpeedY * Time.deltaTime;
this._sourceRect.x = this._scrollX;
this._sourceRect.y = this._scrollY;
}
}
public render(camera: Camera) {
if (!this.sprite)
return;
super.render(camera);
let renderTexture = new egret.RenderTexture();
let cacheBitmap = new egret.DisplayObjectContainer();
cacheBitmap.removeChildren();
cacheBitmap.addChild(this.leftTexture);
cacheBitmap.addChild(this.rightTexture);
this.leftTexture.x = this.sourceRect.x;
this.rightTexture.x = this.sourceRect.x - this.sourceRect.width;
this.leftTexture.y = this.sourceRect.y;
this.rightTexture.y = this.sourceRect.y;
cacheBitmap.cacheAsBitmap = true;
renderTexture.drawToTexture(cacheBitmap, new egret.Rectangle(0, 0, this.sourceRect.width, this.sourceRect.height));
this.bitmap.texture = renderTexture;
}
}
}
+22 -20
View File
@@ -1,24 +1,26 @@
class Sprite {
public texture2D: egret.Texture;
public readonly sourceRect: Rectangle;
public readonly center: Vector2;
public origin: Vector2;
public readonly uvs: Rectangle = new Rectangle();
module es {
export class Sprite {
public texture2D: egret.Texture;
public readonly sourceRect: Rectangle;
public readonly center: Vector2;
public origin: Vector2;
public readonly uvs: Rectangle = new Rectangle();
constructor(texture: egret.Texture,
sourceRect: Rectangle = new Rectangle(0, 0, texture.textureWidth, texture.textureHeight),
origin: Vector2 = sourceRect.getHalfSize()) {
this.texture2D = texture;
this.sourceRect = sourceRect;
this.center = new Vector2(sourceRect.width * 0.5, sourceRect.height * 0.5);
this.origin = origin;
constructor(texture: egret.Texture,
sourceRect: Rectangle = new Rectangle(0, 0, texture.textureWidth, texture.textureHeight),
origin: Vector2 = sourceRect.getHalfSize()) {
this.texture2D = texture;
this.sourceRect = sourceRect;
this.center = new Vector2(sourceRect.width * 0.5, sourceRect.height * 0.5);
this.origin = origin;
let inverseTexW = 1 / texture.textureWidth;
let inverseTexH = 1 / texture.textureHeight
let inverseTexW = 1 / texture.textureWidth;
let inverseTexH = 1 / texture.textureHeight;
this.uvs.x = sourceRect.x * inverseTexW;
this.uvs.y = sourceRect.y * inverseTexH;
this.uvs.width = sourceRect.width * inverseTexW;
this.uvs.height = sourceRect.height * inverseTexH;
this.uvs.x = sourceRect.x * inverseTexW;
this.uvs.y = sourceRect.y * inverseTexH;
this.uvs.width = sourceRect.width * inverseTexW;
this.uvs.height = sourceRect.height * inverseTexH;
}
}
}
}
+9 -7
View File
@@ -1,9 +1,11 @@
class SpriteAnimation {
public readonly sprites: Sprite[];
public readonly frameRate: number;
module es {
export class SpriteAnimation {
public readonly sprites: Sprite[];
public readonly frameRate: number;
constructor(sprites: Sprite[], frameRate: number){
this.sprites = sprites;
this.frameRate = frameRate;
constructor(sprites: Sprite[], frameRate: number) {
this.sprites = sprites;
this.frameRate = frameRate;
}
}
}
}
+132 -110
View File
@@ -1,104 +1,84 @@
///<reference path="./SpriteRenderer.ts" />
class SpriteAnimator extends SpriteRenderer {
/** 在动画完成时触发,包括动画名称; */
public onAnimationCompletedEvent: Function;
/** 动画播放速度 */
public speed = 1;
/** 动画的当前状态 */
public animationState = State.none;
/** 当前动画 */
public currentAnimation: SpriteAnimation;
/** 当前动画的名称 */
public currentAnimationName: string;
/** 当前动画的精灵数组中当前帧的索引 */
public currentFrame: number;
/** 检查当前动画是否正在运行 */
public get isRunning(): boolean{
return this.animationState == State.running;
module es {
export enum LoopMode {
/** 在一个循环序列[A][B][C][A][B][C][A][B][C]... */
loop,
/** [A][B][C]然后暂停,设置时间为0 [A] */
once,
/** [A][B][C]。当它到达终点时,它会继续播放最后一帧,并且不会停止播放 */
clampForever,
/** 以一个乒乓循环的方式永远播放这个序列 [A][B][C][B][A][B][C][B]... */
pingPong,
/** 将顺序向前播放一次,然后返回到开始[A][B][C][B][A],然后暂停并设置时间为0 */
pingPongOnce,
}
private _animations: Map<string, SpriteAnimation> = new Map<string, SpriteAnimation>();
private _elapsedTime: number = 0;
private _loopMode: LoopMode;
constructor(sprite?: Sprite){
super();
if (sprite) this.setSprite(sprite);
export enum State {
none,
running,
paused,
completed,
}
/**
* SpriteAnimation
* @param name
* @param animation
*/
public addAnimation(name: string, animation: SpriteAnimation): SpriteAnimator{
if (!this.sprite && animation.sprites.length > 0)
this.setSprite(animation.sprites[0]);
this._animations[name] = animation;
return this;
}
export class SpriteAnimator extends SpriteRenderer {
/**
*
*/
public onAnimationCompletedEvent: (string) => {};
/**
*
*/
public speed = 1;
/**
*
*/
public animationState = State.none;
/**
*
*/
public currentAnimation: SpriteAnimation;
/**
*
*/
public currentAnimationName: string;
/**
*
*/
public currentFrame: number;
public _elapsedTime: number = 0;
public _loopMode: LoopMode;
/**
*
* @param name
* @param loopMode
*/
public play(name: string, loopMode: LoopMode = null){
this.currentAnimation = this._animations[name];
this.currentAnimationName = name;
this.currentFrame = 0;
this.animationState = State.running;
constructor(sprite?: Sprite) {
super(sprite);
}
this.sprite = this.currentAnimation.sprites[0];
this._elapsedTime = 0;
this._loopMode = loopMode ? loopMode : LoopMode.loop;
}
/**
*
*/
public get isRunning(): boolean {
return this.animationState == State.running;
}
/**
* ())
* @param name
*/
public isAnimationActive(name: string): boolean{
return this.currentAnimation && this.currentAnimationName == name;
}
private _animations: Map<string, SpriteAnimation> = new Map<string, SpriteAnimation>();
/**
*
*/
public pause(){
this.animationState = State.paused;
}
/** 提供对可用动画列表的访问 */
public get animations() {
return this._animations;
}
/**
*
*/
public unPause(){
this.animationState = State.running;
}
public update() {
if (this.animationState != State.running || !this.currentAnimation) return;
/**
* null
*/
public stop(){
this.currentAnimation = null;
this.currentAnimationName = null;
this.currentFrame = 0;
this.animationState = State.none;
}
let animation = this.currentAnimation;
let secondsPerFrame = 1 / (animation.frameRate * this.speed);
let iterationDuration = secondsPerFrame * animation.sprites.length;
public update(){
if (this.animationState != State.running || !this.currentAnimation) return;
this._elapsedTime += Time.deltaTime;
let time = Math.abs(this._elapsedTime);
let animation = this.currentAnimation;
let secondsPerFrame = 1 / (animation.frameRate * this.speed);
let iterationDuration = secondsPerFrame * animation.sprites.length;
this._elapsedTime += Time.deltaTime;
let time = Math.abs(this._elapsedTime);
if (this._loopMode == LoopMode.once && time > iterationDuration ||
this._loopMode == LoopMode.pingPongOnce && time > iterationDuration * 2){
// Once和PingPongOnce完成后重置为Time = 0
if (this._loopMode == LoopMode.once && time > iterationDuration ||
this._loopMode == LoopMode.pingPongOnce && time > iterationDuration * 2) {
this.animationState = State.completed;
this._elapsedTime = 0;
this.currentFrame = 0;
@@ -109,34 +89,76 @@ class SpriteAnimator extends SpriteRenderer {
// 弄清楚我们在哪个坐标系上
let i = Math.floor(time / secondsPerFrame);
let n = animation.sprites.length;
if (n > 2 && (this._loopMode == LoopMode.pingPong || this._loopMode == LoopMode.pingPongOnce)){
if (n > 2 && (this._loopMode == LoopMode.pingPong || this._loopMode == LoopMode.pingPongOnce)) {
// pingpong
let maxIndex = n - 1;
this.currentFrame = maxIndex - Math.abs(maxIndex - i % (maxIndex * 2));
}else{
} else {
this.currentFrame = i % n;
}
this.sprite = animation.sprites[this.currentFrame];
}
/**
* SpriteAnimation
* @param name
* @param animation
*/
public addAnimation(name: string, animation: SpriteAnimation): SpriteAnimator {
// 如果我们没有精灵,使用我们找到的第一帧
if (!this.sprite && animation.sprites.length > 0)
this.setSprite(animation.sprites[0]);
this._animations[name] = animation;
return this;
}
/**
*
* @param name
* @param loopMode
*/
public play(name: string, loopMode: LoopMode = null) {
this.currentAnimation = this._animations[name];
this.currentAnimationName = name;
this.currentFrame = 0;
this.animationState = State.running;
this.sprite = this.currentAnimation.sprites[0];
this._elapsedTime = 0;
this._loopMode = loopMode ? loopMode : LoopMode.loop;
}
/**
* ())
* @param name
*/
public isAnimationActive(name: string): boolean {
return this.currentAnimation && this.currentAnimationName == name;
}
/**
*
*/
public pause() {
this.animationState = State.paused;
}
/**
*
*/
public unPause() {
this.animationState = State.running;
}
/**
* null
*/
public stop() {
this.currentAnimation = null;
this.currentAnimationName = null;
this.currentFrame = 0;
this.animationState = State.none;
}
}
}
enum LoopMode {
/** 在一个循环序列[A][B][C][A][B][C][A][B][C]... */
loop,
/** [A][B][C]然后暂停,设置时间为0 [A] */
once,
/** [A][B][C]。当它到达终点时,它会继续播放最后一帧,并且不会停止播放 */
clampForever,
/** 以一个乒乓循环的方式永远播放这个序列 [A][B][C][B][A][B][C][B]... */
pingPong,
/** 将顺序向前播放一次,然后返回到开始[A][B][C][B][A],然后暂停并设置时间为0 */
pingPongOnce,
}
enum State {
none,
running,
paused,
completed,
}
+120 -51
View File
@@ -1,62 +1,131 @@
class SpriteRenderer extends RenderableComponent {
private _sprite: Sprite;
protected bitmap: egret.Bitmap;
module es {
import Bitmap = egret.Bitmap;
/** 应该由这个精灵显示的精灵 */
public get sprite(): Sprite{
return this._sprite;
}
/** 应该由这个精灵显示的精灵 */
public set sprite(value: Sprite){
this.setSprite(value);
}
public setSprite(sprite: Sprite): SpriteRenderer{
this.removeChildren();
this._sprite = sprite;
if (this._sprite) {
this.anchorOffsetX = this._sprite.origin.x / this._sprite.sourceRect.width;
this.anchorOffsetY = this._sprite.origin.y / this._sprite.sourceRect.height;
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));
}
this.bitmap = new egret.Bitmap(sprite.texture2D);
this.addChild(this.bitmap);
return this;
}
public get bounds() {
if (this._areBoundsDirty) {
if (this._sprite) {
this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, this._origin,
this.entity.transform.scale, this.entity.transform.rotation, this._sprite.sourceRect.width,
this._sprite.sourceRect.height);
this._areBoundsDirty = false;
}
}
public setColor(color: number): SpriteRenderer{
let colorMatrix = [
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0
];
colorMatrix[0] = Math.floor(color / 256 / 256) / 255;
colorMatrix[6] = Math.floor(color / 256 % 256) / 255;
colorMatrix[12] = color % 256 / 255;
let colorFilter = new egret.ColorMatrixFilter(colorMatrix);
this.filters = [colorFilter];
return this._bounds;
}
return this;
}
/**
*
* x/y 0-1
*/
public get originNormalized(): Vector2 {
return new Vector2(this._origin.x / this.width * this.entity.transform.scale.x,
this._origin.y / this.height * this.entity.transform.scale.y);
}
public isVisibleFromCamera(camera: Camera): boolean{
this.isVisible = new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight).intersects(this.bounds);
this.visible = this.isVisible;
return this.isVisible;
}
/**
*
* x/y 0-1
* @param value
*/
public set originNormalized(value: Vector2) {
this.setOrigin(new Vector2(value.x * this.width / this.entity.transform.scale.x,
value.y * this.height / this.entity.transform.scale.y));
}
/** 渲染处理 在每个模块中处理各自的渲染逻辑 */
public render(camera: Camera){
this.x = -camera.position.x + camera.origin.x;
this.y = -camera.position.y + camera.origin.y;
}
protected _origin: Vector2;
public onRemovedFromEntity(){
if (this.parent)
this.parent.removeChild(this);
}
/**
*
*/
public get origin(): Vector2 {
return this._origin;
}
public reset(){
/**
*
* @param value
*/
public set origin(value: Vector2) {
this.setOrigin(value);
}
protected _sprite: Sprite;
/**
*
* origin
*/
public get sprite(): Sprite {
return this._sprite;
}
/**
*
* origin
* @param value
*/
public set sprite(value: Sprite) {
this.setSprite(value);
}
/**
* sprite.origin
* @param sprite
*/
public setSprite(sprite: Sprite): SpriteRenderer {
this._sprite = sprite;
if (this._sprite) {
this._origin = this._sprite.origin;
this.displayObject.anchorOffsetX = this._origin.x;
this.displayObject.anchorOffsetY = this._origin.y;
}
this.displayObject = new Bitmap(sprite.texture2D);
return this;
}
/**
*
* @param origin
*/
public setOrigin(origin: Vector2): SpriteRenderer {
if (this._origin != origin) {
this._origin = origin;
this.displayObject.anchorOffsetX = this._origin.x;
this.displayObject.anchorOffsetY = this._origin.y;
this._areBoundsDirty = true;
}
return this;
}
/**
*
* x/y 0-1
* @param value
*/
public setOriginNormalized(value: Vector2): SpriteRenderer {
this.setOrigin(new Vector2(value.x * this.width / this.entity.transform.scale.x,
value.y * this.height / this.entity.transform.scale.y));
return this;
}
public render(camera: Camera) {
this.sync(camera);
this.displayObject.x = this.entity.position.x - this.origin.x + this.localOffset.x - camera.position.x + camera.origin.x;
this.displayObject.y = this.entity.position.y - this.origin.y + this.localOffset.y - camera.position.y + camera.origin.y;
}
}
}
+110 -54
View File
@@ -1,57 +1,113 @@
///<reference path="./SpriteRenderer.ts" />
/**
*
*/
class TiledSpriteRenderer extends SpriteRenderer {
protected sourceRect: Rectangle;
protected leftTexture: egret.Bitmap;
protected rightTexture: egret.Bitmap;
module es {
import Bitmap = egret.Bitmap;
public get scrollX() {
return this.sourceRect.x;
/**
*
*/
export class TiledSpriteRenderer extends SpriteRenderer {
public get bounds(): Rectangle {
if (this._areBoundsDirty){
if (this._sprite){
this._bounds.calculateBounds(this.entity.transform.position, this._localOffset, this._origin,
this.entity.transform.scale, this.entity.transform.rotation, this.width, this.height);
this._areBoundsDirty = false;
}
}
return this._bounds;
}
/**
* x值
*/
public get scrollX() {
return this._sourceRect.x;
}
/**
* x值
* @param value
*/
public set scrollX(value: number) {
this._sourceRect.x = value;
}
/**
* y值
*/
public get scrollY() {
return this._sourceRect.y;
}
/**
* y值
* @param value
*/
public set scrollY(value: number) {
this._sourceRect.y = value;
}
/**
*
*/
public get textureScale(): Vector2 {
return this._textureScale;
}
/**
*
* @param value
*/
public set textureScale(value: Vector2) {
this._textureScale = value;
// 重新计算我们的inverseTextureScale和源矩形大小
this._inverseTexScale = new Vector2(1 / this._textureScale.x, 1 / this._textureScale.y);
this._sourceRect.width = this._sprite.sourceRect.width * this._inverseTexScale.x;
this._sourceRect.height = this._sprite.sourceRect.height * this._inverseTexScale.y;
}
/**
* TiledSprite可以有一个独立于其纹理的宽度
*/
public get width(): number{
return this._sourceRect.width;
}
public set width(value: number) {
this._areBoundsDirty = true;
this._sourceRect.width = value;
}
public get height(): number {
return this._sourceRect.height;
}
public set height(value: number) {
this._areBoundsDirty = true;
this._sourceRect.height = value;
}
protected _sourceRect: Rectangle = new Rectangle();
protected _textureScale = Vector2.one;
protected _inverseTexScale = Vector2.one;
constructor(sprite: Sprite) {
super(sprite);
this._sourceRect = sprite.sourceRect;
let bitmap = this.displayObject as Bitmap;
bitmap.$fillMode = egret.BitmapFillMode.REPEAT;
}
public render(camera: es.Camera) {
let bitmap = this.displayObject as Bitmap;
bitmap.width = this.width;
bitmap.height = this.height;
super.render(camera);
}
}
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) {
super();
this.leftTexture = new egret.Bitmap();
this.rightTexture = new egret.Bitmap();
this.leftTexture.texture = sprite.texture2D;
this.rightTexture.texture = sprite.texture2D;
this.setSprite(sprite);
this.sourceRect = sprite.sourceRect;
}
public render(camera: Camera) {
if (!this.sprite)
return;
super.render(camera);
let renderTexture = new egret.RenderTexture();
let cacheBitmap = new egret.DisplayObjectContainer();
cacheBitmap.removeChildren();
cacheBitmap.addChild(this.leftTexture);
cacheBitmap.addChild(this.rightTexture);
this.leftTexture.x = this.sourceRect.x;
this.rightTexture.x = this.sourceRect.x - this.sourceRect.width;
this.leftTexture.y = this.sourceRect.y;
this.rightTexture.y = this.sourceRect.y;
cacheBitmap.cacheAsBitmap = true;
renderTexture.drawToTexture(cacheBitmap, new egret.Rectangle(0, 0, this.sourceRect.width, this.sourceRect.height));
this.bitmap.texture = renderTexture;
}
}
}
+230
View File
@@ -0,0 +1,230 @@
module es {
/**
*
*/
export class Core extends egret.DisplayObjectContainer {
/**
*
*/
public static emitter: Emitter<CoreEvents>;
/**
* 访
*/
public static graphicsDevice: GraphicsDevice;
/**
*
*/
public static content: ContentManager;
/**
* 访
*/
public static _instance: Core;
public _nextScene: Scene;
public _sceneTransition: SceneTransition;
/**
* 访
*/
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;
/**
*
*/
public static get scene() {
if (!this._instance)
return null;
return this._instance._scene;
}
/**
*
* @param value
*/
public static set scene(value: Scene) {
if (!value) {
console.error("场景不能为空");
return;
}
if (this._instance._scene == null) {
this._instance._scene = value;
this._instance.addChild(value);
this._instance._scene.begin();
Core.Instance.onSceneChanged();
} else {
this._instance._nextScene = value;
}
}
/**
* 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;
}
public onOrientationChanged() {
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() {
Core.emitter.emit(CoreEvents.GraphicsDeviceReset);
}
protected initialize() {
}
protected async update() {
// this.startDebugUpdate();
// 更新我们所有的系统管理器
Time.update(egret.getTimer());
if (this._scene) {
for (let i = this._globalManagers.length - 1; i >= 0; i--) {
if (this._globalManagers[i].enabled)
this._globalManagers[i].update();
}
// 仔细阅读:
// 当场景转换发生时,我们不会更新场景
// -除非是不改变场景的场景转换(没有理由不更新)
// -或者它是一个已经切换到新场景的场景转换(新场景需要做它自己的事情)
if (!this._sceneTransition ||
(this._sceneTransition && (!this._sceneTransition.loadsNewScene || this._sceneTransition.isNewSceneLoaded))) {
this._scene.update();
}
if (this._nextScene) {
this.removeChild(this._scene);
this._scene.end();
this._scene = this._nextScene;
this._nextScene = null;
this.onSceneChanged();
this.addChild(this._scene);
await this._scene.begin();
}
}
// this.endDebugUpdate();
await this.draw();
}
private onAddToStage() {
Core.graphicsDevice = new GraphicsDevice();
this.addEventListener(egret.Event.RESIZE, this.onGraphicsDeviceReset, this);
this.addEventListener(egret.StageOrientationEvent.ORIENTATION_CHANGE, this.onOrientationChanged, this);
this.addEventListener(egret.Event.ENTER_FRAME, this.update, this);
Input.initialize();
this.initialize();
}
}
}
+16
View File
@@ -0,0 +1,16 @@
module es {
export enum CoreEvents {
/**
* VRAM将被擦除
*/
GraphicsDeviceReset,
/**
*
*/
SceneChanged,
/**
*
*/
OrientationChanged,
}
}
+396 -183
View File
@@ -1,223 +1,436 @@
class Entity extends egret.DisplayObjectContainer {
private static _idGenerator: number;
module es {
export class Entity {
public static _idGenerator: number;
public name: string;
public readonly id: number;
/** 当前实体所属的场景 */
public scene: Scene;
/** 当前附加到此实体的所有组件的列表 */
public readonly components: ComponentList;
private _updateOrder: number = 0;
private _enabled: boolean = true;
public _isDestoryed: boolean;
private _tag: number = 0;
/**
*
*/
public scene: Scene;
/**
*
*/
public name: string;
/**
*
*/
public readonly id: number;
/**
* //
*/
public readonly transform: Transform;
/**
*
*/
public readonly components: ComponentList;
/**
* entity update方法的频率12
*/
public updateInterval: number = 1;
public componentBits: BitSet;
public componentBits: BitSet;
constructor(name: string) {
this.components = new ComponentList(this);
this.transform = new Transform(this);
this.name = name;
this.id = Entity._idGenerator++;
public get isDestoryed(){
return this._isDestoryed;
}
public get position(){
return new Vector2(this.x, this.y);
}
public set position(value: Vector2){
this.$setX(value.x);
this.$setY(value.y);
this.onEntityTransformChanged(TransformComponent.position);
}
public get scale(){
return new Vector2(this.scaleX, this.scaleY);
}
public set scale(value: Vector2){
this.$setScaleX(value.x);
this.$setScaleY(value.y);
this.onEntityTransformChanged(TransformComponent.scale);
}
public set rotation(value: number){
this.$setRotation(value);
this.onEntityTransformChanged(TransformComponent.rotation);
}
public get enabled(){
return this._enabled;
}
public set enabled(value: boolean){
this.setEnabled(value);
}
public setEnabled(isEnabled: boolean){
if (this._enabled != isEnabled){
this._enabled = isEnabled;
this.componentBits = new BitSet();
}
return this;
}
public _isDestroyed: boolean;
public get tag(){
return this._tag;
}
/**
* destroytrue
*/
public get isDestroyed() {
return this._isDestroyed;
}
public set tag(value: number){
this.setTag(value);
}
private _tag: number = 0;
public get stage(){
if (!this.scene)
return null;
return this.scene.stage;
}
/**
* 使使
*/
public get tag(): number {
return this._tag;
}
constructor(name: string){
super();
this.name = name;
this.components = new ComponentList(this);
this.id = Entity._idGenerator ++;
/**
* 使使
* @param value
*/
public set tag(value: number) {
this.setTag(value);
}
this.componentBits = new BitSet();
}
private _enabled: boolean = true;
public get updateOrder(){
return this._updateOrder;
}
/**
* /
*/
public get enabled() {
return this._enabled;
}
public set updateOrder(value: number){
this.setUpdateOrder(value);
}
/**
* /
* @param value
*/
public set enabled(value: boolean) {
this.setEnabled(value);
}
public roundPosition(){
this.position = Vector2Ext.round(this.position);
}
private _updateOrder: number = 0;
public setUpdateOrder(updateOrder: number){
if (this._updateOrder != updateOrder){
this._updateOrder = updateOrder;
if (this.scene){
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
*/
public get updateOrder() {
return this._updateOrder;
}
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
* @param value
*/
public set updateOrder(value: number) {
this.setUpdateOrder(value);
}
public get parent(): Transform {
return this.transform.parent;
}
public set parent(value: Transform) {
this.transform.setParent(value);
}
public get childCount() {
return this.transform.childCount;
}
public get position(): Vector2 {
return this.transform.position;
}
public set position(value: Vector2) {
this.transform.setPosition(value.x, value.y);
}
public get localPosition(): Vector2 {
return this.transform.localPosition;
}
public set localPosition(value: Vector2) {
this.transform.setLocalPosition(value);
}
public get rotation(): number {
return this.transform.rotation;
}
public set rotation(value: number) {
this.transform.setRotation(value);
}
public get rotationDegrees(): number {
return this.transform.rotationDegrees;
}
public set rotationDegrees(value: number) {
this.transform.setRotationDegrees(value);
}
public get localRotation(): number {
return this.transform.localRotation;
}
public set localRotation(value: number) {
this.transform.setLocalRotation(value);
}
public get localRotationDegrees(): number {
return this.transform.localRotationDegrees;
}
public set localRotationDegrees(value: number) {
this.transform.setLocalRotationDegrees(value);
}
public get scale(): Vector2 {
return this.transform.scale;
}
public set scale(value: Vector2) {
this.transform.setScale(value);
}
public get localScale(): Vector2 {
return this.transform.localScale;
}
public set localScale(value: Vector2) {
this.transform.setLocalScale(value);
}
public get worldInverseTransform(): Matrix2D {
return this.transform.worldInverseTransform;
}
public get localToWorldTransform(): Matrix2D {
return this.transform.localToWorldTransform;
}
public get worldToLocalTransform(): Matrix2D {
return this.transform.worldToLocalTransform;
}
public onTransformChanged(comp: transform.Component) {
// 通知我们的子项改变了位置
this.components.onEntityTransformChanged(comp);
}
/**
*
* @param tag
*/
public setTag(tag: number): Entity {
if (this._tag != tag) {
// 我们只有在已经有场景的情况下才会调用entityTagList。如果我们还没有场景,我们会被添加到entityTagList
if (this.scene)
this.scene.entities.removeFromTagList(this);
this._tag = tag;
if (this.scene)
this.scene.entities.addToTagList(this);
}
return this;
}
}
public setTag(tag: number): Entity{
if (this._tag != tag){
if (this.scene){
this.scene.entities.removeFromTagList(this);
/**
*
* @param isEnabled
*/
public setEnabled(isEnabled: boolean) {
if (this._enabled != isEnabled) {
this._enabled = isEnabled;
if (this._enabled)
this.components.onEntityEnabled();
else
this.components.onEntityDisabled();
}
this._tag = tag;
if (this.scene){
this.scene.entities.addToTagList(this);
return this;
}
/**
* updateOrder还用于对scene.entities上的标签列表进行排序
* @param updateOrder
*/
public setUpdateOrder(updateOrder: number) {
if (this._updateOrder != updateOrder) {
this._updateOrder = updateOrder;
if (this.scene) {
this.scene.entities.markEntityListUnsorted();
this.scene.entities.markTagUnsorted(this.tag);
}
return this;
}
}
return this;
}
/**
*
*/
public destroy() {
this._isDestroyed = true;
this.scene.entities.remove(this);
this.transform.parent = null;
public attachToScene(newScene: Scene){
this.scene = newScene;
newScene.entities.add(this);
this.components.registerAllComponents();
for (let i = 0; i < this.numChildren; i ++){
(this.getChildAt(i) as Component).entity.attachToScene(newScene);
}
}
public detachFromScene(){
this.scene.entities.remove(this);
this.components.deregisterAllComponents();
for (let i = 0; i < this.numChildren; i ++)
(this.getChildAt(i) as Component).entity.detachFromScene();
}
public addComponent<T extends Component>(component: T): T{
component.entity = this;
this.components.add(component);
this.addChild(component);
component.initialize();
return component;
}
public hasComponent<T extends Component>(type){
return this.components.getComponent<T>(type, false) != null;
}
public getOrCreateComponent<T extends Component>(type: T){
let comp = this.components.getComponent<T>(type, true);
if (!comp){
comp = this.addComponent<T>(type);
// 销毁所有子项
for (let i = this.transform.childCount - 1; i >= 0; i--) {
let child = this.transform.getChild(i);
child.entity.destroy();
}
}
return comp;
}
/**
* 下面的生命周期方法将被调用在组件上:OnRemovedFromEntity
*/
public detachFromScene() {
this.scene.entities.remove(this);
this.components.deregisterAllComponents();
public getComponent<T extends Component>(type): T{
return this.components.getComponent(type, false) as T;
}
public getComponents(typeName: string | any, componentList?){
return this.components.getComponents(typeName, componentList);
}
private onEntityTransformChanged(comp: TransformComponent){
this.components.onEntityTransformChanged(comp);
}
public removeComponentForType<T extends Component>(type){
let comp = this.getComponent<T>(type);
if (comp){
this.removeComponent(comp);
return true;
for (let i = 0; i < this.transform.childCount; i++)
this.transform.getChild(i).entity.detachFromScene();
}
return false;
}
/**
*
* @param newScene
*/
public attachToScene(newScene: Scene) {
this.scene = newScene;
newScene.entities.add(this);
this.components.registerAllComponents();
public removeComponent(component: Component){
this.components.remove(component);
}
public removeAllComponents(){
for (let i = 0; i < this.components.count; i ++){
this.removeComponent(this.components.buffer[i]);
for (let i = 0; i < this.transform.childCount; i++) {
this.transform.getChild(i).entity.attachToScene(newScene);
}
}
}
public update(){
this.components.update();
}
/**
*
* CopyFrom方法
* !!
* @param position
*/
public clone(position: Vector2 = new Vector2()): Entity {
let entity = new Entity(this.name + "(clone)");
entity.copyFrom(this);
entity.transform.position = position;
public onAddedToScene(){
return entity;
}
}
/**
*
*/
public onAddedToScene() {
}
public onRemovedFromScene(){
if (this._isDestoryed)
this.components.removeAllComponents();
}
/**
*
*/
public onRemovedFromScene() {
// 如果已经被销毁了,移走我们的组件。如果我们只是分离,我们需要保持我们的组件在实体上。
if (this._isDestroyed)
this.components.removeAllComponents();
}
public destroy(){
this._isDestoryed = true;
this.scene.entities.remove(this);
this.removeChildren();
/**
*
*/
public update() {
this.components.update();
}
for (let i = this.numChildren - 1; i >= 0; i --){
let child = this.getChildAt(i);
(child as Component).entity.destroy();
/**
*
* @param component
*/
public addComponent<T extends Component>(component: T): T {
component.entity = this;
this.components.add(component);
component.initialize();
return component;
}
/**
* T的第一个组件并返回它null
* @param type
*/
public getComponent<T extends Component>(type): T {
return this.components.getComponent(type, false) as T;
}
/**
*
* @param type
*/
public hasComponent<T extends Component>(type) {
return this.components.getComponent<T>(type, false) != null;
}
/**
* T的第一个组件并返回它
* @param type
*/
public getOrCreateComponent<T extends Component>(type: T) {
let comp = this.components.getComponent<T>(type, true);
if (!comp) {
comp = this.addComponent<T>(type);
}
return comp;
}
/**
* typeName类型的所有组件使
* @param typeName
* @param componentList
*/
public getComponents(typeName: string | any, componentList?) {
return this.components.getComponents(typeName, componentList);
}
/**
*
* @param component
*/
public removeComponent(component: Component) {
this.components.remove(component);
}
/**
* T的第一个组件
* @param type
*/
public removeComponentForType<T extends Component>(type) {
let comp = this.getComponent<T>(type);
if (comp) {
this.removeComponent(comp);
return true;
}
return false;
}
/**
*
*/
public removeAllComponents() {
for (let i = 0; i < this.components.count; i++) {
this.removeComponent(this.components.buffer[i]);
}
}
public compareTo(other: Entity): number {
let compare = this._updateOrder - other._updateOrder;
if (compare == 0)
compare = this.id - other.id;
return compare;
}
public toString(): string {
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;
}
}
}
}
enum TransformComponent {
rotation,
scale,
position
}
+337 -195
View File
@@ -1,213 +1,355 @@
/** 场景 */
class Scene extends egret.DisplayObjectContainer {
public camera: Camera;
public readonly entities: EntityList;
public readonly renderableComponents: RenderableComponentList;
public readonly content: ContentManager;
public enablePostProcessing = true;
module es {
/** 场景 */
export class Scene extends egret.DisplayObjectContainer {
/**
*
*/
public camera: Camera;
/**
* 使/使SceneManager.content
* contentManager来加载它们Nez不会卸载它们
*/
public readonly content: ContentManager;
/**
*
*/
public enablePostProcessing = true;
/**
*
*/
public readonly entities: EntityList;
/**
*
*/
public readonly renderableComponents: RenderableComponentList;
/**
*
*/
public readonly entityProcessors: EntityProcessorList;
private _renderers: Renderer[] = [];
private _postProcessors: PostProcessor[] = [];
private _didSceneBegin;
public _renderers: Renderer[] = [];
public readonly _postProcessors: PostProcessor[] = [];
public _didSceneBegin;
public readonly entityProcessors: EntityProcessorList;
constructor() {
super();
this.entities = new EntityList(this);
this.renderableComponents = new RenderableComponentList();
this.content = new ContentManager();
constructor() {
super();
this.entityProcessors = new EntityProcessorList();
this.renderableComponents = new RenderableComponentList();
this.entities = new EntityList(this);
this.content = new ContentManager();
this.width = SceneManager.stage.stageWidth;
this.height = SceneManager.stage.stageHeight;
this.entityProcessors = new EntityProcessorList();
this.addEventListener(egret.Event.ACTIVATE, this.onActive, this);
this.addEventListener(egret.Event.DEACTIVATE, this.onDeactive, this);
}
this.initialize();
}
public createEntity(name: string) {
let entity = new Entity(name);
entity.position = new Vector2(0, 0);
return this.addEntity(entity);
}
/**
* DefaultRenderer附加并准备使用
*/
public static createWithDefaultRenderer() {
let scene = new Scene();
scene.addRenderer(new DefaultRenderer());
return scene;
}
public addEntity(entity: Entity) {
this.entities.add(entity);
entity.scene = this;
this.addChild(entity);
/**
* begin之前
*/
public initialize() {
}
for (let i = 0; i < entity.numChildren; i++)
this.addEntity((entity.getChildAt(i) as Component).entity);
/**
* SceneManager将此场景设置为活动场景时
*/
public async onStart() {
}
return entity;
}
/**
* SceneManager从活动槽中删除此场景时调用
*/
public unload() {
}
public destroyAllEntities() {
for (let i = 0; i < this.entities.count; i++) {
this.entities.buffer[i].destroy();
}
}
public findEntity(name: string): Entity {
return this.entities.findEntity(name);
}
/**
*
*/
public onActive() {
}
/**
* EntitySystem处理器
* @param processor
*/
public addEntityProcessor(processor: EntitySystem) {
processor.scene = this;
this.entityProcessors.add(processor);
return processor;
}
/**
*
*/
public onDeactive() {
}
public removeEntityProcessor(processor: EntitySystem) {
this.entityProcessors.remove(processor);
}
public getEntityProcessor<T extends EntitySystem>(): T {
return this.entityProcessors.getProcessor<T>();
}
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
renderer.onAddedToScene(this);
return renderer;
}
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;
}
public removeRenderer(renderer: Renderer) {
this._renderers.remove(renderer);
renderer.unload();
}
public begin() {
if (SceneManager.sceneTransition){
SceneManager.stage.addChildAt(this, SceneManager.stage.numChildren - 1);
}else{
SceneManager.stage.addChild(this);
}
if (this._renderers.length == 0) {
this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
}
/** 初始化默认相机 */
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
Physics.reset();
if (this.entityProcessors)
this.entityProcessors.begin();
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();
Physics.clear();
this.camera = null;
this.content.dispose();
if (this.entityProcessors)
this.entityProcessors.end();
this.unload();
if (this.parent)
this.parent.removeChild(this);
}
protected async onStart() {
}
/** 场景激活 */
protected onActive() {
}
/** 场景失去焦点 */
protected onDeactive() {
}
protected 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 postRender() {
let enabledCounter = 0;
if (this.enablePostProcessing) {
for (let i = 0; i < this._postProcessors.length; i++) {
if (this._postProcessors[i].enable) {
let isEven = MathHelper.isEven(enabledCounter);
enabledCounter ++;
this._postProcessors[i].process();
public async begin() {
if (this._renderers.length == 0) {
this.addRenderer(new DefaultRenderer());
console.warn("场景开始时没有渲染器 自动添加DefaultRenderer以保证能够正常渲染");
}
}
}
}
public render() {
for (let i = 0; i < this._renderers.length; i++) {
this._renderers[i].render(this);
}
}
this.camera = this.createEntity("camera").getOrCreateComponent(new Camera());
public addPostProcessor<T extends PostProcessor>(postProcessor: T): T{
this._postProcessors.push(postProcessor);
this._postProcessors.sort();
postProcessor.onAddedToScene(this);
Physics.reset();
if (this._didSceneBegin){
postProcessor.onSceneBackBufferSizeChanged(this.stage.stageWidth, this.stage.stageHeight);
}
if (this.entityProcessors)
this.entityProcessors.begin();
return postProcessor;
}
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();
}
}
}
}
/**
*
* @param renderer
*/
public addRenderer<T extends Renderer>(renderer: T) {
this._renderers.push(renderer);
this._renderers.sort();
renderer.onAddedToScene(this);
return renderer;
}
/**
* T的第一个渲染器
* @param type
*/
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>();
}
}
}
-101
View File
@@ -1,101 +0,0 @@
/** 运行时的场景管理。 */
class SceneManager {
private static _scene: Scene;
private static _nextScene: Scene;
public static sceneTransition: SceneTransition;
public static stage: egret.Stage;
constructor(stage: egret.Stage) {
stage.addEventListener(egret.Event.ENTER_FRAME, SceneManager.update, this);
SceneManager.stage = stage;
SceneManager.initialize(stage);
}
public static get scene() {
return this._scene;
}
public static set scene(value: Scene) {
if (!value)
throw new Error("场景不能为空");
if (this._scene == null) {
this._scene = value;
this._scene.begin();
} else {
this._nextScene = value;
}
}
public static initialize(stage: egret.Stage) {
Input.initialize(stage);
}
public static update() {
Time.update(egret.getTimer());
if (SceneManager._scene) {
for (let i = GlobalManager.globalManagers.length - 1; i >= 0; i--) {
if (GlobalManager.globalManagers[i].enabled)
GlobalManager.globalManagers[i].update();
}
if (!SceneManager.sceneTransition ||
(SceneManager.sceneTransition && (!SceneManager.sceneTransition.loadsNewScene || SceneManager.sceneTransition.isNewSceneLoaded))) {
SceneManager._scene.update();
}
if (SceneManager._nextScene) {
SceneManager._scene.end();
for (let i = 0; i < SceneManager._scene.entities.buffer.length; i++) {
let entity = SceneManager._scene.entities.buffer[i];
entity.destroy();
}
SceneManager._scene = SceneManager._nextScene;
SceneManager._nextScene = null;
SceneManager._scene.begin();
}
}
SceneManager.render();
}
public static render() {
if (this.sceneTransition){
this.sceneTransition.preRender();
if (this._scene && !this.sceneTransition.hasPreviousSceneRender){
this._scene.render();
this._scene.postRender();
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();
this._scene.postRender();
}
}
/**
* SceneTransition
* @param sceneTransition
*/
public static startSceneTransition<T extends SceneTransition>(sceneTransition: T): T {
if (this.sceneTransition) {
console.warn("在前一个场景完成之前,不能开始一个新的场景转换。");
return;
}
this.sceneTransition = sceneTransition;
return sceneTransition;
}
}
@@ -1,32 +1,34 @@
///<reference path="./EntitySystem.ts" />
/**
*
*/
abstract class EntityProcessingSystem extends EntitySystem {
constructor(matcher: Matcher) {
super(matcher);
}
module es {
/**
*
* @param entity
*
*/
public abstract processEntity(entity: Entity);
export abstract class EntityProcessingSystem extends EntitySystem {
constructor(matcher: Matcher) {
super(matcher);
}
public lateProcessEntity(entity: Entity) {
/**
*
* @param entity
*/
public abstract processEntity(entity: Entity);
public lateProcessEntity(entity: Entity) {
}
/**
*
* @param entities
*/
protected process(entities: Entity[]) {
entities.forEach(entity => this.processEntity(entity));
}
protected lateProcess(entities: Entity[]) {
entities.forEach(entity => this.lateProcessEntity(entity));
}
}
/**
*
* @param entities
*/
protected process(entities: Entity[]) {
entities.forEach(entity => this.processEntity(entity));
}
protected lateProcess(entities: Entity[]) {
entities.forEach(entity => this.lateProcessEntity(entity));
}
}
}
+81 -77
View File
@@ -1,79 +1,83 @@
class EntitySystem {
private _scene: Scene;
private _entities: Entity[] = [];
private _matcher: Matcher;
module es {
export class EntitySystem {
private _entities: Entity[] = [];
public get matcher(){
return this._matcher;
constructor(matcher?: Matcher) {
this._matcher = matcher ? matcher : Matcher.empty();
}
private _scene: Scene;
public get scene() {
return this._scene;
}
public set scene(value: Scene) {
this._scene = value;
this._entities = [];
}
private _matcher: Matcher;
public get matcher() {
return this._matcher;
}
public initialize() {
}
public onChanged(entity: Entity) {
let contains = this._entities.contains(entity);
let interest = this._matcher.IsIntersted(entity);
if (interest && !contains)
this.add(entity);
else if (!interest && contains)
this.remove(entity);
}
public add(entity: Entity) {
this._entities.push(entity);
this.onAdded(entity);
}
public onAdded(entity: Entity) {
}
public remove(entity: Entity) {
this._entities.remove(entity);
this.onRemoved(entity);
}
public onRemoved(entity: Entity) {
}
public update() {
this.begin();
this.process(this._entities);
}
public lateUpdate() {
this.lateProcess(this._entities);
this.end();
}
protected begin() {
}
protected process(entities: Entity[]) {
}
protected lateProcess(entities: Entity[]) {
}
protected end() {
}
}
public get scene(){
return this._scene;
}
public set scene(value: Scene){
this._scene = value;
this._entities = [];
}
constructor(matcher?: Matcher){
this._matcher = matcher ? matcher : Matcher.empty();
}
public initialize(){
}
public onChanged(entity: Entity){
let contains = this._entities.contains(entity);
let interest = this._matcher.IsIntersted(entity);
if (interest && !contains)
this.add(entity);
else if(!interest && contains)
this.remove(entity);
}
public add(entity: Entity){
this._entities.push(entity);
this.onAdded(entity);
}
public onAdded(entity: Entity){
}
public remove(entity: Entity){
this._entities.remove(entity);
this.onRemoved(entity);
}
public onRemoved(entity: Entity){
}
public update(){
this.begin();
this.process(this._entities);
}
public lateUpdate(){
this.lateProcess(this._entities);
this.end();
}
protected begin(){
}
protected process(entities: Entity[]){
}
protected lateProcess(entities: Entity[]){
}
protected end(){
}
}
}
+10 -8
View File
@@ -1,11 +1,13 @@
abstract class PassiveSystem extends EntitySystem {
public onChanged(entity: Entity){
module es {
export abstract class PassiveSystem extends EntitySystem {
public onChanged(entity: Entity) {
}
}
protected process(entities: Entity[]){
// 我们用我们自己的不考虑实体的基本实体系统来代替
this.begin();
this.end();
protected process(entities: Entity[]) {
// 我们用我们自己的不考虑实体的基本实体系统来代替
this.begin();
this.end();
}
}
}
}
+14 -12
View File
@@ -1,15 +1,17 @@
/** 用于协调其他系统的通用系统基类 */
abstract class ProcessingSystem extends EntitySystem {
public onChanged(entity: Entity){
module es {
export abstract class ProcessingSystem extends EntitySystem {
public onChanged(entity: Entity) {
}
/** 处理我们的系统 每帧调用 */
public abstract processSystem();
protected process(entities: Entity[]) {
this.begin();
this.processSystem();
this.end();
}
}
protected process(entities: Entity[]){
this.begin();
this.processSystem();
this.end();
}
/** 处理我们的系统 每帧调用 */
public abstract processSystem();
}
}
+507
View File
@@ -0,0 +1,507 @@
module transform {
export enum Component {
position,
scale,
rotation,
}
}
module es {
import HashObject = egret.HashObject;
export enum DirtyType {
clean,
positionDirty,
scaleDirty,
rotationDirty,
}
export class Transform extends HashObject {
/** 与此转换关联的实体 */
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;
/**
*
*/
public get parent() {
return this._parent;
}
/**
*
* @param value
*/
public set parent(value: Transform) {
this.setParent(value);
}
public _worldToLocalTransform = Matrix2D.create().identity();
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 _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 {
this.updateTransform();
if (this._positionDirty) {
if (!this.parent) {
this._position = this._localPosition;
} else {
this.parent.updateTransform();
this._position = Vector2Ext.transformR(this._localPosition, this.parent._worldTransform);
}
this._positionDirty = false;
}
return this._position;
}
/**
*
* @param value
*/
public set position(value: Vector2) {
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相同
*/
public get localPosition(): Vector2 {
this.updateTransform();
return this._localPosition;
}
/**
* transform.position相同
* @param value
*/
public set localPosition(value: Vector2) {
this.setLocalPosition(value);
}
public _localScale: Vector2 = Vector2.one;
/**
* transform.scale相同
*/
public get localScale(): Vector2 {
this.updateTransform();
return this._localScale;
}
/**
* transform.scale相同
* @param value
*/
public set localScale(value: Vector2) {
this.setLocalScale(value);
}
public _localRotation: number = 0;
/**
* transform.rotation相同
*/
public get localRotation(): number {
this.updateTransform();
return this._localRotation;
}
/**
* transform.rotation相同
* @param value
*/
public set localRotation(value: number) {
this.setLocalRotation(value);
}
/**
*
* @param index
*/
public getChild(index: number): Transform {
return this._children[index];
}
/**
*
* @param parent
*/
public setParent(parent: Transform): Transform {
if (this._parent.equals(parent))
return this;
if (!this._parent) {
this._parent._children.remove(this);
this._parent._children.push(this);
}
this._parent = parent;
this.setDirty(DirtyType.positionDirty);
return this;
}
/**
*
* @param x
* @param y
*/
public setPosition(x: number, y: number): Transform {
let position = new Vector2(x, y);
if (position.equals(this._position))
return this;
this._position = position;
if (this.parent) {
this.localPosition = Vector2Ext.transformR(this._position, this._worldToLocalTransform);
} else {
this.localPosition = position;
}
this._positionDirty = false;
return this;
}
/**
* transform.position相同
* @param localPosition
*/
public setLocalPosition(localPosition: Vector2): Transform {
if (localPosition.equals(this._localPosition))
return this;
this._localPosition = localPosition;
this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.positionDirty);
return this;
}
/**
*
* @param radians
*/
public setRotation(radians: number): Transform {
this._rotation = radians;
if (this.parent) {
this.localRotation = this.parent.rotation + radians;
} else {
this.localRotation = radians;
}
return this;
}
/**
*
* @param degrees
*/
public setRotationDegrees(degrees: number): Transform {
return this.setRotation(MathHelper.toRadians(degrees));
}
/**
* 使
* @param pos
*/
public lookAt(pos: Vector2) {
let sign = this.position.x > pos.x ? -1 : 1;
let vectorToAlignTo = Vector2.normalize(Vector2.subtract(this.position, pos));
this.rotation = sign * Math.acos(Vector2.dot(vectorToAlignTo, Vector2.unitY));
}
/**
* transform.rotation相同
* @param radians
*/
public setLocalRotation(radians: number) {
this._localRotation = radians;
this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.rotationDirty);
return this;
}
/**
* transform.rotation相同
* @param degrees
*/
public setLocalRotationDegrees(degrees: number): Transform {
return this.setLocalRotation(MathHelper.toRadians(degrees));
}
/**
*
* @param scale
*/
public setScale(scale: Vector2): Transform {
this._scale = scale;
if (this.parent) {
this.localScale = Vector2.divide(scale, this.parent._scale);
} else {
this.localScale = scale;
}
return this;
}
/**
* transform.scale相同
* @param scale
*/
public setLocalScale(scale: Vector2): Transform {
this._localScale = scale;
this._localDirty = this._positionDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.scaleDirty);
return this;
}
/**
*
*/
public roundPosition() {
this.position = this._position.round();
}
public updateTransform() {
if (this.hierarchyDirty != DirtyType.clean) {
if (this.parent)
this.parent.updateTransform();
if (this._localDirty) {
if (this._localPositionDirty) {
this._translationMatrix = Matrix2D.create().translate(this._localPosition.x, this._localPosition.y);
this._localPositionDirty = false;
}
if (this._localRotationDirty) {
this._rotationMatrix = Matrix2D.create().rotate(this._localRotation);
this._localRotationDirty = false;
}
if (this._localScaleDirty) {
this._scaleMatrix = Matrix2D.create().scale(this._localScale.x, this._localScale.y);
this._localScaleDirty = false;
}
this._localTransform = this._scaleMatrix.multiply(this._rotationMatrix);
this._localTransform = this._localTransform.multiply(this._translationMatrix);
if (!this.parent) {
this._worldTransform = this._localTransform;
this._rotation = this._localRotation;
this._scale = this._localScale;
this._worldInverseDirty = true;
}
this._localDirty = false;
}
if (this.parent) {
this._worldTransform = this._localTransform.multiply(this.parent._worldTransform);
this._rotation = this._localRotation + this.parent._rotation;
this._scale = Vector2.multiply(this.parent._scale, this._localScale);
this._worldInverseDirty = true;
}
this._worldToLocalDirty = true;
this._positionDirty = true;
this.hierarchyDirty = DirtyType.clean;
}
}
public setDirty(dirtyFlagType: DirtyType) {
if ((this.hierarchyDirty & dirtyFlagType) == 0) {
this.hierarchyDirty |= dirtyFlagType;
switch (dirtyFlagType) {
case es.DirtyType.positionDirty:
this.entity.onTransformChanged(transform.Component.position);
break;
case es.DirtyType.rotationDirty:
this.entity.onTransformChanged(transform.Component.rotation);
break;
case es.DirtyType.scaleDirty:
this.entity.onTransformChanged(transform.Component.scale);
break;
}
if (!this._children)
this._children = [];
// 告诉子项发生了变换
for (let i = 0; i < this._children.length; i++)
this._children[i].setDirty(dirtyFlagType);
}
}
/**
* transform属性进行拷贝
* @param transform
*/
public copyFrom(transform: Transform) {
this._position = transform.position;
this._localPosition = transform._localPosition;
this._rotation = transform._rotation;
this._localRotation = transform._localRotation;
this._scale = transform._scale;
this._localScale = transform._localScale;
this.setDirty(DirtyType.positionDirty);
this.setDirty(DirtyType.rotationDirty);
this.setDirty(DirtyType.scaleDirty);
}
public toString(): string {
return `[Transform: parent: ${this.parent}, position: ${this.position}, rotation: ${this.rotation},
scale: ${this.scale}, localPosition: ${this._localPosition}, localRotation: ${this._localRotation},
localScale: ${this._localScale}]`;
}
public equals(other: Transform) {
return other.hashCode == this.hashCode;
}
}
}
+112 -110
View File
@@ -1,133 +1,135 @@
/**
*
*
* ;
*/
class BitSet{
private static LONG_MASK: number = 0x3f;
private _bits: number[];
module es {
/**
*
*
* ;
*/
export class BitSet {
private static LONG_MASK: number = 0x3f;
private _bits: number[];
constructor(nbits: number = 64){
let length = nbits >> 6;
if ((nbits & BitSet.LONG_MASK) != 0)
length ++;
constructor(nbits: number = 64) {
let length = nbits >> 6;
if ((nbits & BitSet.LONG_MASK) != 0)
length++;
this._bits = new Array(length);
}
this._bits = new Array(length);
}
public and(bs: BitSet){
let max = Math.min(this._bits.length, bs._bits.length);
let i;
for (let i = 0; i < max; ++i)
this._bits[i] &= bs._bits[i];
public and(bs: BitSet) {
let max = Math.min(this._bits.length, bs._bits.length);
let i;
for (let i = 0; i < max; ++i)
this._bits[i] &= bs._bits[i];
while (i < this._bits.length)
this._bits[i ++] = 0;
}
while (i < this._bits.length)
this._bits[i++] = 0;
}
public andNot(bs: BitSet){
let i = Math.min(this._bits.length, bs._bits.length);
while(--i >= 0)
this._bits[i] &= ~bs._bits[i];
}
public andNot(bs: BitSet) {
let i = Math.min(this._bits.length, bs._bits.length);
while (--i >= 0)
this._bits[i] &= ~bs._bits[i];
}
public cardinality(): number{
let card = 0;
for (let i = this._bits.length - 1; i >= 0; i --){
let a = this._bits[i];
public cardinality(): number {
let card = 0;
for (let i = this._bits.length - 1; i >= 0; i--) {
let a = this._bits[i];
if (a == 0)
continue;
if (a == 0)
continue;
if (a == -1){
card += 64;
continue;
if (a == -1) {
card += 64;
continue;
}
a = ((a >> 1) & 0x5555555555555555) + (a & 0x5555555555555555);
a = ((a >> 2) & 0x3333333333333333) + (a & 0x3333333333333333);
let b = ((a >> 32) + a);
b = ((b >> 4) & 0x0f0f0f0f) + (b & 0x0f0f0f0f);
b = ((b >> 8) & 0x00ff00ff) + (b & 0x00ff00ff);
card += ((b >> 16) & 0x0000ffff) + (b & 0x0000ffff);
}
a = ((a >> 1) & 0x5555555555555555) + (a & 0x5555555555555555);
a = ((a >> 2) & 0x3333333333333333) + (a & 0x3333333333333333);
let b = ((a >> 32) + a);
b = ((b >> 4) & 0x0f0f0f0f) + (b & 0x0f0f0f0f);
b = ((b >> 8) & 0x00ff00ff) + (b & 0x00ff00ff);
card += ((b >> 16) & 0x0000ffff) + (b & 0x0000ffff);
return card;
}
return card;
}
public clear(pos?: number) {
if (pos != undefined) {
let offset = pos >> 6;
this.ensure(offset);
this._bits[offset] &= ~(1 << pos);
} else {
for (let i = 0; i < this._bits.length; i++)
this._bits[i] = 0;
}
}
public clear(pos?: number){
if (pos != undefined){
public get(pos: number): boolean {
let offset = pos >> 6;
this.ensure(offset);
this._bits[offset] &= ~(1 << pos);
}else{
for (let i = 0; i < this._bits.length; i ++)
this._bits[i] = 0;
}
}
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;
}
}
public get(pos: number): boolean{
let offset = pos >> 6;
if (offset >= this._bits.length)
return false;
return (this._bits[offset] & (1 << pos)) != 0;
}
public intersects(set: BitSet){
let i = Math.min(this._bits.length, set._bits.length);
while (--i >= 0){
if ((this._bits[i] & set._bits[i]) != 0)
return true;
}
return false;
}
public isEmpty(): boolean{
for (let i = this._bits.length - 1; i >= 0; i --){
if (this._bits[i])
if (offset >= this._bits.length)
return false;
return (this._bits[offset] & (1 << pos)) != 0;
}
return true;
}
public intersects(set: BitSet) {
let i = Math.min(this._bits.length, set._bits.length);
while (--i >= 0) {
if ((this._bits[i] & set._bits[i]) != 0)
return true;
}
public nextSetBit(from: number){
let offset = from >> 6;
let mask = 1 << from;
while (offset < this._bits.length){
let h = this._bits[offset];
do {
if ((h & mask) != 0)
return from;
mask <<= 1;
from ++;
} while (mask != 0);
mask = 1;
offset ++;
return false;
}
return -1;
}
public isEmpty(): boolean {
for (let i = this._bits.length - 1; i >= 0; i--) {
if (this._bits[i])
return false;
}
public set(pos: number, value: boolean = true){
if (value){
let offset = pos >> 6;
this.ensure(offset);
this._bits[offset] |= 1 << pos;
}else{
this.clear(pos);
return true;
}
public nextSetBit(from: number) {
let offset = from >> 6;
let mask = 1 << from;
while (offset < this._bits.length) {
let h = this._bits[offset];
do {
if ((h & mask) != 0)
return from;
mask <<= 1;
from++;
} while (mask != 0);
mask = 1;
offset++;
}
return -1;
}
public set(pos: number, value: boolean = true) {
if (value) {
let offset = pos >> 6;
this.ensure(offset);
this._bits[offset] |= 1 << pos;
} else {
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;
}
}
}
}
}
+223 -138
View File
@@ -1,186 +1,271 @@
class ComponentList {
private _entity: Entity;
private _components: Component[] = [];
private _componentsToAdd: Component[] = [];
private _componentsToRemove: Component[] = [];
private _tempBufferList: Component[] = [];
///<reference path="../Components/IUpdatableComparer.ts" />
module es {
export class ComponentList {
/**
* updateOrder排序
*/
public static compareUpdatableOrder: IUpdatableComparer = new IUpdatableComparer();
public _entity: Entity;
constructor(entity: Entity){
this._entity = entity;
}
/**
*
*/
public _components: Component[] = [];
/**
*
*/
public _componentsToAdd: Component[] = [];
/**
*
*/
public _componentsToRemove: Component[] = [];
public _tempBufferList: Component[] = [];
/**
*
*/
public _isComponentListUnsorted: boolean;
public get count(){
return this._components.length;
}
public get buffer(){
return this._components;
}
public add(component: Component){
this._componentsToAdd.push(component);
}
public remove(component: Component){
if (this._componentsToAdd.contains(component)){
this._componentsToAdd.remove(component);
return;
constructor(entity: Entity) {
this._entity = entity;
}
this._componentsToRemove.push(component);
}
public removeAllComponents(){
for (let i = 0; i < this._components.length; i ++){
this.handleRemove(this._components[i]);
public get count() {
return this._components.length;
}
this._components.length = 0;
this._componentsToAdd.length = 0;
this._componentsToRemove.length = 0;
}
public deregisterAllComponents(){
for (let i = 0; i < this._components.length; i ++){
let component = this._components[i];
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.remove(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
public get buffer() {
return this._components;
}
}
public registerAllComponents(){
for (let i = 0; i < this._components.length; i ++){
let component = this._components[i];
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.add(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component));
this._entity.scene.entityProcessors.onComponentAdded(this._entity);
public markEntityListUnsorted() {
this._isComponentListUnsorted = true;
}
}
public updateLists(){
if (this._componentsToRemove.length > 0){
for (let i = 0; i < this._componentsToRemove.length; i ++){
this.handleRemove(this._componentsToRemove[i]);
this._components.remove(this._componentsToRemove[i]);
public add(component: Component) {
this._componentsToAdd.push(component);
}
public remove(component: Component) {
if (this._componentsToRemove.contains(component))
console.warn(`You are trying to remove a Component (${component}) that you already removed`);
// 这可能不是一个活动的组件,所以我们必须注意它是否还没有被处理,它可能正在同一帧中被删除
if (this._componentsToAdd.contains(component)) {
this._componentsToAdd.remove(component);
return;
}
this._componentsToRemove.push(component);
}
/**
*
*/
public removeAllComponents() {
for (let i = 0; i < this._components.length; i++) {
this.handleRemove(this._components[i]);
}
this._components.length = 0;
this._componentsToAdd.length = 0;
this._componentsToRemove.length = 0;
}
if (this._componentsToAdd.length > 0){
for (let i = 0, count = this._componentsToAdd.length; i < count; i ++){
let component = this._componentsToAdd[i];
if (component instanceof RenderableComponent)
public deregisterAllComponents() {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
// 处理渲染层列表
if (component instanceof RenderableComponent) {
this._entity.scene.removeChild(component.displayObject);
this._entity.scene.renderableComponents.remove(component);
}
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
}
}
public registerAllComponents() {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
if (component instanceof RenderableComponent) {
this._entity.scene.addChild(component.displayObject);
this._entity.scene.renderableComponents.add(component);
}
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component));
this._entity.scene.entityProcessors.onComponentAdded(this._entity);
this._components.push(component);
this._tempBufferList.push(component);
}
}
this._componentsToAdd.length = 0;
for (let i = 0; i < this._tempBufferList.length; i++){
let component = this._tempBufferList[i];
component.onAddedToEntity();
if (component.enabled){
component.onEnabled();
/**
*
*/
public updateLists() {
if (this._componentsToRemove.length > 0) {
for (let i = 0; i < this._componentsToRemove.length; i++) {
this.handleRemove(this._componentsToRemove[i]);
this._components.remove(this._componentsToRemove[i]);
}
this._componentsToRemove.length = 0;
}
this._tempBufferList.length = 0;
}
}
if (this._componentsToAdd.length > 0) {
for (let i = 0, count = this._componentsToAdd.length; i < count; i++) {
let component = this._componentsToAdd[i];
if (component instanceof RenderableComponent) {
this._entity.scene.addChild(component.displayObject);
this._entity.scene.renderableComponents.add(component);
}
public onEntityTransformChanged(comp: TransformComponent){
for (let i = 0; i < this._components.length; i ++){
if (this._components[i].enabled)
this._components[i].onEntityTransformChanged(comp);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component));
this._entity.scene.entityProcessors.onComponentAdded(this._entity);
this._components.push(component);
this._tempBufferList.push(component);
}
// 在调用onAddedToEntity之前清除,以防添加更多组件
this._componentsToAdd.length = 0;
this._isComponentListUnsorted = true;
// 现在所有的组件都添加到了场景中,我们再次循环并调用onAddedToEntity/onEnabled
for (let i = 0; i < this._tempBufferList.length; i++) {
let component = this._tempBufferList[i];
component.onAddedToEntity();
// enabled检查实体和组件
if (component.enabled) {
component.onEnabled();
}
}
this._tempBufferList.length = 0;
}
if (this._isComponentListUnsorted) {
this._components.sort(ComponentList.compareUpdatableOrder.compare);
this._isComponentListUnsorted = false;
}
}
for (let i = 0; i < this._componentsToAdd.length; i ++){
if (this._componentsToAdd[i].enabled)
this._componentsToAdd[i].onEntityTransformChanged(comp);
}
}
public handleRemove(component: Component) {
// 处理渲染层列表
if (component instanceof RenderableComponent) {
this._entity.scene.removeChild(component.displayObject);
this._entity.scene.renderableComponents.remove(component);
}
private handleRemove(component: Component){
if (component instanceof RenderableComponent)
this._entity.scene.renderableComponents.remove(component);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
this._entity.componentBits.set(ComponentTypeManager.getIndexFor(component), false);
this._entity.scene.entityProcessors.onComponentRemoved(this._entity);
component.onRemovedFromEntity();
component.entity = null;
}
public getComponent<T extends Component>(type, onlyReturnInitializedComponents: boolean): T{
for (let i = 0; i < this._components.length; i ++){
let component = this._components[i];
if (component instanceof type)
return component as T;
component.onRemovedFromEntity();
component.entity = null;
}
if (!onlyReturnInitializedComponents){
for (let i = 0; i < this._componentsToAdd.length; i ++){
let component = this._componentsToAdd[i];
/**
* T的第一个组件并返回它
* (onAddedToEntity方法的组件)
* null
* @param type
* @param onlyReturnInitializedComponents
*/
public getComponent<T extends Component>(type, onlyReturnInitializedComponents: boolean): T {
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
if (component instanceof type)
return component as T;
}
// 我们可以选择检查挂起的组件,以防addComponent和getComponent在同一个框架中被调用
if (!onlyReturnInitializedComponents) {
for (let i = 0; i < this._componentsToAdd.length; i++) {
let component = this._componentsToAdd[i];
if (component instanceof type)
return component as T;
}
}
return null;
}
return null;
}
/**
* T类型的所有组件使
* @param typeName
* @param components
*/
public getComponents(typeName: string | any, components?) {
if (!components)
components = [];
public getComponents(typeName: string | any, components?){
if (!components)
components = [];
for (let i = 0; i < this._components.length; i++) {
let component = this._components[i];
if (typeof (typeName) == "string") {
if (egret.is(component, typeName)) {
components.push(component);
}
} else {
if (component instanceof typeName) {
components.push(component);
}
}
}
for (let i = 0; i < this._components.length; i ++){
let component = this._components[i];
if (typeof(typeName) == "string"){
if (egret.is(component, typeName)){
components.push(component);
}
}else{
if (component instanceof typeName){
components.push(component);
for (let i = 0; i < this._componentsToAdd.length; i++) {
let component = this._componentsToAdd[i];
if (typeof (typeName) == "string") {
if (egret.is(component, typeName)) {
components.push(component);
}
} else {
if (component instanceof typeName) {
components.push(component);
}
}
}
return components;
}
public update() {
this.updateLists();
for (let i = 0; i < this._components.length; i++) {
let updatableComponent = this._components[i];
if (updatableComponent.enabled &&
(updatableComponent.updateInterval == 1 ||
Time.frameCount % updatableComponent.updateInterval == 0))
updatableComponent.update();
}
}
for (let i = 0; i < this._componentsToAdd.length; i ++){
let component = this._componentsToAdd[i];
if (typeof(typeName) == "string"){
if (egret.is(component, typeName)){
components.push(component);
}
}else{
if (component instanceof typeName){
components.push(component);
}
public onEntityTransformChanged(comp: transform.Component) {
for (let i = 0; i < this._components.length; i++) {
if (this._components[i].enabled)
this._components[i].onEntityTransformChanged(comp);
}
for (let i = 0; i < this._componentsToAdd.length; i++) {
if (this._componentsToAdd[i].enabled)
this._componentsToAdd[i].onEntityTransformChanged(comp);
}
}
return components;
}
public onEntityEnabled() {
for (let i = 0; i < this._components.length; i++)
this._components[i].onEnabled();
}
public update(){
this.updateLists();
for (let i = 0; i < this._components.length; i ++){
let component = this._components[i];
if (component.enabled && (component.updateInterval == 1 || Time.frameCount % component.updateInterval == 0))
component.update();
public onEntityDisabled() {
for (let i = 0; i < this._components.length; i++)
this._components[i].onDisabled();
}
}
}
}
+16 -14
View File
@@ -1,18 +1,20 @@
class ComponentTypeManager{
private static _componentTypesMask: Map<any, number> = new Map<any, number>();
module es {
export class ComponentTypeManager {
private static _componentTypesMask: Map<any, number> = new Map<any, number>();
public static add(type){
if (!this._componentTypesMask.has(type))
this._componentTypesMask[type] = this._componentTypesMask.size;
}
public static getIndexFor(type){
let v = -1;
if (!this._componentTypesMask.has(type)){
this.add(type);
v = this._componentTypesMask.get(type);
public static add(type) {
if (!this._componentTypesMask.has(type))
this._componentTypesMask[type] = this._componentTypesMask.size;
}
return v;
public static getIndexFor(type) {
let v = -1;
if (!this._componentTypesMask.has(type)) {
this.add(type);
v = this._componentTypesMask.get(type);
}
return v;
}
}
}
}
+268 -117
View File
@@ -1,134 +1,285 @@
class EntityList{
public scene: Scene;
private _entitiesToRemove: Entity[] = [];
private _entitiesToAdded: Entity[] = [];
private _tempEntityList: Entity[] = [];
private _entities: Entity[] = [];
private _entityDict: Map<number, Entity[]> = new Map<number, Entity[]>();
private _unsortedTags: number[] = [];
module es {
export class EntityList {
public scene: Scene;
/**
*
*/
public _entities: Entity[] = [];
/**
* 便
*/
public _entitiesToAdded: Entity[] = [];
/**
* 便
*/
public _entitiesToRemove: Entity[] = [];
/**
*
*/
public _isEntityListUnsorted: boolean;
/**
* 便
*/
public _entityDict: Map<number, Entity[]> = new Map<number, Entity[]>();
public _unsortedTags: number[] = [];
/**
* updateLists中用于双缓冲区便
*/
public _tempEntityList: Entity[] = [];
constructor(scene: Scene){
this.scene = scene;
}
public get count(){
return this._entities.length;
}
public get buffer(){
return this._entities;
}
public add(entity: Entity){
if (this._entitiesToAdded.indexOf(entity) == -1)
this._entitiesToAdded.push(entity);
}
public remove(entity: Entity){
if (this._entitiesToAdded.contains(entity)){
this._entitiesToAdded.remove(entity);
return;
constructor(scene: Scene) {
this.scene = scene;
}
if (!this._entitiesToRemove.contains(entity))
this._entitiesToRemove.push(entity);
}
public findEntity(name: string){
for (let i = 0; i < this._entities.length; i ++){
if (this._entities[i].name == name)
return this._entities[i];
public get count() {
return this._entities.length;
}
return this._entitiesToAdded.firstOrDefault(entity => entity.name == name);
}
public getTagList(tag: number){
let list = this._entityDict.get(tag);
if (!list){
list = [];
this._entityDict.set(tag, list);
public get buffer() {
return this._entities;
}
return this._entityDict.get(tag);
}
public addToTagList(entity: Entity){
let list = this.getTagList(entity.tag);
if (!list.contains(entity)){
list.push(entity);
this._unsortedTags.push(entity.tag);
}
}
public removeFromTagList(entity: Entity){
let list = this._entityDict.get(entity.tag);
if (list){
list.remove(entity);
}
}
public update(){
for (let i = 0; i < this._entities.length; i++){
let entity = this._entities[i];
if (entity.enabled)
entity.update();
}
}
public removeAllEntities(){
this._entitiesToAdded.length = 0;
this.updateLists();
for (let i = 0; i < this._entities.length; i ++){
this._entities[i]._isDestoryed = true;
this._entities[i].onRemovedFromScene();
this._entities[i].scene = null;
public markEntityListUnsorted() {
this._isEntityListUnsorted = true;
}
this._entities.length = 0;
this._entityDict.clear();
}
public updateLists(){
if (this._entitiesToRemove.length > 0){
let temp = this._entitiesToRemove;
this._entitiesToRemove = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
this._entities.remove(entity);
entity.scene = null;
this.scene.entityProcessors.onEntityRemoved(entity);
});
this._tempEntityList.length = 0;
public markTagUnsorted(tag: number) {
this._unsortedTags.push(tag);
}
if (this._entitiesToAdded.length > 0){
let temp = this._entitiesToAdded;
this._entitiesToAdded = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
if (!this._entities.contains(entity)){
this._entities.push(entity);
entity.scene = this.scene;
this.scene.entityProcessors.onEntityAdded(entity)
}
});
this._tempEntityList.forEach(entity => entity.onAddedToScene());
this._tempEntityList.length = 0;
/**
*
* @param entity
*/
public add(entity: Entity) {
if (this._entitiesToAdded.indexOf(entity) == -1)
this._entitiesToAdded.push(entity);
}
if (this._unsortedTags.length > 0){
this._unsortedTags.forEach(tag => {
this._entityDict.get(tag).sort();
});
/**
*
* @param entity
*/
public remove(entity: Entity) {
if (!this._entitiesToRemove.contains(entity)) {
console.warn(`You are trying to remove an entity (${entity.name}) that you already removed`);
return;
}
// 防止在同一帧中添加或删除实体
if (this._entitiesToAdded.contains(entity)) {
this._entitiesToAdded.remove(entity);
return;
}
if (!this._entitiesToRemove.contains(entity))
this._entitiesToRemove.push(entity);
}
/**
*
*/
public removeAllEntities() {
this._unsortedTags.length = 0;
this._entitiesToAdded.length = 0;
this._isEntityListUnsorted = false;
// 为什么我们要在这里更新列表?主要用于处理场景切换前分离的实体。
// 它们仍然在_entitiesToRemove列表中,该列表将由更新列表处理。
this.updateLists();
for (let i = 0; i < this._entities.length; i++) {
this._entities[i]._isDestroyed = true;
this._entities[i].onRemovedFromScene();
this._entities[i].scene = null;
}
this._entities.length = 0;
this._entityDict.clear();
}
/**
* EntityList管理
* @param entity
*/
public contains(entity: Entity): boolean {
return this._entities.contains(entity) || this._entitiesToAdded.contains(entity);
}
public getTagList(tag: number) {
let list = this._entityDict.get(tag);
if (!list) {
list = [];
this._entityDict.set(tag, list);
}
return this._entityDict.get(tag);
}
public addToTagList(entity: Entity) {
let list = this.getTagList(entity.tag);
if (!list.contains(entity)) {
list.push(entity);
this._unsortedTags.push(entity.tag);
}
}
public removeFromTagList(entity: Entity) {
let list = this._entityDict.get(entity.tag);
if (list) {
list.remove(entity);
}
}
public update() {
for (let i = 0; i < this._entities.length; i++) {
let entity = this._entities[i];
if (entity.enabled && (entity.updateInterval == 1 || Time.frameCount % entity.updateInterval == 0))
entity.update();
}
}
public updateLists() {
if (this._entitiesToRemove.length > 0) {
let temp = this._entitiesToRemove;
this._entitiesToRemove = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
this.removeFromTagList(entity);
this._entities.remove(entity);
entity.onRemovedFromScene();
entity.scene = null;
this.scene.entityProcessors.onEntityRemoved(entity);
});
this._tempEntityList.length = 0;
}
if (this._entitiesToAdded.length > 0) {
let temp = this._entitiesToAdded;
this._entitiesToAdded = this._tempEntityList;
this._tempEntityList = temp;
this._tempEntityList.forEach(entity => {
if (!this._entities.contains(entity)) {
this._entities.push(entity);
entity.scene = this.scene;
this.addToTagList(entity);
this.scene.entityProcessors.onEntityAdded(entity)
}
});
// 现在所有实体都被添加到场景中,我们再次循环并调用onAddedToScene
this._tempEntityList.forEach(entity => entity.onAddedToScene());
this._tempEntityList.length = 0;
this._isEntityListUnsorted = true;
}
if (this._isEntityListUnsorted) {
this._entities.sort();
this._isEntityListUnsorted = false;
}
if (this._unsortedTags.length > 0) {
this._unsortedTags.forEach(tag => {
this._entityDict.get(tag).sort();
});
this._unsortedTags.length = 0;
}
}
/**
* null
* @param name
*/
public findEntity(name: string) {
for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].name == name)
return this._entities[i];
}
return this._entitiesToAdded.firstOrDefault(entity => entity.name == name);
}
/**
* ListPool.free将返回的列表放回池中
* @param tag
*/
public entitiesWithTag(tag: number) {
let list = this.getTagList(tag);
let returnList = ListPool.obtain<Entity>();
for (let i = 0; i < list.length; i++)
returnList.push(list[i]);
return returnList;
}
/**
* t类型的所有实体的列表ListPool.free放回池中
* @param type
*/
public entitiesOfType<T extends Entity>(type): T[] {
let list = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i] instanceof type)
list.push(this._entities[i] as T);
}
this._entitiesToAdded.forEach(entity => {
if (entity instanceof type)
list.push(entity as T);
});
return list;
}
/**
* T的场景中找到的第一个组件
* @param type
*/
public findComponentOfType<T extends Component>(type): T {
for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].enabled) {
let comp = this._entities[i].getComponent<T>(type);
if (comp)
return comp;
}
}
for (let i = 0; i < this._entitiesToAdded.length; i++) {
let entity = this._entitiesToAdded[i];
if (entity.enabled) {
let comp = entity.getComponent<T>(type);
if (comp)
return comp;
}
}
return null;
}
/**
* t的场景中找到的所有组件ListPool.free放回池中
* @param type
*/
public findComponentsOfType<T extends Component>(type): T[] {
let comps = ListPool.obtain<T>();
for (let i = 0; i < this._entities.length; i++) {
if (this._entities[i].enabled)
this._entities[i].getComponents(type, comps);
}
for (let i = 0; i < this._entitiesToAdded.length; i++) {
let entity = this._entitiesToAdded[i];
if (entity.enabled)
entity.getComponents(type, comps);
}
return comps;
}
}
}
}
+67 -65
View File
@@ -1,69 +1,71 @@
class EntityProcessorList {
private _processors: EntitySystem[] = [];
module es {
export class EntityProcessorList {
private _processors: EntitySystem[] = [];
public add(processor: EntitySystem){
this._processors.push(processor);
}
public remove(processor: EntitySystem){
this._processors.remove(processor);
}
public onComponentAdded(entity: Entity){
this.notifyEntityChanged(entity);
}
public onComponentRemoved(entity: Entity){
this.notifyEntityChanged(entity);
}
public onEntityAdded(entity: Entity){
this.notifyEntityChanged(entity);
}
public onEntityRemoved(entity: Entity){
this.removeFromProcessors(entity);
}
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);
}
}
public begin(){
}
public update(){
for (let i = 0; i < this._processors.length; i++){
this._processors[i].update();
}
}
public lateUpdate(){
for (let i = 0; i < this._processors.length; i ++){
this._processors[i].lateUpdate();
}
}
public end(){
}
public getProcessor<T extends EntitySystem>(): T{
for (let i = 0; i < this._processors.length; i ++){
let processor = this._processors[i];
if (processor instanceof EntitySystem)
return processor as T;
public add(processor: EntitySystem) {
this._processors.push(processor);
}
return null;
public remove(processor: EntitySystem) {
this._processors.remove(processor);
}
public onComponentAdded(entity: Entity) {
this.notifyEntityChanged(entity);
}
public onComponentRemoved(entity: Entity) {
this.notifyEntityChanged(entity);
}
public onEntityAdded(entity: Entity) {
this.notifyEntityChanged(entity);
}
public onEntityRemoved(entity: Entity) {
this.removeFromProcessors(entity);
}
public begin() {
}
public update() {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].update();
}
}
public lateUpdate() {
for (let i = 0; i < this._processors.length; i++) {
this._processors[i].lateUpdate();
}
}
public end() {
}
public getProcessor<T extends EntitySystem>(): T {
for (let i = 0; i < this._processors.length; i++) {
let processor = this._processors[i];
if (processor instanceof EntitySystem)
return processor as T;
}
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);
}
}
}
}
}
+58 -56
View File
@@ -1,62 +1,64 @@
class Matcher{
protected allSet = new BitSet();
protected exclusionSet = new BitSet();
protected oneSet = new BitSet();
module es {
export class Matcher {
protected allSet = new BitSet();
protected exclusionSet = new BitSet();
protected oneSet = new BitSet();
public static empty(){
return new Matcher();
}
public getAllSet(){
return this.allSet;
}
public getExclusionSet(){
return this.exclusionSet;
}
public getOneSet(){
return this.oneSet;
}
public IsIntersted(e: Entity){
if (!this.allSet.isEmpty()){
for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)){
if (!e.componentBits.get(i))
return false;
}
public static empty() {
return new Matcher();
}
if (!this.exclusionSet.isEmpty() && this.exclusionSet.intersects(e.componentBits))
return false;
public getAllSet() {
return this.allSet;
}
if (!this.oneSet.isEmpty() && !this.oneSet.intersects(e.componentBits))
return false;
public getExclusionSet() {
return this.exclusionSet;
}
return true;
public getOneSet() {
return this.oneSet;
}
public IsIntersted(e: Entity) {
if (!this.allSet.isEmpty()) {
for (let i = this.allSet.nextSetBit(0); i >= 0; i = this.allSet.nextSetBit(i + 1)) {
if (!e.componentBits.get(i))
return false;
}
}
if (!this.exclusionSet.isEmpty() && this.exclusionSet.intersects(e.componentBits))
return false;
if (!this.oneSet.isEmpty() && !this.oneSet.intersects(e.componentBits))
return false;
return true;
}
public all(...types: any[]): Matcher {
types.forEach(type => {
this.allSet.set(ComponentTypeManager.getIndexFor(type));
});
return this;
}
public exclude(...types: any[]) {
types.forEach(type => {
this.exclusionSet.set(ComponentTypeManager.getIndexFor(type));
});
return this;
}
public one(...types: any[]) {
types.forEach(type => {
this.oneSet.set(ComponentTypeManager.getIndexFor(type));
});
return this;
}
}
public all(...types: any[]): Matcher{
types.forEach(type => {
this.allSet.set(ComponentTypeManager.getIndexFor(type));
});
return this;
}
public exclude(...types: any[]){
types.forEach(type => {
this.exclusionSet.set(ComponentTypeManager.getIndexFor(type));
});
return this;
}
public one(...types: any[]){
types.forEach(type => {
this.oneSet.set(ComponentTypeManager.getIndexFor(type));
});
return this;
}
}
}
+19
View File
@@ -0,0 +1,19 @@
class ObjectUtils {
/**
*
* @param p any
* @param c any , , ,
*/
public static clone<T>(p: any, c: T = null): T {
var c = c || <T>{};
for (let i in p) {
if (typeof p[i] === 'object') {
c[i] = p[i] instanceof Array ? [] : {};
this.clone(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
}
+95 -16
View File
@@ -1,22 +1,101 @@
class RenderableComponentList {
private _components: IRenderable[] = [];
public get count(){
return this._components.length;
}
///<reference path="../../Graphics/Renderers/IRenderable.ts" />
module es {
export class RenderableComponentList {
/**
* IRenderable列表的全局updatePrder排序
*/
public static compareUpdatableOrder = new RenderableComparer();
/**
*
*/
public _components: IRenderable[] = [];
/**
* 便
*/
public _componentsByRenderLayer: Map<number, IRenderable[]> = new Map<number, IRenderable[]>();
public _unsortedRenderLayers: number[] = [];
public _componentsNeedSort: boolean = true;
public get buffer(){
return this._components;
}
public get count() {
return this._components.length;
}
public add(component: IRenderable){
this._components.push(component);
}
public get buffer() {
return this._components;
}
public remove(component: IRenderable){
this._components.remove(component);
}
public add(component: IRenderable) {
this._components.push(component);
this.addToRenderLayerList(component, component.renderLayer);
}
public updateList(){
public remove(component: IRenderable) {
this._components.remove(component);
this._componentsByRenderLayer.get(component.renderLayer).remove(component);
}
public updateRenderableRenderLayer(component: IRenderable, oldRenderLayer: number, newRenderLayer: number) {
// 需要注意的是,如果渲染层在组件update之前发生了改变
if (this._componentsByRenderLayer.has(oldRenderLayer) && this._componentsByRenderLayer.get(oldRenderLayer).contains(component)) {
this._componentsByRenderLayer.get(oldRenderLayer).remove(component);
this.addToRenderLayerList(component, newRenderLayer);
}
}
/**
*
* @param renderLayer
*/
public setRenderLayerNeedsComponentSort(renderLayer: number) {
if (!this._unsortedRenderLayers.contains(renderLayer))
this._unsortedRenderLayers.push(renderLayer);
this._componentsNeedSort = true;
}
public setNeedsComponentSort() {
this._componentsNeedSort = true;
}
public addToRenderLayerList(component: IRenderable, renderLayer: number) {
let list = this.componentsWithRenderLayer(renderLayer);
if (!list.contains(component)) {
console.warn("Component renderLayer list already contains this component");
return;
}
list.push(component);
if (!this._unsortedRenderLayers.contains(renderLayer))
this._unsortedRenderLayers.push(renderLayer);
this._componentsNeedSort = true;
}
/**
* 使
* @param renderLayer
*/
public componentsWithRenderLayer(renderLayer: number): IRenderable[] {
if (!this._componentsByRenderLayer.get(renderLayer)) {
this._componentsByRenderLayer.set(renderLayer, []);
}
return this._componentsByRenderLayer.get(renderLayer);
}
public updateList() {
if (this._componentsNeedSort) {
this._components.sort(RenderableComponentList.compareUpdatableOrder.compare);
this._componentsNeedSort = false;
}
if (this._unsortedRenderLayers.length > 0) {
for (let i = 0, count = this._unsortedRenderLayers.length; i < count; i++) {
let renderLayerComponents = this._componentsByRenderLayer.get(this._unsortedRenderLayers[i]);
if (renderLayerComponents) {
renderLayerComponents.sort(RenderableComponentList.compareUpdatableOrder.compare);
}
}
this._unsortedRenderLayers.length = 0;
}
}
}
}
}
+233
View File
@@ -0,0 +1,233 @@
class StringUtils {
/**
*
*/
private static specialSigns: string[] = [
'&', '&amp;',
'<', '&lt;',
'>', '&gt;',
'"', '&quot;',
"'", '&apos;',
'®', '&reg;',
'©', '&copy;',
'™', '&trade;',
];
/**
*
* @param str
* @return
*/
public static matchChineseWord(str: string): string[] {
//中文字符的unicode值[\u4E00-\u9FA5]
let patternA: RegExp = /[\u4E00-\u9FA5]+/gim;
return str.match(patternA);
}
/**
*
* @param target
* @return
*/
public static lTrim(target: string): string {
let startIndex: number = 0;
while (this.isWhiteSpace(target.charAt(startIndex))) {
startIndex++;
}
return target.slice(startIndex, target.length);
}
/**
*
* @param target
* @return
*/
public static rTrim(target: string): string {
let endIndex: number = target.length - 1;
while (this.isWhiteSpace(target.charAt(endIndex))) {
endIndex--;
}
return target.slice(0, endIndex + 1);
}
/**
* 2
* @param target
* @return 2
*/
public static trim(target: string): string {
if (target == null) {
return null;
}
return this.rTrim(this.lTrim(target));
}
/**
*
* @param str
* @return
*/
public static isWhiteSpace(str: string): boolean {
if (str == " " || str == "\t" || str == "\r" || str == "\n")
return true;
return false;
}
/**
*
* @param mainStr
* @param targetStr
* @param replaceStr
* @param caseMark
* @return
*/
public static replaceMatch(mainStr: string, targetStr: string,
replaceStr: string, caseMark: boolean = false): string {
let len: number = mainStr.length;
let tempStr: string = "";
let isMatch: boolean = false;
let tempTarget: string = caseMark == true ? targetStr.toLowerCase() : targetStr;
for (let i: number = 0; i < len; i++) {
isMatch = false;
if (mainStr.charAt(i) == tempTarget.charAt(0)) {
if (mainStr.substr(i, tempTarget.length) == tempTarget) {
isMatch = true;
}
}
if (isMatch) {
tempStr += replaceStr;
i = i + tempTarget.length - 1;
} else {
tempStr += mainStr.charAt(i);
}
}
return tempStr;
}
/**
* html实体换掉字符窜中的特殊字符
* @param str
* @param reversion
* @return
*/
public static htmlSpecialChars(str: string, reversion: boolean = false): string {
let len: number = this.specialSigns.length;
for (let i: number = 0; i < len; i += 2) {
let from: string;
let to: string;
from = this.specialSigns[i];
to = this.specialSigns[i + 1];
if (reversion) {
let temp: string = from;
from = to;
to = temp;
}
str = this.replaceMatch(str, from, to);
}
return str;
}
/**
* "0"
*
* <pre>
*
* trace( StringFormat.zfill('1') );
* // 01
*
* trace( StringFormat.zfill('16', 5) );
* // 00016
*
* trace( StringFormat.zfill('-3', 3) );
* // -03
*
* </pre>
*
* @param str
* @param width
* str.length >= widthstr
* @return
*
*/
public static zfill(str: string, width: number = 2): string {
if (!str) {
return str;
}
width = Math.floor(width);
let slen: number = str.length;
if (slen >= width) {
return str;
}
let negative: boolean = false;
if (str.substr(0, 1) == '-') {
negative = true;
str = str.substr(1);
}
let len: number = width - slen;
for (let i: number = 0; i < len; i++) {
str = '0' + str;
}
if (negative) {
str = '-' + str;
}
return str;
}
/**
*
* @param str
* @return
*/
public static reverse(str: string): string {
if (str.length > 1)
return this.reverse(str.substring(1)) + str.substring(0, 1);
else
return str;
}
/**
*
* @param str
* @param start
* @param len
* @param order true从字符串头部开始计算false从字符串尾巴开始结算
* @return
*/
public static cutOff(str: string, start: number,
len: number, order: boolean = true): string {
start = Math.floor(start);
len = Math.floor(len);
let length: number = str.length;
if (start > length) start = length;
let s: number = start;
let e: number = start + len;
let newStr: string;
if (order) {
newStr = str.substring(0, s) + str.substr(e, length);
} else {
s = length - 1 - start - len;
e = s + len;
newStr = str.substring(0, s + 1) + str.substr(e + 1, length);
}
return newStr;
}
/**{0} 字符替换 */
public static strReplace(str: string, rStr: string[]): string {
let i: number = 0, len: number = rStr.length;
for (; i < len; i++) {
if (rStr[i] == null || rStr[i] == "") {
rStr[i] = "无";
}
str = str.replace("{" + i + "}", rStr[i]);
}
return str
}
}
+151
View File
@@ -0,0 +1,151 @@
module es {
/**
*
*/
export class TextureUtils {
public static sharedCanvas: HTMLCanvasElement;
public static sharedContext: CanvasRenderingContext2D;
public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement {
if (!this.sharedCanvas) {
this.sharedCanvas = egret.sys.createCanvas();
this.sharedContext = this.sharedCanvas.getContext("2d");
}
let w = texture.$getTextureWidth();
let h = texture.$getTextureHeight();
if (!rect) {
rect = egret.$TempRectangle;
rect.x = 0;
rect.y = 0;
rect.width = w;
rect.height = h;
}
rect.x = Math.min(rect.x, w - 1);
rect.y = Math.min(rect.y, h - 1);
rect.width = Math.min(rect.width, w - rect.x);
rect.height = Math.min(rect.height, h - rect.y);
let iWidth = Math.floor(rect.width);
let iHeight = Math.floor(rect.height);
let surface = this.sharedCanvas;
surface["style"]["width"] = iWidth + "px";
surface["style"]["height"] = iHeight + "px";
this.sharedCanvas.width = iWidth;
this.sharedCanvas.height = iHeight;
if (egret.Capabilities.renderMode == "webgl") {
let renderTexture: egret.RenderTexture;
//webgl下非RenderTexture纹理先画到RenderTexture
if (!(<egret.RenderTexture>texture).$renderBuffer) {
if (egret.sys.systemRenderer["renderClear"]) {
egret.sys.systemRenderer["renderClear"]();
}
renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture));
} else {
renderTexture = <egret.RenderTexture>texture;
}
//从RenderTexture中读取像素数据,填入canvas
let pixels = renderTexture.$renderBuffer.getPixels(rect.x, rect.y, iWidth, iHeight);
let x = 0;
let y = 0;
for (let i = 0; i < pixels.length; i += 4) {
this.sharedContext.fillStyle =
'rgba(' + pixels[i]
+ ',' + pixels[i + 1]
+ ',' + pixels[i + 2]
+ ',' + (pixels[i + 3] / 255) + ')';
this.sharedContext.fillRect(x, y, 1, 1);
x++;
if (x == iWidth) {
x = 0;
y++;
}
}
if (!(<egret.RenderTexture>texture).$renderBuffer) {
renderTexture.dispose();
}
return surface;
} else {
let bitmapData = texture;
let offsetX: number = Math.round(bitmapData.$offsetX);
let offsetY: number = Math.round(bitmapData.$offsetY);
let bitmapWidth: number = bitmapData.$bitmapWidth;
let bitmapHeight: number = bitmapData.$bitmapHeight;
let $TextureScaleFactor = Core._instance.stage.textureScaleFactor;
this.sharedContext.drawImage(bitmapData.$bitmapData.source, bitmapData.$bitmapX + rect.x / $TextureScaleFactor, bitmapData.$bitmapY + rect.y / $TextureScaleFactor,
bitmapWidth * rect.width / w, bitmapHeight * rect.height / h, offsetX, offsetY, rect.width, rect.height);
return surface;
}
}
public static toDataURL(type: string, texture: egret.Texture, rect?: egret.Rectangle, encoderOptions?): string {
try {
let surface = this.convertImageToCanvas(texture, rect);
let result = surface.toDataURL(type, encoderOptions);
return result;
} catch (e) {
egret.$error(1033);
}
return null;
}
/**
* saveToFile
* @param type
* @param texture
* @param filePath
* @param rect
* @param encoderOptions
*/
public static eliFoTevas(type: string, texture: egret.Texture, filePath: string, rect?: egret.Rectangle, encoderOptions?): void {
let surface = this.convertImageToCanvas(texture, rect);
let result = (surface as any).toTempFilePathSync({
fileType: type.indexOf("png") >= 0 ? "png" : "jpg"
});
wx.getFileSystemManager().saveFile({
tempFilePath: result,
filePath: `${wx.env.USER_DATA_PATH}/${filePath}`,
success: function (res) {
//todo
}
});
return result;
}
public static getPixel32(texture: egret.Texture, x: number, y: number): number[] {
egret.$warn(1041, "getPixel32", "getPixels");
return texture.getPixels(x, y);
}
public static getPixels(texture: egret.Texture, x: number, y: number, width: number = 1, height: number = 1): number[] {
//webgl环境下不需要转换成canvas获取像素信息
if (egret.Capabilities.renderMode == "webgl") {
let renderTexture: egret.RenderTexture;
//webgl下非RenderTexture纹理先画到RenderTexture
if (!(<egret.RenderTexture>texture).$renderBuffer) {
renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture));
} else {
renderTexture = <egret.RenderTexture>texture;
}
//从RenderTexture中读取像素数据
let pixels = renderTexture.$renderBuffer.getPixels(x, y, width, height);
return pixels;
}
try {
let surface = this.convertImageToCanvas(texture);
let result = this.sharedContext.getImageData(x, y, width, height).data;
return <number[]><any>result;
} catch (e) {
egret.$error(1039);
}
}
}
}
+36 -14
View File
@@ -1,17 +1,39 @@
class Time {
public static unscaledDeltaTime;
public static deltaTime: number = 0;
public static timeScale = 1;
public static frameCount = 0;;
private static _lastTime = 0;
module es {
/** 提供帧定时信息 */
export class Time {
/** deltaTime的未缩放版本。不受时间尺度的影响 */
public static unscaledDeltaTime;
/** 前一帧到当前帧的时间增量,按时间刻度进行缩放 */
public static deltaTime: number = 0;
/** 时间刻度缩放 */
public static timeScale = 1;
/** 已传递的帧总数 */
public static frameCount = 0;
/** 自场景加载以来的总时间 */
public static _timeSinceSceneLoad;
private static _lastTime = 0;
public static update(currentTime: number){
let dt = (currentTime - this._lastTime) / 1000;
this.deltaTime = dt * this.timeScale;
this.unscaledDeltaTime = dt;
this.frameCount ++;
public static update(currentTime: number) {
let dt = (currentTime - this._lastTime) / 1000;
this.deltaTime = dt * this.timeScale;
this.unscaledDeltaTime = dt;
this._timeSinceSceneLoad += dt;
this.frameCount++;
this._lastTime = currentTime;
this._lastTime = currentTime;
}
public static sceneChanged() {
this._timeSinceSceneLoad = 0;
}
/**
* 使delta的间隔值true
* @param interval
*/
public static checkEvery(interval: number) {
// 我们减去了delta,因为timeSinceSceneLoad已经包含了这个update ticks delta
return (this._timeSinceSceneLoad / interval) > ((this._timeSinceSceneLoad - this.deltaTime) / interval);
}
}
}
}
+212
View File
@@ -0,0 +1,212 @@
class TimeUtils {
/**
* ID
* @param d
* @returns ID
*/
public static monthId(d: Date = null): number {
d = d ? d : new Date();
let y = d.getFullYear();
let m = d.getMonth() + 1;
let g = m < 10 ? "0" : "";
return parseInt(y + g + m);
}
/**
* ID
* @param d
* @returns ID
*/
public static dateId(t: Date = null): number {
t = t ? t : new Date();
let m: number = t.getMonth() + 1;
let a = m < 10 ? "0" : "";
let d: number = t.getDate();
let b = d < 10 ? "0" : "";
return parseInt(t.getFullYear() + a + m + b + d);
}
/**
* ID
* @param d
* @returns ID
*/
public static weekId(d: Date = null, first: boolean = true): number {
d = d ? d : new Date();
let c: Date = new Date();
c.setTime(d.getTime());
c.setDate(1);
c.setMonth(0);//当年第一天
let year: number = c.getFullYear();
let firstDay: number = c.getDay();
if (firstDay == 0) {
firstDay = 7;
}
let max: boolean = false;
if (firstDay <= 4) {
max = firstDay > 1;
c.setDate(c.getDate() - (firstDay - 1));
} else {
c.setDate(c.getDate() + 7 - firstDay + 1);
}
let num: number = this.diffDay(d, c, false);
if (num < 0) {
c.setDate(1);
c.setMonth(0);//当年第一天
c.setDate(c.getDate() - 1);
return this.weekId(c, false);
}
let week: number = num / 7;
let weekIdx: number = Math.floor(week) + 1;
if (weekIdx == 53) {
c.setTime(d.getTime());
c.setDate(c.getDate() - 1);
let endDay: number = c.getDay();
if (endDay == 0) {
endDay = 7;
}
if (first && (!max || endDay < 4)) {
c.setFullYear(c.getFullYear() + 1);
c.setDate(1);
c.setMonth(0);//当年第一天
return this.weekId(c, false);
}
}
let g: string = weekIdx > 9 ? "" : "0";
let s: string = year + "00" + g + weekIdx;//加上00防止和月份ID冲突
return parseInt(s);
}
/**
* a比b小
*/
public static diffDay(a: Date, b: Date, fixOne: boolean = false): number {
let x = (a.getTime() - b.getTime()) / 86400000;
return fixOne ? Math.ceil(x) : Math.floor(x);
}
/**
*
*/
public static getFirstDayOfWeek(d?: Date): Date {
d = d ? d : new Date();
let day = d.getDay() || 7;
return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1 - day, 0, 0, 0, 0);
}
/**
*
*/
public static getFirstOfDay(d?: Date): Date {
d = d ? d : new Date();
d.setHours(0, 0, 0, 0);
return d;
}
/**
*
*/
public static getNextFirstOfDay(d?: Date): Date {
return new Date(this.getFirstOfDay(d).getTime() + 86400000);
}
/**
* @returns 2018-12-12
*/
public static formatDate(date: Date): string {
let y = date.getFullYear();
let m: any = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
let d: any = date.getDate();
d = d < 10 ? ('0' + d) : d;
return y + '-' + m + '-' + d;
}
/**
* @returns 2018-12-12 12:12:12
*/
public static formatDateTime(date: Date): string {
let y = date.getFullYear();
let m: any = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
let d: any = date.getDate();
d = d < 10 ? ('0' + d) : d;
let h = date.getHours();
let i: any = date.getMinutes();
i = i < 10 ? ('0' + i) : i;
let s: any = date.getSeconds();
s = s < 10 ? ('0' + s) : s;
return y + '-' + m + '-' + d + ' ' + h + ':' + i + ":" + s;
}
/**
* @returns s 2018-12-12 2018-12-12 12:12:12
*/
public static parseDate(s: string): Date {
let t = Date.parse(s);
if (!isNaN(t)) {
return new Date(Date.parse(s.replace(/-/g, "/")));
} else {
return new Date();
}
}
/**
*
* @param time
* @param partition
* @param showHour
* @return , ,
*
* 比如: time = 4351; secondToTime(time)返回字符串01:12:31;
*/
public static secondToTime(time: number = 0, partition: string = ":", showHour: boolean = true): string {
let hours: number = Math.floor(time / 3600);
let minutes: number = Math.floor(time % 3600 / 60);
let seconds: number = Math.floor(time % 3600 % 60);
let h: string = hours.toString();
let m: string = minutes.toString();
let s: string = seconds.toString();
if (hours < 10) h = "0" + h;
if (minutes < 10) m = "0" + m;
if (seconds < 10) s = "0" + s;
let timeStr: string;
if (showHour)
timeStr = h + partition + m + partition + s;
else
timeStr = m + partition + s;
return timeStr;
}
/**
*
* @param time
* @param partition
* @return
* @throws Error Exception
*
* 1 trace(MillisecondTransform.timeToMillisecond("00:60:00"))
* 3600000
*
*
* 2 trace(MillisecondTransform.timeToMillisecond("00.60.00","."))
* 3600000
*/
public static timeToMillisecond(time: string, partition: string = ":"): string {
let _ary: any[] = time.split(partition);
let timeNum: number = 0;
let len: number = _ary.length;
for (let i: number = 0; i < len; i++) {
let n: number = <number>_ary[i];
timeNum += n * Math.pow(60, (len - 1 - i));
}
timeNum *= 1000;
return timeNum.toString();
}
}
+73 -57
View File
@@ -3,90 +3,106 @@ declare interface Array<T> {
*
* @param predicate
*/
findIndex(predicate: Function): number;
findIndex(predicate: (c: T)=>boolean): number;
/**
*
* @param predicate
*/
any(predicate: Function): boolean;
any(predicate: (c: T) => boolean): boolean;
/**
*
* @param predicate
*/
firstOrDefault(predicate: Function): T;
firstOrDefault(predicate: (c: T)=>boolean): T;
/**
*
* @param predicate
*/
find(predicate: Function): T;
find(predicate: (c: T) => boolean): T;
/**
*
* @param predicate
*/
where(predicate: Function): Array<T>;
where(predicate: (c: T) => boolean): Array<T>;
/**
*
* @param predicate
*/
count(predicate: Function): number;
count(predicate: (c: T) => boolean): number;
/**
*
* @param predicate
*/
findAll(predicate: Function): Array<T>;
findAll(predicate: (c: T) => boolean): Array<T>;
/**
*
* @param value
*/
contains(value): boolean;
contains(value: T): boolean;
/**
*
* @param predicate
*/
removeAll(predicate: Function): void;
removeAll(predicate: (c: T) => boolean): void;
/**
*
* @param element
*/
remove(element): boolean;
remove(element: T): boolean;
/**
*
* @param index
*/
removeAt(index): void;
removeAt(index: number): void;
/**
*
* @param index
* @param count
*/
removeRange(index, count): void;
removeRange(index: number, count: number): void;
/**
*
* @param selector
*/
select(selector: Function): Array<T>;
/**
*
* @param keySelector key选择器
* @param comparer
*/
orderBy(keySelector: Function, comparer: Function): Array<T>;
/**
*
* @param keySelector key选择器
* @param comparer
*/
orderByDescending(keySelector: Function, comparer: Function): Array<T>;
/**
*
* @param keySelector key选择器
*/
groupBy(keySelector: Function): Array<T>;
/**
*
* @param selector
*/
sum(selector);
sum(selector: Function): number;
}
Array.prototype.findIndex = function (predicate) {
@@ -101,7 +117,7 @@ Array.prototype.findIndex = function (predicate) {
}
return findIndex(this, predicate);
}
};
Array.prototype.any = function (predicate) {
function any(array, predicate) {
@@ -109,7 +125,7 @@ Array.prototype.any = function (predicate) {
}
return any(this, predicate);
}
};
Array.prototype.firstOrDefault = function (predicate) {
function firstOrDefault(array, predicate) {
@@ -118,7 +134,7 @@ Array.prototype.firstOrDefault = function (predicate) {
}
return firstOrDefault(this, predicate);
}
};
Array.prototype.find = function (predicate) {
function find(array, predicate) {
@@ -126,7 +142,7 @@ Array.prototype.find = function (predicate) {
}
return find(this, predicate);
}
};
Array.prototype.where = function (predicate) {
function where(array, predicate) {
@@ -138,8 +154,7 @@ Array.prototype.where = function (predicate) {
return ret;
}, []);
}
else {
} else {
let ret = [];
for (let i = 0, len = array.length; i < len; i++) {
let element = array[i];
@@ -153,7 +168,7 @@ Array.prototype.where = function (predicate) {
}
return where(this, predicate);
}
};
Array.prototype.count = function (predicate) {
function count(array, predicate) {
@@ -161,7 +176,7 @@ Array.prototype.count = function (predicate) {
}
return count(this, predicate);
}
};
Array.prototype.findAll = function (predicate) {
function findAll(array, predicate) {
@@ -169,11 +184,16 @@ Array.prototype.findAll = function (predicate) {
}
return findAll(this, predicate);
}
};
Array.prototype.contains = function (value) {
function contains(array, value) {
for (let i = 0, len = array.length; i < len; i++) {
if (array[i] instanceof egret.HashObject && value instanceof egret.HashObject){
if ((array[i] as egret.HashObject).hashCode == (value as egret.HashObject).hashCode)
return true;
}
if (array[i] == value) {
return true;
}
@@ -183,7 +203,7 @@ Array.prototype.contains = function (value) {
}
return contains(this, value);
}
};
Array.prototype.removeAll = function (predicate) {
function removeAll(array, predicate) {
@@ -198,7 +218,7 @@ Array.prototype.removeAll = function (predicate) {
}
removeAll(this, predicate);
}
};
Array.prototype.remove = function (element) {
function remove(array, element) {
@@ -209,14 +229,13 @@ Array.prototype.remove = function (element) {
if (index >= 0) {
array.splice(index, 1);
return true;
}
else {
} else {
return false;
}
}
return remove(this, element);
}
};
Array.prototype.removeAt = function (index) {
function removeAt(array, index) {
@@ -224,7 +243,7 @@ Array.prototype.removeAt = function (index) {
}
return removeAt(this, index);
}
};
Array.prototype.removeRange = function (index, count) {
function removeRange(array, index, count) {
@@ -232,7 +251,7 @@ Array.prototype.removeRange = function (index, count) {
}
return removeRange(this, index, count);
}
};
Array.prototype.select = function (selector) {
function select(array, selector) {
@@ -241,8 +260,7 @@ Array.prototype.select = function (selector) {
ret.push(selector.call(arguments[2], element, index, array));
return ret;
}, []);
}
else {
} else {
let ret = [];
for (let i = 0, len = array.length; i < len; i++) {
ret.push(selector.call(arguments[2], array[i], i, array))
@@ -253,17 +271,16 @@ Array.prototype.select = function (selector) {
}
return select(this, selector);
}
};
Array.prototype.orderBy = function (keySelector, comparer) {
function orderBy(array, keySelector, comparer) {
array.sort(function (x, y) {
let v1 = keySelector(x)
let v2 = keySelector(y)
let v1 = keySelector(x);
let v2 = keySelector(y);
if (comparer) {
return comparer(v1, v2);
}
else {
} else {
return (v1 > v2) ? 1 : -1;
}
});
@@ -272,17 +289,16 @@ Array.prototype.orderBy = function (keySelector, comparer) {
}
return orderBy(this, keySelector, comparer);
}
};
Array.prototype.orderByDescending = function (keySelector, comparer) {
function orderByDescending(array, keySelector, comparer) {
array.sort(function (x, y) {
let v1 = keySelector(x)
let v2 = keySelector(y)
let v1 = keySelector(x);
let v2 = keySelector(y);
if (comparer) {
return -comparer(v1, v2);
}
else {
} else {
return (v1 < v2) ? 1 : -1;
}
});
@@ -291,15 +307,17 @@ Array.prototype.orderByDescending = function (keySelector, comparer) {
}
return orderByDescending(this, keySelector, comparer);
}
};
Array.prototype.groupBy = function (keySelector) {
function groupBy(array, keySelector) {
if (typeof (array.reduce) === "function") {
let keys = [];
return array.reduce(function (groups, element, index) {
let key = JSON.stringify(keySelector.call(arguments[1], element, index, array))
let index2 = keys.findIndex(function (x) { return x === key });
let key = JSON.stringify(keySelector.call(arguments[1], element, index, array));
let index2 = keys.findIndex(function (x) {
return x === key;
});
if (index2 < 0) {
index2 = keys.push(key) - 1;
@@ -312,13 +330,14 @@ Array.prototype.groupBy = function (keySelector) {
groups[index2].push(element);
return groups;
}, []);
}
else {
} else {
let groups = [];
let keys = [];
for (let i = 0, len = array.length; i < len; i++) {
let key = JSON.stringify(keySelector.call(arguments[1], array[i], i, array));
let index = keys.findIndex(function (x) { return x === key });
let index = keys.findIndex(function (x) {
return x === key;
});
if (index < 0) {
index = keys.push(key) - 1;
@@ -336,7 +355,7 @@ Array.prototype.groupBy = function (keySelector) {
}
return groupBy(this, keySelector);
}
};
Array.prototype.sum = function (selector) {
function sum(array, selector) {
@@ -345,17 +364,14 @@ Array.prototype.sum = function (selector) {
if (i == 0) {
if (selector) {
ret = selector.call(arguments[2], array[i], i, array);
} else {
ret = array[i];
}
else {
ret = array[i]
}
}
else {
} else {
if (selector) {
ret += selector.call(arguments[2], array[i], i, array);
}
else {
ret += array[i]
} else {
ret += array[i];
}
}
}
@@ -364,4 +380,4 @@ Array.prototype.sum = function (selector) {
}
return sum(this, selector);
}
};
@@ -1,72 +1,74 @@
class GaussianBlurEffect extends egret.CustomFilter {
// private static blur_frag = "precision mediump float;\n" +
// "uniform vec2 blur;\n" +
// "uniform sampler2D uSampler;\n" +
// "varying vec2 vTextureCoord;\n" +
// "uniform vec2 uTextureSize;\n" +
// "void main()\n" +
// "{\n " +
// "const int sampleRadius = 5;\n" +
// "const int samples = sampleRadius * 2 + 1;\n" +
// "vec2 blurUv = blur / uTextureSize;\n" +
// "vec4 color = vec4(0, 0, 0, 0);\n" +
// "vec2 uv = vec2(0.0, 0.0);\n" +
// "blurUv /= float(sampleRadius);\n" +
// "for (int i = -sampleRadius; i <= sampleRadius; i++) {\n" +
// "uv.x = vTextureCoord.x + float(i) * blurUv.x;\n" +
// "uv.y = vTextureCoord.y + float(i) * blurUv.y;\n" +
// "color += texture2D(uSampler, uv);\n" +
// "}\n" +
// "color /= float(samples);\n" +
// "gl_FragColor = color;\n" +
// "}";
module es {
export class GaussianBlurEffect extends egret.CustomFilter {
// private static blur_frag = "precision mediump float;\n" +
// "uniform vec2 blur;\n" +
// "uniform sampler2D uSampler;\n" +
// "varying vec2 vTextureCoord;\n" +
// "uniform vec2 uTextureSize;\n" +
// "void main()\n" +
// "{\n " +
// "const int sampleRadius = 5;\n" +
// "const int samples = sampleRadius * 2 + 1;\n" +
// "vec2 blurUv = blur / uTextureSize;\n" +
// "vec4 color = vec4(0, 0, 0, 0);\n" +
// "vec2 uv = vec2(0.0, 0.0);\n" +
// "blurUv /= float(sampleRadius);\n" +
private static blur_frag = "precision mediump float;\n" +
"uniform sampler2D uSampler;\n" +
"uniform float screenWidth;\n" +
"uniform float screenHeight;\n" +
// "for (int i = -sampleRadius; i <= sampleRadius; i++) {\n" +
// "uv.x = vTextureCoord.x + float(i) * blurUv.x;\n" +
// "uv.y = vTextureCoord.y + float(i) * blurUv.y;\n" +
// "color += texture2D(uSampler, uv);\n" +
// "}\n" +
"float normpdf(in float x, in float sigma)\n" +
"{\n" +
"return 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;\n" +
"}\n" +
// "color /= float(samples);\n" +
// "gl_FragColor = color;\n" +
// "}";
"void main()\n" +
"{\n" +
"vec3 c = texture2D(uSampler, gl_FragCoord.xy / vec2(screenWidth, screenHeight).xy).rgb;\n" +
private static blur_frag = "precision mediump float;\n" +
"uniform sampler2D uSampler;\n" +
"uniform float screenWidth;\n" +
"uniform float screenHeight;\n" +
"const int mSize = 11;\n" +
"const int kSize = (mSize - 1)/2;\n" +
"float kernel[mSize];\n" +
"vec3 final_colour = vec3(0.0);\n" +
"float normpdf(in float x, in float sigma)\n" +
"{\n" +
"return 0.39894*exp(-0.5*x*x/(sigma*sigma))/sigma;\n" +
"}\n" +
"float sigma = 7.0;\n" +
"float z = 0.0;\n" +
"for (int j = 0; j <= kSize; ++j)\n" +
"{\n" +
"kernel[kSize+j] = kernel[kSize-j] = normpdf(float(j),sigma);\n" +
"}\n" +
"for (int j = 0; j < mSize; ++j)\n" +
"{\n" +
"z += kernel[j];\n" +
"}\n" +
"void main()\n" +
"{\n" +
"vec3 c = texture2D(uSampler, gl_FragCoord.xy / vec2(screenWidth, screenHeight).xy).rgb;\n" +
"for (int i = -kSize; i <= kSize; ++i)\n" +
"{\n" +
"for (int j = -kSize; j <= kSize; ++j)\n" +
"{\n" +
"final_colour += kernel[kSize+j]*kernel[kSize+i]*texture2D(uSampler, (gl_FragCoord.xy+vec2(float(i),float(j))) / vec2(screenWidth, screenHeight).xy).rgb;\n" +
"}\n}\n" +
"gl_FragColor = vec4(final_colour/(z*z), 1.0);\n" +
"}";
"const int mSize = 11;\n" +
"const int kSize = (mSize - 1)/2;\n" +
"float kernel[mSize];\n" +
"vec3 final_colour = vec3(0.0);\n" +
constructor(){
super(PostProcessor.default_vert, GaussianBlurEffect.blur_frag,{
screenWidth: SceneManager.stage.stageWidth,
screenHeight: SceneManager.stage.stageHeight
});
"float sigma = 7.0;\n" +
"float z = 0.0;\n" +
"for (int j = 0; j <= kSize; ++j)\n" +
"{\n" +
"kernel[kSize+j] = kernel[kSize-j] = normpdf(float(j),sigma);\n" +
"}\n" +
"for (int j = 0; j < mSize; ++j)\n" +
"{\n" +
"z += kernel[j];\n" +
"}\n" +
"for (int i = -kSize; i <= kSize; ++i)\n" +
"{\n" +
"for (int j = -kSize; j <= kSize; ++j)\n" +
"{\n" +
"final_colour += kernel[kSize+j]*kernel[kSize+i]*texture2D(uSampler, (gl_FragCoord.xy+vec2(float(i),float(j))) / vec2(screenWidth, screenHeight).xy).rgb;\n" +
"}\n}\n" +
"gl_FragColor = vec4(final_colour/(z*z), 1.0);\n" +
"}";
constructor() {
super(PostProcessor.default_vert, GaussianBlurEffect.blur_frag, {
screenWidth: Core.graphicsDevice.viewport.width,
screenHeight: Core.graphicsDevice.viewport.height
});
}
}
}
}
@@ -1,34 +1,36 @@
class PolygonLightEffect extends egret.CustomFilter {
private static vertSrc = "attribute vec2 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" +
module es {
export class PolygonLightEffect extends egret.CustomFilter {
private static vertSrc = "attribute vec2 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" +
"uniform vec2 projectionVector;\n" +
"uniform vec2 projectionVector;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"const vec2 center = vec2(-1.0, 1.0);\n" +
"const vec2 center = vec2(-1.0, 1.0);\n" +
"void main(void) {\n" +
" gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n" +
" vTextureCoord = aTextureCoord;\n" +
"}";
private static fragmentSrc = "precision lowp float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform sampler2D uSampler;\n" +
"void main(void) {\n" +
" gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n" +
" vTextureCoord = aTextureCoord;\n" +
"}";
private static fragmentSrc = "precision lowp float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform sampler2D uSampler;\n" +
"#define SAMPLE_COUNT 15\n" +
"#define SAMPLE_COUNT 15\n" +
"uniform vec2 _sampleOffsets[SAMPLE_COUNT];\n" +
"uniform float _sampleWeights[SAMPLE_COUNT];\n" +
"uniform vec2 _sampleOffsets[SAMPLE_COUNT];\n" +
"uniform float _sampleWeights[SAMPLE_COUNT];\n" +
"void main(void) {\n" +
"vec4 c = vec4(0, 0, 0, 0);\n" +
"for( int i = 0; i < SAMPLE_COUNT; i++ )\n" +
" c += texture2D( uSampler, vTextureCoord + _sampleOffsets[i] ) * _sampleWeights[i];\n" +
"gl_FragColor = c;\n" +
"}";
"void main(void) {\n" +
"vec4 c = vec4(0, 0, 0, 0);\n" +
"for( int i = 0; i < SAMPLE_COUNT; i++ )\n" +
" c += texture2D( uSampler, vTextureCoord + _sampleOffsets[i] ) * _sampleWeights[i];\n" +
"gl_FragColor = c;\n" +
"}";
constructor(){
super(PolygonLightEffect.vertSrc, PolygonLightEffect.fragmentSrc);
constructor() {
super(PolygonLightEffect.vertSrc, PolygonLightEffect.fragmentSrc);
}
}
}
}
+28 -30
View File
@@ -1,33 +1,31 @@
class GraphicsCapabilities {
public supportsTextureFilterAnisotropic: boolean;
public supportsNonPowerOfTwo: boolean;
public supportsDepth24: boolean;
public supportsPackedDepthStencil: boolean;
public supportsDepthNonLinear: boolean;
public supportsTextureMaxLevel: boolean;
public supportsS3tc: boolean;
public supportsDxt1: boolean;
public supportsPvrtc: boolean;
public supportsAtitc: boolean;
public supportsFramebufferObjectARB: boolean;
module es {
export class GraphicsCapabilities extends egret.Capabilities {
public initialize(device: GraphicsDevice){
this.platformInitialize(device);
}
public initialize(device: GraphicsDevice) {
this.platformInitialize(device);
}
private platformInitialize(device: GraphicsDevice){
let gl: WebGLRenderingContext = new egret.sys.RenderBuffer().context.getInstance();
this.supportsNonPowerOfTwo = false;
this.supportsTextureFilterAnisotropic = gl.getExtension("EXT_texture_filter_anisotropic") != null;
this.supportsDepth24 = true;
this.supportsPackedDepthStencil = true;
this.supportsDepthNonLinear = false;
this.supportsTextureMaxLevel = true;
this.supportsS3tc = gl.getExtension("WEBGL_compressed_texture_s3tc") != null ||
gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") != null;
this.supportsDxt1 = this.supportsS3tc;
this.supportsPvrtc = false;
this.supportsAtitc = gl.getExtension("WEBGL_compressed_texture_astc") != null;
this.supportsFramebufferObjectARB = false;
private platformInitialize(device: GraphicsDevice) {
if (GraphicsCapabilities.runtimeType != egret.RuntimeType.WXGAME)
return;
let capabilities = this;
capabilities["isMobile"] = true;
let systemInfo = wx.getSystemInfoSync();
let systemStr = systemInfo.system.toLowerCase();
if (systemStr.indexOf("ios") > -1) {
capabilities["os"] = "iOS";
} else if (systemStr.indexOf("android") > -1) {
capabilities["os"] = "Android";
}
let language = systemInfo.language;
if (language.indexOf('zh') > -1) {
language = "zh-CN";
} else {
language = "en-US";
}
capabilities["language"] = language;
}
}
}
}
+18 -7
View File
@@ -1,10 +1,21 @@
class GraphicsDevice {
private viewport: Viewport;
module es {
export class GraphicsDevice {
public graphicsCapabilities: GraphicsCapabilities;
public graphicsCapabilities: GraphicsCapabilities;
constructor() {
this.setup();
this.graphicsCapabilities = new GraphicsCapabilities();
this.graphicsCapabilities.initialize(this);
}
constructor(){
this.graphicsCapabilities = new GraphicsCapabilities();
this.graphicsCapabilities.initialize(this);
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);
}
}
}
}
@@ -1,58 +1,60 @@
class PostProcessor {
public enable: boolean;
public effect: egret.Filter;
public scene: Scene;
public shape: egret.Shape;
module es {
export class PostProcessor {
public static default_vert = "attribute vec2 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" +
"attribute vec2 aColor;\n" +
public static default_vert = "attribute vec2 aVertexPosition;\n" +
"attribute vec2 aTextureCoord;\n" +
"attribute vec2 aColor;\n" +
"uniform vec2 projectionVector;\n" +
//"uniform vec2 offsetVector;\n" +
"uniform vec2 projectionVector;\n" +
//"uniform vec2 offsetVector;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec4 vColor;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec4 vColor;\n" +
"const vec2 center = vec2(-1.0, 1.0);\n" +
"const vec2 center = vec2(-1.0, 1.0);\n" +
"void main(void) {\n" +
"gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n" +
"vTextureCoord = aTextureCoord;\n" +
"vColor = vec4(aColor.x, aColor.x, aColor.x, aColor.x);\n" +
"}";
"void main(void) {\n" +
"gl_Position = vec4( (aVertexPosition / projectionVector) + center , 0.0, 1.0);\n" +
"vTextureCoord = aTextureCoord;\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){
this.enable = true;
this.effect = effect;
}
public onAddedToScene(scene: Scene){
this.scene = scene;
this.shape = new egret.Shape();
this.shape.graphics.beginFill(0xFFFFFF, 1);
this.shape.graphics.drawRect(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
this.shape.graphics.endFill();
scene.addChild(this.shape);
}
public process(){
this.drawFullscreenQuad();
}
public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number){}
protected drawFullscreenQuad(){
this.scene.filters = [this.effect];
// this.shape.filters = [this.effect];
}
public unload(){
if (this.effect){
this.effect = null;
constructor(effect: egret.Filter = null) {
this.enabled = true;
this.effect = effect;
}
this.scene.removeChild(this.shape);
this.scene = null;
public onAddedToScene(scene: Scene) {
this.scene = scene;
this.shape = new egret.Shape();
this.shape.graphics.beginFill(0xFFFFFF, 1);
this.shape.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height);
this.shape.graphics.endFill();
scene.addChild(this.shape);
}
public process() {
this.drawFullscreenQuad();
}
public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number) {
}
public unload() {
if (this.effect) {
this.effect = null;
}
this.scene.removeChild(this.shape);
this.scene = null;
}
protected drawFullscreenQuad() {
this.scene.filters = [this.effect];
// this.shape.filters = [this.effect];
}
}
}
}
@@ -1,6 +1,8 @@
class GaussianBlurPostProcessor extends PostProcessor {
public onAddedToScene(scene: Scene){
super.onAddedToScene(scene);
this.effect = new GaussianBlurEffect();
module es {
export class GaussianBlurPostProcessor extends PostProcessor {
public onAddedToScene(scene: Scene) {
super.onAddedToScene(scene);
this.effect = new GaussianBlurEffect();
}
}
}
}
@@ -1,13 +1,19 @@
///<reference path="./Renderer.ts" />
class DefaultRenderer extends Renderer {
public render(scene: Scene) {
let cam = this.camera ? this.camera : scene.camera;
this.beginRender(cam);
module es {
export class DefaultRenderer extends Renderer {
constructor() {
super(0, null);
}
for (let i = 0; i < scene.renderableComponents.count; i++){
let renderable = scene.renderableComponents.buffer[i];
if (renderable.enabled && renderable.isVisibleFromCamera(cam))
this.renderAfterStateCheck(renderable, cam);
public render(scene: Scene) {
let cam = this.camera ? this.camera : scene.camera;
this.beginRender(cam);
for (let i = 0; i < scene.renderableComponents.count; i++) {
let renderable = scene.renderableComponents.buffer[i];
if (renderable.enabled && renderable.isVisibleFromCamera(cam))
this.renderAfterStateCheck(renderable, cam);
}
}
}
}
}
+47 -7
View File
@@ -1,7 +1,47 @@
interface IRenderable {
bounds: Rectangle;
enabled: boolean;
isVisible: boolean;
isVisibleFromCamera(camera: Camera);
render(camera: Camera);
}
module es {
/**
*
*
*/
export interface IRenderable {
/**
* AABB用于相机剔除
*/
bounds: Rectangle;
/**
*
*/
enabled: boolean;
/**
*
*/
renderLayer: number;
/**
* onBecameVisible/onBecameInvisible方法
*/
isVisible: boolean;
/**
* renderableComponent的边界与camera.bounds相交 true
* isVisible标志的状态开关
* 使
* @param camera
*/
isVisibleFromCamera(camera: Camera);
/**
* 使
* @param camera
*/
render(camera: Camera);
}
/**
* IRenderables的比较器
*/
export class RenderableComparer {
public compare(self: IRenderable, other: IRenderable) {
return other.renderLayer - self.renderLayer;
}
}
}
@@ -1,46 +1,50 @@
class PolyLight extends RenderableComponent {
public power: number;
protected _radius: number;
private _lightEffect;
private _indices: number[] = [];
module es {
export class PolyLight extends RenderableComponent {
public power: number;
private _lightEffect;
private _indices: number[] = [];
public get radius(){
return this._radius;
}
public set radius(value: number){
this.setRadius(value);
}
constructor(radius: number, color: number, power: number) {
super();
constructor(radius: number, color: number, power: number){
super();
this.radius = radius;
this.power = power;
this.color = color;
this.computeTriangleIndices();
}
this.radius = radius;
this.power = power;
this.color = color;
this.computeTriangleIndices();
}
protected _radius: number;
private computeTriangleIndices(totalTris: number = 20){
this._indices.length = 0;
public get radius() {
return this._radius;
}
for (let i = 0; i < totalTris; i += 2){
this._indices.push(0);
this._indices.push(i + 2);
this._indices.push(i + 1);
public set radius(value: number) {
this.setRadius(value);
}
public setRadius(radius: number) {
if (radius != this._radius) {
this._radius = radius;
this._areBoundsDirty = true;
}
}
public render(camera: Camera) {
}
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);
}
}
}
public setRadius(radius: number){
if (radius != this._radius){
this._radius = radius;
this._areBoundsDirty = true;
}
}
public render(camera: Camera) {
}
public reset(){
}
}
}
+62 -34
View File
@@ -1,38 +1,66 @@
/**
* RenderableComponent的实际调用
*/
abstract class Renderer {
/**
* ()
*
* Renderer子类可以选择调用beginRender时使用的摄像头
*/
public camera: Camera;
module es {
/**
*
* @param scene
* RenderableComponent的实际调用
*/
public onAddedToScene(scene: Scene){}
export abstract class Renderer {
/**
* ()
*
* Renderer子类可以选择调用beginRender时使用的摄像头
*/
public camera: Camera;
/**
*
*/
public readonly renderOrder: number = 0;
protected beginRender(cam: Camera){
protected constructor(renderOrder: number, camera: Camera = null) {
this.camera = camera;
this.renderOrder = renderOrder;
}
/**
*
* @param scene
*/
public onAddedToScene(scene: Scene) {
}
/**
* 使
*/
public unload() {
}
public abstract render(scene: Scene);
/**
*
* @param newWidth
* @param newHeight
*/
public onSceneBackBufferSizeChanged(newWidth: number, newHeight: number) {
}
public compareTo(other: Renderer): number {
return this.renderOrder - other.renderOrder;
}
/**
*
* @param cam
*/
protected beginRender(cam: Camera) {
}
/**
*
* @param renderable
* @param cam
*/
protected renderAfterStateCheck(renderable: IRenderable, cam: Camera) {
renderable.render(cam);
}
}
/**
*
* @param scene
*/
public abstract render(scene: Scene);
public unload(){ }
/**
*
* @param renderable
* @param cam
*/
protected renderAfterStateCheck(renderable: IRenderable, cam: Camera){
renderable.render(cam);
}
}
}
@@ -1,7 +1,9 @@
/**
* 使
*/
class ScreenSpaceRenderer extends Renderer {
public render(scene: Scene) {
module es {
/**
* 使
*/
export class ScreenSpaceRenderer extends Renderer {
public render(scene: Scene) {
}
}
}
}
@@ -1,38 +1,38 @@
///<reference path="./SceneTransition.ts"/>
class FadeTransition extends SceneTransition {
public fadeToColor: number = 0x000000;
public fadeOutDuration = 0.4;
public fadeEaseType: Function = egret.Ease.quadInOut;
public delayBeforeFadeInDuration = 0.1;
private _mask: egret.Shape;
private _alpha: number = 0;
module es {
export class FadeTransition extends SceneTransition {
public fadeToColor: number = 0x000000;
public fadeOutDuration = 0.4;
public fadeEaseType: Function = egret.Ease.quadInOut;
public delayBeforeFadeInDuration = 0.1;
private _mask: egret.Shape;
private _alpha: number = 0;
constructor(sceneLoadAction: Function) {
super(sceneLoadAction);
this._mask = new egret.Shape();
}
constructor(sceneLoadAction: Function) {
super(sceneLoadAction);
this._mask = new egret.Shape();
}
public async onBeginTransition() {
this._mask.graphics.beginFill(this.fadeToColor, 1);
this._mask.graphics.drawRect(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
this._mask.graphics.endFill();
SceneManager.stage.addChild(this._mask);
public async onBeginTransition() {
this._mask.graphics.beginFill(this.fadeToColor, 1);
this._mask.graphics.drawRect(0, 0, Core.graphicsDevice.viewport.width, Core.graphicsDevice.viewport.height);
this._mask.graphics.endFill();
egret.Tween.get(this).to({ _alpha: 1}, this.fadeOutDuration * 1000, this.fadeEaseType)
.call(async () => {
await this.loadNextScene();
}).wait(this.delayBeforeFadeInDuration).call(() => {
egret.Tween.get(this).to({ _alpha: 0 }, this.fadeOutDuration * 1000, this.fadeEaseType).call(() => {
egret.Tween.get(this).to({_alpha: 1}, this.fadeOutDuration * 1000, this.fadeEaseType)
.call(async () => {
await this.loadNextScene();
}).wait(this.delayBeforeFadeInDuration).call(() => {
egret.Tween.get(this).to({_alpha: 0}, this.fadeOutDuration * 1000, this.fadeEaseType).call(() => {
this.transitionComplete();
SceneManager.stage.removeChild(this._mask);
});
});
}
}
public render(){
this._mask.graphics.clear();
this._mask.graphics.beginFill(this.fadeToColor, this._alpha);
this._mask.graphics.drawRect(0, 0, SceneManager.stage.stageWidth, SceneManager.stage.stageHeight);
this._mask.graphics.endFill();
public render() {
this._mask.graphics.clear();
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.endFill();
}
}
}
}

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