diff --git a/cocos/2d/profiler/CCProfiler.js b/cocos/2d/profiler/CCProfiler.js deleted file mode 100644 index 363ab3c84e..0000000000 --- a/cocos/2d/profiler/CCProfiler.js +++ /dev/null @@ -1,247 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -var macro = require('../../platform/CCMacro'); - -const PerfCounter = require('./perf-counter'); - -let _showFPS = false; -let _fontSize = 15; - -let _atlas = null; -let _stats = null; -let _rootNode = null; -let _label = null; - -function generateAtlas () { - if (_atlas) return; - - let textureWidth = 256, - textureHeight = 256; - - let canvas = document.createElement("canvas"); - canvas.style.width = canvas.width = textureWidth; - canvas.style.height = canvas.height = textureHeight; - - // comment out this to show atlas - // document.body.appendChild(canvas) - - let ctx = canvas.getContext('2d'); - ctx.font = `${_fontSize}px Arial`; - ctx.textBaseline = 'top'; - ctx.textAlign = 'left'; - ctx.fillStyle = '#fff'; - - let space = 2; - let x = space; - let y = space; - let lineHeight = _fontSize; - - _atlas = new cc.LabelAtlas(); - _atlas._fntConfig = { - atlasName: 'profiler-arial', - commonHeight: lineHeight, - fontSize: _fontSize, - kerningDict: {}, - fontDefDictionary: {} - }; - - _atlas._name = 'profiler-arial'; - _atlas.fontSize = _fontSize; - - let dict = _atlas._fntConfig.fontDefDictionary; - - for (let i = 32; i <= 126; i++) { - let char = String.fromCharCode(i); - let width = ctx.measureText(char).width; - - if ((x + width) >= textureWidth) { - x = space; - y += lineHeight + space; - } - ctx.fillText(char, x, y); - - dict[i] = { - xAdvance: width, - xOffset: 0, - yOffset: 0, - rect: { - x: x, - y: y, - width: width, - height: lineHeight - } - } - - x += width + space; - } - - let texture = new cc.Texture2D(); - texture.image = new ImageAsset(canvas); - - let spriteFrame = new cc.SpriteFrame(); - spriteFrame.setTexture(texture); - - _atlas.spriteFrame = spriteFrame; -} - -function generateStats () { - if (_stats) return; - - _stats = { - frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: 500 }, - fps: { desc: 'Framerate (FPS)', below: 30, average: 500 }, - draws: { desc: 'Draw call' }, - logic: { desc: 'Game Logic (ms)', min: 0, max: 50, average: 500, color: '#080' }, - render: { desc: 'Renderer (ms)', min: 0, max: 50, average: 500, color: '#f90' }, - mode: { desc: cc.game.renderType === cc.game.RENDER_TYPE_WEBGL ? 'WebGL' : 'Canvas', min: 1 } - }; - - let now = performance.now(); - for (let id in _stats) { - _stats[id]._counter = new PerfCounter(id, _stats[id], now); - } -} - -function generateNode () { - if (_rootNode && _rootNode.isValid) return; - - - _rootNode = new cc.Node('PROFILER-NODE'); - _rootNode.x = _rootNode.y = 10; - - _rootNode.groupIndex = cc.Node.BuiltinGroupIndex.DEBUG; - cc.Camera._setupDebugCamera(); - - _rootNode.zIndex = macro.MAX_ZINDEX; - cc.game.addPersistRootNode(_rootNode); - - let left = new cc.Node('LEFT-PANEL'); - left.anchorX = left.anchorY = 0; - left.parent = _rootNode; - let leftLabel = left.addComponent(cc.Label); - leftLabel.font = _atlas; - leftLabel.fontSize = _fontSize; - leftLabel.lineHeight = _fontSize; - - let right = new cc.Node('RIGHT-PANEL'); - right.anchorX = 1; - right.anchorY = 0; - right.x = 200; - right.parent = _rootNode; - let rightLabel = right.addComponent(cc.Label); - rightLabel.horizontalAlign = cc.Label.HorizontalAlign.RIGHT; - rightLabel.font = _atlas; - rightLabel.fontSize = _fontSize; - rightLabel.lineHeight = _fontSize; - - _label = { - left: leftLabel, - right: rightLabel - }; -} - -function beforeUpdate () { - generateNode(); - - let now = cc.director._lastUpdate; - _stats['frame']._counter.start(now); - _stats['logic']._counter.start(now); -} - -function afterUpdate () { - let now = performance.now(); - if (cc.director.isPaused()) { - _stats['frame']._counter.start(now); - } - else { - _stats['logic']._counter.end(now); - } - _stats['render']._counter.start(now); -} - -function updateLabel (stat) { - let length = 20; - let desc = stat.desc; - let value = stat._counter.human() + ''; - stat.label.string = stat.desc + ' ' + stat._counter.human(); -} - -function afterDraw () { - let now = performance.now(); - _stats['render']._counter.end(now); - _stats['draws']._counter.value = cc.renderer.drawCalls; - _stats['frame']._counter.end(now); - _stats['fps']._counter.frame(now); - - let left = ''; - let right = ''; - for (let id in _stats) { - let stat = _stats[id]; - stat._counter.sample(now); - - left += stat.desc + '\n'; - right += stat._counter.human() + '\n'; - } - - _label.left.string = left; - _label.right.string = right; -} - -cc.profiler = module.exports = { - isShowingStats () { - return _showFPS; - }, - - hideStats () { - if (_showFPS) { - if (_rootNode) { - _rootNode.active = false; - } - - cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate); - cc.director.off(cc.Director.EVENT_AFTER_UPDATE, afterUpdate); - cc.director.off(cc.Director.EVENT_AFTER_DRAW, afterDraw); - _showFPS = false; - } - }, - - showStats () { - if (!_showFPS) { - generateAtlas(); - generateStats(); - - if (_rootNode) { - _rootNode.active = true; - } - - cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate); - cc.director.on(cc.Director.EVENT_AFTER_UPDATE, afterUpdate); - cc.director.on(cc.Director.EVENT_AFTER_DRAW, afterDraw); - _showFPS = true; - } - } -} \ No newline at end of file diff --git a/cocos/2d/profiler/counter.js b/cocos/2d/profiler/counter.js deleted file mode 100644 index f29c1912fb..0000000000 --- a/cocos/2d/profiler/counter.js +++ /dev/null @@ -1,58 +0,0 @@ -let Counter = cc.Class({ - name: 'cc.Counter', - ctor (id, opts, now) { - this._id = id; - this._opts = opts || {}; - - this._value = 0; - this._total = 0; - this._averageValue = 0; - this._accumValue = 0; - this._accumSamples = 0; - this._accumStart = now; - }, - - properties: { - value: { - get () { - return this._value; - }, - set (v) { - this._value = v; - } - } - }, - - _average (v, now) { - if (this._opts.average) { - this._accumValue += v; - ++this._accumSamples; - - let t = now; - if (t - this._accumStart >= this._opts.average) { - this._averageValue = this._accumValue / this._accumSamples; - this._accumValue = 0; - this._accumStart = t; - this._accumSamples = 0; - } - } - }, - - sample (now) { - this._average(this._value, now); - }, - - human () { - let v = this._opts.average ? this._averageValue : this._value; - return Math.round(v * 100) / 100; - }, - - alarm () { - return ( - (this._opts.below && this._value < this._opts.below) || - (this._opts.over && this._value > this._opts.over) - ); - } -}) - -module.exports = Counter; diff --git a/cocos/2d/profiler/perf-counter.js b/cocos/2d/profiler/perf-counter.js deleted file mode 100644 index b7958ea17f..0000000000 --- a/cocos/2d/profiler/perf-counter.js +++ /dev/null @@ -1,52 +0,0 @@ -const Counter = require('./counter'); - -let PerfCounter = cc.Class({ - name: 'cc.PerfCounter', - extends: Counter, - - ctor (id, opts, now) { - // DISABLE - // this._idstart = `${id}_start`; - // this._idend = `${id}_end`; - - this._time = now; - }, - - start(now) { - this._time = now; - - // DISABLE: long time running will cause performance drop down - // window.performance.mark(this._idstart); - }, - - end(now) { - this._value = now - this._time; - - // DISABLE: long time running will cause performance drop down - // window.performance.mark(this._idend); - // window.performance.measure(this._id, this._idstart, this._idend); - - this._average(this._value); - }, - - tick() { - this.end(); - this.start(); - }, - - frame(now) { - let t = now; - let e = t - this._time; - this._total++; - let avg = this._opts.average || 1000; - - if (e > avg) { - this._value = this._total * 1000 / e; - this._total = 0; - this._time = t; - this._average(this._value); - } - } -}); - -module.exports = PerfCounter; diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 3d61ee00e8..f599ea0b73 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -173,12 +173,31 @@ export class Material extends Asset { for (let i = 0; i < mat._props.length; i++) { Object.assign(this._props[i], mat._props[i]); } - Object.assign(this._defines, mat._defines); + this._defines.length = mat._defines.length; + this._defines.fill({}); + for (let i = 0; i < mat._defines.length; i++) { + Object.assign(this._defines[i], mat._defines[i]); + } Object.assign(this._states, mat._states); this._effectAsset = mat._effectAsset; this._update(); } + public recompileShaders (defineOverrides: IDefineMap | IDefineMap[]) { + const passes = this._passes; + const len = passes.length; + if (Array.isArray(defineOverrides)) { + for (let i = 0; i < len; i++) { + passes[i].tryCompile(defineOverrides[i]); + } + } else { + for (let i = 0; i < len; i++) { + passes[i].tryCompile(defineOverrides); + } + } + this._onPassesChange(); + } + public overridePipelineStates (overrides: PassOverrides, passIdx?: number) { if (!this._passes || !this._effectAsset) { return; } const passInfos = Effect.getPassesInfo(this._effectAsset, this._techIdx); @@ -208,28 +227,30 @@ export class Material extends Asset { protected _update (keepProps: boolean = true) { const asset = this._effectAsset; - // ugly yellow indicating missing effect - if (!asset) { this._passes = builtinResMgr.get('missing-effect-material')._passes.slice(); return; } - // create passes - this._passes = Effect.parseEffect(asset, { - techIdx: this._techIdx, - defines: this._defines, - states: this._states, - }); - // handle property values - this._props.length = this._passes.length; - if (keepProps) { - this._passes.forEach((pass, i) => { - let props = this._props[i]; - if (!props) { props = this._props[i] = {}; } - for (const p of Object.keys(props)) { - const val = props[p]; - if (!val) { continue; } - this._uploadProperty(pass, p, props[p]); - } + if (asset) { + // create passes + this._passes = Effect.parseEffect(asset, { + techIdx: this._techIdx, + defines: this._defines, + states: this._states, }); - } else { - this._props.fill({}); + // handle property values + this._props.length = this._passes.length; + if (keepProps) { + this._passes.forEach((pass, i) => { + let props = this._props[i]; + if (!props) { props = this._props[i] = {}; } + for (const p of Object.keys(props)) { + const val = props[p]; + if (!val) { continue; } + this._uploadProperty(pass, p, props[p]); + } + }); + } else { + this._props.fill({}); + } + } else { // ugly yellow indicating missing effect + this._passes = builtinResMgr.get('missing-effect-material')._passes.slice(); } this._onPassesChange(); } diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts index 1ab299858f..9f3bb6bef2 100644 --- a/cocos/3d/builtin/init.ts +++ b/cocos/3d/builtin/init.ts @@ -158,10 +158,16 @@ class BuiltinResMgr { // sprite material const spriteMtl = new cc.Material(); - spriteMtl._uuid = 'ui-sprite-material'; - spriteMtl.initialize({ defines: { USE_TEXTURE: true }, effectName: 'builtin-sprite' }); + spriteMtl._uuid = 'ui-base-material'; + spriteMtl.initialize({ defines: { USE_TEXTURE: false }, effectName: 'builtin-sprite' }); resources[spriteMtl._uuid] = spriteMtl; + // sprite material + const spriteColorMtl = new cc.Material(); + spriteColorMtl._uuid = 'ui-sprite-material'; + spriteColorMtl.initialize({ defines: { USE_TEXTURE: true }, effectName: 'builtin-sprite' }); + resources[spriteColorMtl._uuid] = spriteColorMtl; + // default particle material const defaultParticleMtl = new cc.Material(); defaultParticleMtl._uuid = 'default-particle-material'; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 50bc409f50..d54c4a7257 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -320,7 +320,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { } else { console.warn(`particle system renderMode ${this._renderMode} not support.`); } - for (const pass of mat!.passes) { pass.tryCompile(this._defines); } + mat!.recompileShaders(this._defines); if (this.particleSystem.textureAnimationModule.enable) { mat!.setProperty('frameTile_velLenScale', vec2.set(this.frameTile_velLenScale, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts index 722d1b1630..ed6c563814 100644 --- a/cocos/3d/framework/physics/collider-component.ts +++ b/cocos/3d/framework/physics/collider-component.ts @@ -12,19 +12,22 @@ import { createBoxShape, createSphereShape, ERigidBodyType } from '../../physics import { PhysicsBasedComponent } from './detail/physics-based-component'; export class ColliderComponentBase extends PhysicsBasedComponent { - protected _shapeBase: ShapeBase | null = null; + protected _shapeBase!: ShapeBase; @property private _triggered: boolean = false; + @property get isTrigger () { return this._triggered; } + set isTrigger (value) { this._triggered = value; + + const type = this._triggered ? ERigidBodyType.DYNAMIC : ERigidBodyType.STATIC; if (this._body) { - const type = this._triggered ? ERigidBodyType.DYNAMIC : ERigidBodyType.STATIC; this._body.setType(type); - this._body.setIsTrigger(value); } + this._shapeBase.setCollisionResponse(!this._triggered); } /** @@ -37,7 +40,7 @@ export class ColliderComponentBase extends PhysicsBasedComponent { set center (value: Vec3) { vec3.copy(this._center, value); - this._shapeBase!.setCenter(this._center); + this._shapeBase.setCenter(this._center); } @property @@ -47,17 +50,29 @@ export class ColliderComponentBase extends PhysicsBasedComponent { super(); } + public __preload () { + super.__preload(); + + this.center = this._center; + this.isTrigger = this._triggered; + + if (this._enabled) { + this.onEnable(); + } + } + public onLoad () { super.onLoad(); - this.center = this._center; } public start () { super.start(); - if (this._enabled) { - this.onEnable(); + } + + public lateUpdate () { + if (this.node.hasChanged) { + this._shapeBase.setScale(this.node._scale); } - this.isTrigger = this._triggered; } public onEnable () { @@ -88,18 +103,25 @@ export class BoxColliderComponent extends ColliderComponentBase { @property private _size: Vec3 = new Vec3(0, 0, 0); - private _shape: BoxShapeBase; + private _shape: BoxShapeBase | undefined; constructor () { super(); + } + + public __preload () { + // 父类在__preload要对_shapeBase进行操作,需要保证其已经构造完成 this._shape = createBoxShape(this._size); this._shape.setUserData(this); this._shapeBase = this._shape; + + super.__preload(); + + this._shape.setScale(this.node._scale); } public onLoad () { super.onLoad(); - this.size = this._size; } /** @@ -113,7 +135,7 @@ export class BoxColliderComponent extends ColliderComponentBase { set size (value) { vec3.copy(this._size, value); - this._shape.setSize(this._size); + this._shape!.setSize(this._size); if (this.sharedBody) { this.sharedBody.body.commitShapeUpdates(); } @@ -128,18 +150,27 @@ export class SphereColliderComponent extends ColliderComponentBase { @property private _radius: number = 0; - private _shape: SphereShapeBase; + private _shape!: SphereShapeBase; constructor () { super(); + } + + public __preload () { + + // const scale = this.node._scale; + // const max = Math.abs(Math.max(scale.x, Math.max(scale.y, scale.z))); this._shape = createSphereShape(this._radius); this._shape.setUserData(this); this._shapeBase = this._shape; + + super.__preload(); + + this._shape.setScale(this.node._scale); } public onLoad () { super.onLoad(); - this.radius = this._radius; } /** diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts index 4c1ac33fb3..6eb20448c1 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -10,23 +10,26 @@ import { stringfyQuat, stringfyVec3 } from '../../../physics/util'; export class PhysicsBasedComponent extends Component { protected get _body () { - return this._sharedBody ? this._sharedBody.body : null; + return this._sharedBody!.body; } protected get sharedBody () { return this._sharedBody; } - private _sharedBody: SharedRigidBody | null = null; + private _sharedBody!: SharedRigidBody | null; constructor () { super(); } + public __preload () { + this._refSharedBody(); + } + public onLoad () { } public start () { - this._refSharedBody(); } public destroy () { @@ -36,11 +39,11 @@ export class PhysicsBasedComponent extends Component { } } - public syncPhysWithScene () { - if (this.sharedBody) { - this.sharedBody.syncPhysWithScene(this.node); - } - } + // public syncPhysWithScene () { + // if (this.sharedBody) { + // this.sharedBody.syncPhysWithScene(this.node); + // } + // } private _refSharedBody () { if (this._sharedBody) { @@ -124,17 +127,18 @@ class SharedRigidBody { } public syncPhysWithScene (node: Node) { - this._transformInitialized = true; + // sync position rotation const p = node.getWorldPosition(); const r = node.getWorldRotation(); this.body.setPosition(p); this.body.setRotation(r); - node.getWorldScale(this._worldScale); - // Because we sync the scale, we should update shape parameters. - this.body.scaleAllShapes(this._worldScale); - this.body.commitShapeUpdates(); + // remove to shape, scale belong to shape + // node.getWorldScale(this._worldScale); + // // Because we sync the scale, we should update shape parameters. + // this.body.scaleAllShapes(this._worldScale); + // this.body.commitShapeUpdates(); } /** @@ -196,9 +200,12 @@ class SharedRigidBody { if (!this._transformInitialized) { // d(`Initialize`); + this._transformInitialized = true; this.syncPhysWithScene(this._node); this._activeBody(); - } else if (!this.body.isPhysicsManagedTransform() && this._node.hasChanged) { + } + + if (!this.body.isPhysicsManagedTransform() && this._node.hasChanged) { // d(`Synchronize`); this.syncPhysWithScene(this._node); this._activeBody(); diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 039df7523d..0399c28f3e 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -198,8 +198,8 @@ export class RigidBodyComponent extends PhysicsBasedComponent { this._body!.applyForce(force, position); } - public applyImpulse (impulse: Vec3) { - this._body!.applyImpulse(impulse); + public applyImpulse (impulse: Vec3, position?: Vec3) { + this._body!.applyImpulse(impulse, position); } public setCollisionFilter (group: number, mask: number) { diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts index 15a5e4815c..a99d351dd7 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/3d/framework/skinning-model-component.ts @@ -147,8 +147,7 @@ export class SkinningModelComponent extends ModelComponent { const device = _getGlobalDevice(); const useJointTexture = device !== null && useJointsTexture(device); const mat = this.getMaterial(index, CC_EDITOR)!; - const defines = { CC_USE_SKINNING: true, CC_USE_JOINTS_TEXTURE: useJointTexture }; - for (const pass of mat.passes) { pass.tryCompile(defines); } + mat.recompileShaders({ CC_USE_SKINNING: true, CC_USE_JOINTS_TEXTURE: useJointTexture }); super._onMaterialModified(index, mat); } diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/3d/geom-utils/frustum.ts index 878fd0790f..d734e48c5c 100644 --- a/cocos/3d/geom-utils/frustum.ts +++ b/cocos/3d/geom-utils/frustum.ts @@ -1,3 +1,4 @@ +import { Vec3 } from '../../core/value-types'; import { mat4, vec3 } from '../../core/vmath'; import enums from './enums'; import plane from './plane'; @@ -31,6 +32,37 @@ export class frustum { return new frustum(); } + public static createOrtho = (() => { + const _temp_v3 = new Vec3(); + return (out: frustum, width: number, height: number, near: number, far: number, transform: mat4) => { + const halfWidth = width / 2; + const halfHeight = height / 2; + vec3.set(_temp_v3, halfWidth, halfHeight, near); + vec3.transformMat4(out.vertices[0], _temp_v3, transform); + vec3.set(_temp_v3, -halfWidth, halfHeight, near); + vec3.transformMat4(out.vertices[1], _temp_v3, transform); + vec3.set(_temp_v3, -halfWidth, -halfHeight, near); + vec3.transformMat4(out.vertices[2], _temp_v3, transform); + vec3.set(_temp_v3, halfWidth, -halfHeight, near); + vec3.transformMat4(out.vertices[3], _temp_v3, transform); + vec3.set(_temp_v3, halfWidth, halfHeight, far); + vec3.transformMat4(out.vertices[4], _temp_v3, transform); + vec3.set(_temp_v3, -halfWidth, halfHeight, far); + vec3.transformMat4(out.vertices[5], _temp_v3, transform); + vec3.set(_temp_v3, -halfWidth, -halfHeight, far); + vec3.transformMat4(out.vertices[6], _temp_v3, transform); + vec3.set(_temp_v3, halfWidth, -halfHeight, far); + vec3.transformMat4(out.vertices[7], _temp_v3, transform); + + plane.fromPoints(out.planes[0], out.vertices[1], out.vertices[6], out.vertices[5]); + plane.fromPoints(out.planes[1], out.vertices[3], out.vertices[4], out.vertices[7]); + plane.fromPoints(out.planes[2], out.vertices[6], out.vertices[3], out.vertices[7]); + plane.fromPoints(out.planes[3], out.vertices[0], out.vertices[5], out.vertices[4]); + plane.fromPoints(out.planes[4], out.vertices[2], out.vertices[0], out.vertices[3]); + plane.fromPoints(out.planes[0], out.vertices[7], out.vertices[5], out.vertices[6]); + }; + })(); + /** * Clone a frustum */ diff --git a/cocos/3d/geom-utils/octree.ts b/cocos/3d/geom-utils/octree.ts index 4cf7e70b3b..a39534fa4d 100644 --- a/cocos/3d/geom-utils/octree.ts +++ b/cocos/3d/geom-utils/octree.ts @@ -72,7 +72,7 @@ class OctreeBlock { } public frustumSelect (out, frustum) { - if (!intersect.box_frustum(this.boundingBox, frustum)) { return; } + if (!intersect.aabb_frustum(this.boundingBox, frustum)) { return; } if (this.blocks) { for (const block of this.blocks) { block.frustumSelect(out, frustum); diff --git a/cocos/3d/physics/api.d.ts b/cocos/3d/physics/api.d.ts index e95f1555da..637b7fec70 100644 --- a/cocos/3d/physics/api.d.ts +++ b/cocos/3d/physics/api.d.ts @@ -74,7 +74,7 @@ export class RigidBodyBase { applyForce (force: Vec3, position?: Vec3): void; - applyImpulse (impulse: Vec3): void; + applyImpulse (impulse: Vec3, position?: Vec3): void; getIsKinematic (): boolean; @@ -146,6 +146,10 @@ export class ShapeBase { getUserData (): any; setUserData (data: any): void; + + getCollisionResponse():boolean; + + setCollisionResponse(value:boolean):void; } export class SphereShapeBase extends ShapeBase { diff --git a/cocos/3d/physics/cannon-impl.ts b/cocos/3d/physics/cannon-impl.ts index 54445fb65c..68f2176922 100644 --- a/cocos/3d/physics/cannon-impl.ts +++ b/cocos/3d/physics/cannon-impl.ts @@ -535,6 +535,14 @@ export class CannonShape implements ShapeBase { } + public getCollisionResponse (): boolean { + return this.impl.collisionResponse; + } + + public setCollisionResponse (v: boolean): void { + this.impl.collisionResponse = v; + } + public _devStrinfy () { if (!this._body) { return ``; @@ -594,7 +602,8 @@ export class CannonBoxShape extends CannonShape implements BoxShapeBase { constructor (size: Vec3) { super(); vec3.scale(this._halfExtent, size, 0.5); - this._cannonBox = new CANNON.Box(this._halfExtent); + // attention : here should use clone + this._cannonBox = new CANNON.Box(this._halfExtent.clone()); setWrap(this._cannonBox, this); setWrap(this._cannonBox.convexPolyhedronRepresentation, this); this._cannonShape = this._cannonBox; @@ -603,6 +612,25 @@ export class CannonBoxShape extends CannonShape implements BoxShapeBase { public setScale (scale: Vec3): void { super.setScale(scale); this._recalcExtents(); + + // Another implementation method + // see https://github.com/schteppe/cannon.js/issues/270 + // if (this._body) { + // const body = this._body; + // const shape = this._cannonBox; + // const iShape = body.shapes.indexOf(shape); + // if (iShape >= 0) { + // body.shapes.splice(iShape, 1); + // body.shapeOffsets.splice(iShape, 1); + // body.shapeOrientations.splice(iShape, 1); + // body.updateMassProperties(); + // body.updateBoundingRadius(); + // body.aabbNeedsUpdate = true; + // (shape as any).body = null; + // } + // } + // vec3.multiply(this._cannonBox.halfExtents, this._cannonBox.halfExtents, scale); + // if (this._body) { this._body.addShape(this._cannonBox); } } public setSize (size: Vec3) { diff --git a/cocos/3d/physics/instance.ts b/cocos/3d/physics/instance.ts index acdbdeeb68..114463b22f 100644 --- a/cocos/3d/physics/instance.ts +++ b/cocos/3d/physics/instance.ts @@ -6,7 +6,7 @@ import { RaycastResult } from './raycast-result'; export enum ERigidBodyType { DYNAMIC = 1, STATIC = 2, - KINEMATIC = 4 + KINEMATIC = 4, } export function createPhysicsWorld (): PhysicsWorldBase { diff --git a/cocos/3d/ui/assembler/label/bmfont.ts b/cocos/3d/ui/assembler/label/bmfont.ts index 4d613e247a..52a9e4a489 100644 --- a/cocos/3d/ui/assembler/label/bmfont.ts +++ b/cocos/3d/ui/assembler/label/bmfont.ts @@ -34,7 +34,7 @@ import { fillMeshVertices3D } from '../utils'; import { bmfontUtils } from './bmfontUtils'; export const bmfont: IAssembler = { - createData (comp) { + createData (comp: LabelComponent) { return comp.requestRenderData(); }, diff --git a/cocos/3d/ui/assembler/label/bmfontUtils.ts b/cocos/3d/ui/assembler/label/bmfontUtils.ts index 545172ee32..53bf8ef01f 100644 --- a/cocos/3d/ui/assembler/label/bmfontUtils.ts +++ b/cocos/3d/ui/assembler/label/bmfontUtils.ts @@ -273,7 +273,7 @@ export const bmfontUtils = { } }, - _multilineTextWrap (nextTokenFunc) { + _multilineTextWrap (nextTokenFunc: Function) { const textLen = _string.length; let lineIndex = 0; diff --git a/cocos/3d/ui/assembler/mask/mask-assembler.ts b/cocos/3d/ui/assembler/mask/mask-assembler.ts index fcbda51369..ae718d9056 100644 --- a/cocos/3d/ui/assembler/mask/mask-assembler.ts +++ b/cocos/3d/ui/assembler/mask/mask-assembler.ts @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -import { Color, Mat4 } from '../../../../core/value-types'; import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; import { UI } from '../../../../renderer/ui/ui'; import { Node } from '../../../../scene-graph/node'; diff --git a/cocos/3d/ui/assembler/mask/stencil-manager.ts b/cocos/3d/ui/assembler/mask/stencil-manager.ts index 74c1f98ac1..b1d4fc4e76 100644 --- a/cocos/3d/ui/assembler/mask/stencil-manager.ts +++ b/cocos/3d/ui/assembler/mask/stencil-manager.ts @@ -139,9 +139,9 @@ export class StencilManager { } } - const state = this._stencilPattern; const pass = mat.passes[0]; if (this._changed(pass)){ + const state = this._stencilPattern; this._defaultPipelineState.depthStencilState = { stencilTestFront: state.stencilTest, stencilFuncFront: state.func, diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/3d/ui/assembler/sprite/bar-filled.ts index c50014ad9a..956ed5c01c 100644 --- a/cocos/3d/ui/assembler/sprite/bar-filled.ts +++ b/cocos/3d/ui/assembler/sprite/bar-filled.ts @@ -32,7 +32,6 @@ import { color4, vec3 } from '../../../../core/vmath/index'; import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; import { UI } from '../../../../renderer/ui/ui'; import { Node } from '../../../../scene-graph/node'; -import { MeshBuffer } from '../../mesh-buffer'; import { IAssembler } from '../assembler'; import { fillVerticesWithoutCalc3D } from '../utils'; diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index c686b9d1ea..640c77edfe 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -122,6 +122,12 @@ export class CanvasComponent extends Component { return this._camera; } + /** + * !#en Current active canvas, the scene should only have one active canvas at the same time. + * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 + * @property {CanvasComponent} instance + * @static + */ public static instance: CanvasComponent | null = null; public static views = []; /** @@ -138,35 +144,20 @@ export class CanvasComponent extends Component { private _fitHeight = true; @property private _priority = 0; - // @property - // private _priority = 0; private _thisOnResized: () => void; private _camera: Camera | null = null; - // /** - // * !#en Current active canvas, the scene should only have one active canvas at the same time. - // * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 - // * @property {CanvasComponent} instance - // * @static - // */ - // static instance = null; - constructor () { super(); this._thisOnResized = this.alignWithScreen.bind(this); + // TODO:maybe remove when multiple scene if (!CanvasComponent.instance){ CanvasComponent.instance = this; } } - // public onLoad () {} - - public resetInEditor () { - // _Scene._applyCanvasPreferences(this); - } - public __preload () { const cameraNode = new cc.Node('UICamera'); cameraNode.setPosition(0, 0, 1000); @@ -188,29 +179,10 @@ export class CanvasComponent extends Component { this._camera!.resize(device.width, device.height); } - // if (CC_DEV) { - // var Flags = cc.Object.Flags; - // this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked); - // } - - // if (CanvasComponent.instance) { - // return cc.errorID(6700, - // this.node.name, CanvasComponent.instance.node.name); - // } - // CanvasComponent.instance = this; - if (CC_EDITOR) { cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); - // cc.engine.on('design-resolution-changed', this._thisOnResized); - } - else { - // if (cc.sys.isMobile) { - // window.addEventListener('resize', this._thisOnResized); - // } - // else { - // cc.view.on('design-resolution-changed', this._thisOnResized); - // } } + cc.view.on('design-resolution-changed', this._thisOnResized); this.applySettings(); @@ -232,15 +204,7 @@ export class CanvasComponent extends Component { if (CC_EDITOR) { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); - // cc.engine.off('design-resolution-changed', this._thisOnResized); } - // else { - // if (cc.sys.isMobile) { - // window.removeEventListener('resize', this._thisOnResized); - // } else { - // cc.view.off('design-resolution-changed', this._thisOnResized); - // } - // } cc.view.off('design-resolution-changed', this._thisOnResized); diff --git a/cocos/3d/ui/components/graphics-component.ts b/cocos/3d/ui/components/graphics-component.ts index bee0ee1367..4e020bc646 100644 --- a/cocos/3d/ui/components/graphics-component.ts +++ b/cocos/3d/ui/components/graphics-component.ts @@ -27,12 +27,10 @@ import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { Color } from '../../../core/value-types'; import { UI } from '../../../renderer/ui/ui'; -import { Material } from '../../assets'; -import { RenderableComponent } from '../../framework/renderable-component'; import { IAssembler } from '../assembler/assembler'; import { LineCap, LineJoin } from '../assembler/graphics/types'; import { Impl } from '../assembler/graphics/webgl/impl'; -import { UIRenderComponent } from '../components/ui-render-component'; +import { InstanceMaterialType, UIRenderComponent } from '../components/ui-render-component'; /** * @class Graphics @@ -197,7 +195,7 @@ export class GraphicsComponent extends UIRenderComponent { constructor (){ super(); - this.impl = this._assembler && (this._assembler as IAssembler).createImpl!(this); + this._instanceMaterialType = InstanceMaterialType.ADDCOLOR; } public onRestore () { @@ -206,10 +204,20 @@ export class GraphicsComponent extends UIRenderComponent { } } + public __preload (){ + if (super.__preload){ + super.__preload(); + } + + this._flushAssembler(); + this.impl = this._assembler && (this._assembler as IAssembler).createImpl!(this); + } + public onEnable () { if (super.onEnable) { super.onEnable(); } + this._activateMaterial(); } @@ -457,22 +465,12 @@ export class GraphicsComponent extends UIRenderComponent { return false; } - protected _instanceMaterial () { - let mat: Material | null = null; - if (this._sharedMaterial) { - mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); - } else { - if (UIRenderComponent.addColorMat) { - mat = new Material(); - mat.copy(UIRenderComponent.addColorMat); - } else { - mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); - mat.initialize({ defines: { USE_TEXTURE: false } }); - UIRenderComponent.addColorMat = mat; - } + public helpInstanceMaterial () { + this._instanceMaterial(); + if (!this.impl){ + this._flushAssembler(); + this.impl = this._assembler && (this._assembler as IAssembler).createImpl!(this); } - - this._updateMaterial(mat); } protected _flushAssembler (){ diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index 9d29962799..e4f1dd8ce4 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -31,11 +31,9 @@ import { ImageAsset } from '../../../assets/image-asset'; import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { ccenum } from '../../../core/value-types/enum'; import { UI } from '../../../renderer/ui/ui'; -import { Material } from '../../assets'; -import { RenderableComponent } from '../../framework/renderable-component'; import { FontAtlas } from '../assembler/label/bmfontUtils'; import { ISharedLabelData } from '../assembler/label/ttfUtils'; -import { UIRenderComponent } from './ui-render-component'; +import { InstanceMaterialType, UIRenderComponent } from './ui-render-component'; /** * !#en Enum for vertical text alignment. @@ -156,7 +154,6 @@ export class LabelComponent extends UIRenderComponent { return this._string; } set string (value) { - value = value.toString(); if (this._string === value) { return; } @@ -629,24 +626,6 @@ export class LabelComponent extends UIRenderComponent { return true; } - protected _instanceMaterial () { - let mat: Material | null = null; - if (this._sharedMaterial) { - mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); - } else { - if (UIRenderComponent.addTextureMat) { - mat = new Material(); - mat.copy(UIRenderComponent.addTextureMat); - } else { - mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); - mat.initialize({ defines: { USE_TEXTURE: true } }); - UIRenderComponent.addColorMat = mat; - } - } - - this._updateMaterial(mat); - } - protected _flushAssembler () { const assembler = LabelComponent.Assembler!.getAssembler(this); diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index 03440142d7..df7caf4545 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -24,17 +24,15 @@ THE SOFTWARE. ****************************************************************************/ import { SpriteFrame } from '../../../assets/CCSpriteFrame'; -import { Mat4, Vec2, Vec3 } from '../../../core'; import { ccclass, executionOrder, menu, property} from '../../../core/data/class-decorator'; import { EventType } from '../../../core/platform/event-manager/event-enum'; +import { Mat4, Vec2, Vec3 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; import * as vmath from '../../../core/vmath'; import { UI } from '../../../renderer/ui/ui'; import { Node } from '../../../scene-graph'; -import { Material } from '../../assets/material'; -import { RenderableComponent } from '../../framework/renderable-component'; import { GraphicsComponent } from './graphics-component'; -import { UIRenderComponent } from './ui-render-component'; +import { InstanceMaterialType, UIRenderComponent } from './ui-render-component'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); @@ -247,7 +245,13 @@ export class MaskComponent extends UIRenderComponent { private _graphics: GraphicsComponent | null = null; private _clearGraphics: GraphicsComponent | null = null; + constructor (){ + super(); + this._instanceMaterialType = InstanceMaterialType.ADDCOLOR; + } + public onLoad (){ + this._flushAssembler(); this._createGraphics(); } @@ -364,35 +368,6 @@ export class MaskComponent extends UIRenderComponent { return this._clearGraphics !== null && this._graphics !== null && this._renderPermit; } - protected _instanceMaterial () { - let mat: Material | null = null; - if (this._sharedMaterial) { - mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); - } else { - // if (this._type === MaskType.IMAGE_STENCIL) { - // if (UIRenderComponent.addTextureMat) { - // mat = new Material(); - // mat.copy(UIRenderComponent.addTextureMat); - // } else { - // mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); - // mat.initialize({ defines: { USE_TEXTURE: true } }); - // UIRenderComponent.addTextureMat = mat; - // } - // } else { - if (UIRenderComponent.addColorMat) { - mat = new Material(); - mat.copy(UIRenderComponent.addColorMat); - } else { - mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); - mat.initialize({ defines: { USE_TEXTURE: false } }); - UIRenderComponent.addColorMat = mat; - } - // } - } - - this._updateMaterial(mat); - } - protected _flushAssembler (){ const assembler = MaskComponent.Assembler!.getAssembler(this); const posAssembler = MaskComponent.PostAssembler!.getAssembler(this); @@ -446,6 +421,7 @@ export class MaskComponent extends UIRenderComponent { if (!this._clearGraphics) { this._clearGraphics = new GraphicsComponent(); this._clearGraphics.node = new Node('clear-graphics'); + this._clearGraphics.helpInstanceMaterial(); this._clearGraphics._activateMaterial(); this._clearGraphics.lineWidth = 0; this._clearGraphics.rect(0, 0, cc.visibleRect.width, cc.visibleRect.height); @@ -455,6 +431,7 @@ export class MaskComponent extends UIRenderComponent { if (!this._graphics) { this._graphics = new GraphicsComponent(); this._graphics.node = this.node; + this._graphics.helpInstanceMaterial(); this._graphics.lineWidth = 0; this._graphics.strokeColor = cc.color(0, 0, 0, 0); } diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 3d15b6d596..2d8f216588 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -32,9 +32,7 @@ import { clampf } from '../../../core/utils/misc'; import { Vec2 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; import { UI } from '../../../renderer/ui/ui'; -import { Material } from '../../assets'; -import { RenderableComponent } from '../../framework/renderable-component'; -import { UIRenderComponent } from './ui-render-component'; +import { InstanceMaterialType, UIRenderComponent } from './ui-render-component'; /** * !#en Enum for sprite type. @@ -518,24 +516,6 @@ export class SpriteComponent extends UIRenderComponent { return true; } - protected _instanceMaterial () { - let mat: Material | null = null; - if (this._sharedMaterial) { - mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); - } else { - if (UIRenderComponent.addTextureMat) { - mat = new Material(); - mat.copy(UIRenderComponent.addTextureMat); - } else { - mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); - mat.initialize({ defines: { USE_TEXTURE: true}}); - UIRenderComponent.addTextureMat = mat; - } - } - - this._updateMaterial(mat); - } - protected _flushAssembler () { const assembler = SpriteComponent.Assembler!.getAssembler(this); diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index 1ae9e7b2bf..266de385dd 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -37,6 +37,7 @@ import { GFXBlendFactor } from '../../../gfx/define'; import { RenderData } from '../../../renderer/ui/renderData'; import { UI } from '../../../renderer/ui/ui'; import { Material } from '../../assets/material'; +import { RenderableComponent } from '../../framework/renderable-component'; import { IAssembler, IAssemblerManager } from '../assembler/assembler'; import { CanvasComponent } from './canvas-component'; import { UIComponent } from './ui-component'; @@ -45,6 +46,11 @@ import { UITransformComponent } from './ui-transfrom-component'; // hack ccenum(GFXBlendFactor); +export enum InstanceMaterialType { + ADDCOLOR = 0, + ADDCOLORANDTEXTURE = 1, +} + /** * !#en * Base class for components which supports rendering features. @@ -168,10 +174,6 @@ export class UIRenderComponent extends UIComponent { public static Assembler: IAssemblerManager | null = null; public static PostAssembler: IAssemblerManager | null = null; - // 预先定制两份 UI 常用材质,也许之后需要修改 - public static addColorMat: Material | null = null; - public static addTextureMat: Material | null = null; - @property protected _srcBlendFactor = GFXBlendFactor.SRC_ALPHA; @property @@ -189,6 +191,7 @@ export class UIRenderComponent extends UIComponent { // 特殊渲染标记,在可渲染情况下,因为自身某个原因不给予渲染 protected _renderPermit = true; protected _material: Material | null = null; + protected _instanceMaterialType = InstanceMaterialType.ADDCOLORANDTEXTURE; protected _blendTemplate = { blendState: { targets: [ @@ -202,19 +205,8 @@ export class UIRenderComponent extends UIComponent { rasterizerState: {}, }; - constructor (){ - super(); - if (this._instanceMaterial) { - this._instanceMaterial(); - } - - if (this._flushAssembler) { - this._flushAssembler(); - } - } - public __preload (){ - + this._instanceMaterial(); } public onEnable () { @@ -367,7 +359,24 @@ export class UIRenderComponent extends UIComponent { } } - protected _instanceMaterial? (): void; + protected _instanceMaterial () { + let mat: Material | null = null; + if (this._sharedMaterial) { + mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false); + } else { + switch (this._instanceMaterialType){ + case InstanceMaterialType.ADDCOLOR: + mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-base-material'), new RenderableComponent(), CC_EDITOR ? true : false); + break; + case InstanceMaterialType.ADDCOLORANDTEXTURE: + mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false); + break; + } + } + + this._updateMaterial(mat); + } + protected _flushAssembler? (): void; } diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts index 9f2004b0a8..45db26972c 100644 --- a/cocos/3d/ui/index.ts +++ b/cocos/3d/ui/index.ts @@ -1,23 +1,22 @@ import './assembler/index'; -import './components/button-component'; -import './components/canvas-component'; -import './components/editbox/edit-box-component'; -import './components/label-component'; -import './components/layout-component'; -import './components/mask-component'; -import './components/progress-bar-component'; -import './components/rich-text'; -import './components/scroll-bar-component'; -import './components/scroll-view-component'; -import './components/slider-component'; -import './components/sprite-component'; -import './components/toggle-component'; -import './components/toggle-group-component'; -import './components/ui-model-component'; -import './components/ui-render-component'; -import './components/ui-transfrom-component'; -import './components/ui-transfrom-component'; -import './components/view-group-component'; -import './components/webview/webView-component'; -import './components/widget-component'; +export { ButtonComponent } from './components/button-component'; +export { CanvasComponent } from './components/canvas-component'; +export { EditBoxComponent } from './components/editbox/edit-box-component'; +export { LabelComponent } from './components/label-component'; +export { LayoutComponent } from './components/layout-component'; +export { MaskComponent } from './components/mask-component'; +export { ProgressBarComponent } from './components/progress-bar-component'; +export { RichTextComponent } from './components/rich-text'; +export { ScrollBarComponent } from './components/scroll-bar-component'; +export { ScrollViewComponent } from './components/scroll-view-component'; +export { SliderComponent } from './components/slider-component'; +export { SpriteComponent } from './components/sprite-component'; +export { ToggleComponent } from './components/toggle-component'; +export { ToggleContainerComponent } from './components/toggle-group-component'; +export { UIModelComponent } from './components/ui-model-component'; +export { UIRenderComponent } from './components/ui-render-component'; +export { UITransformComponent } from './components/ui-transfrom-component'; +export { ViewGroupComponent } from './components/view-group-component'; +export { WebviewComponent } from './components/webview/webView-component'; +export { WidgetComponent } from './components/widget-component'; diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts index 0f3cf193f3..53eb3a6a9a 100644 --- a/cocos/assets/image-asset.ts +++ b/cocos/assets/image-asset.ts @@ -27,6 +27,7 @@ import {ccclass, property} from '../core/data/class-decorator'; // import {addon} from '../core/utils/js'; import { Asset } from './asset'; import { EventTargetFactory } from '../core/event/event-target-factory'; +import { GFXDevice, GFXFeature } from '../gfx/device'; export interface IMemoryImageSource { _data: ArrayBufferView | null; @@ -84,7 +85,7 @@ export class ImageAsset extends EventTargetFactory(Asset) { return this._url; } - private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; + private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm']; private _nativeData: ImageSource; @@ -175,12 +176,14 @@ export class ImageAsset extends EventTargetFactory(Asset) { } public _deserialize (data: string, handle: any) { + const device = _getGlobalDevice(); const extensionIDs = data.split('_'); let preferedExtensionIndex = Number.MAX_VALUE; let format = this._format; let ext = ''; const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[]; + const PixelFormat = cc.TextureBase.PixelFormat; for (const extensionID of extensionIDs) { const extFormat = extensionID.split('@'); @@ -189,6 +192,19 @@ export class ImageAsset extends EventTargetFactory(Asset) { const index = SupportTextureFormats.indexOf(tmpExt); if (index !== -1 && index < preferedExtensionIndex) { + const formatStr = extFormat[1] ? extFormat[1] : this._format; + const tmpForVal = parseInt(formatStr); + // check whether or not support compressed texture + if ( tmpExt === '.pvr' && (!device || !device.hasFeature(GFXFeature.FORMAT_PVRTC))) { + continue; + } else if (tmpForVal === PixelFormat.RGB_ETC1 && (!device || !device.hasFeature(GFXFeature.FORMAT_ETC1))) { + continue; + } else if ((tmpForVal === PixelFormat.RGB_ETC2 || tmpForVal === PixelFormat.RGBA_ETC2) && + (!device || !device.hasFeature(GFXFeature.FORMAT_ETC2))) { + continue; + } else if (tmpExt === '.webp' && !cc.sys.capabilities.webp) { + continue; + } preferedExtensionIndex = index; ext = tmpExt; format = extFormat[1] ? extFormat[1] : this._format; @@ -215,6 +231,14 @@ export class ImageAsset extends EventTargetFactory(Asset) { } } +function _getGlobalDevice (): GFXDevice | null { + if (cc.director && cc.director.root) { + return cc.director.root.device; + } else { + return null; + } +} + /** * !#zh * 当该资源加载成功后触发该事件 diff --git a/cocos/2d/assets/CCLabelAtlas.js b/cocos/assets/label-atlas.ts similarity index 90% rename from cocos/2d/assets/CCLabelAtlas.js rename to cocos/assets/label-atlas.ts index dd4e63005b..c6b540c5ef 100644 --- a/cocos/2d/assets/CCLabelAtlas.js +++ b/cocos/assets/label-atlas.ts @@ -24,6 +24,8 @@ THE SOFTWARE. ****************************************************************************/ +import { ccclass } from '../core/data/class-decorator'; +import { BitmapFont } from './bitmap-font'; /** * @module cc */ @@ -34,10 +36,8 @@ * @extends BitmapFont * */ -var LabelAtlas = cc.Class({ - name: 'cc.LabelAtlas', - extends: cc.BitmapFont -}); +@ccclass('cc.LabelAtlas') +export class LabelAtlas extends BitmapFont{ +} cc.LabelAtlas = LabelAtlas; -module.exports = LabelAtlas; diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 840b1c9c25..efa4448295 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -99,6 +99,18 @@ export enum PixelFormat { * rgba 4 bpp pvrtc */ RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4, + /** + * rgb etc1 + */ + RGB_ETC1 = GFXFormat.ETC_RGB8, + /** + * rgb etc2 + */ + RGB_ETC2 = GFXFormat.ETC2_RGB8, + /** + * rgba etc2 + */ + RGBA_ETC2 = GFXFormat.ETC2_RGBA8, } /** @@ -178,7 +190,7 @@ export class TextureBase extends EventTargetFactory(Asset) { * @param texture */ public static _isCompressed (texture: TextureBase) { - return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; + return texture._format >= PixelFormat.RGB_ETC1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; } @property diff --git a/cocos/core/game.js b/cocos/core/game.js index ba86e5c6b4..55e07f8fec 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -174,6 +174,12 @@ class Game extends EventTarget { */ setFrameRate(frameRate) { var config = this.config; + if (typeof frameRate !== 'number') { + frameRate = parseInt(frameRate); + if (isNaN(frameRate)) { + frameRate = 60; + } + } config.frameRate = frameRate; if (this._intervalId) window.cancelAnimFrame(this._intervalId); diff --git a/cocos/core/platform/CCMacro.js b/cocos/core/platform/CCMacro.js index 5e416879f2..60e77d1a6f 100644 --- a/cocos/core/platform/CCMacro.js +++ b/cocos/core/platform/CCMacro.js @@ -33,15 +33,7 @@ import Vec2 from '../value-types/vec2'; * @static */ -let SUPPORT_TEXTURE_FORMATS = ['.webp', '.jpg', '.jpeg', '.bmp', '.png']; -if (cc.sys.isMobile) { - if (cc.sys.os === cc.sys.OS_IOS) { - SUPPORT_TEXTURE_FORMATS = ['.pvr'].concat(SUPPORT_TEXTURE_FORMATS); - } - // else if (cc.sys.os === cc.sys.OS_ANDROID) { - // SUPPORT_TEXTURE_FORMATS = ['.etc'].join(SUPPORT_TEXTURE_FORMATS); - // } -} +let SUPPORT_TEXTURE_FORMATS = ['.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png']; /** diff --git a/cocos/core/platform/CCView.js b/cocos/core/platform/CCView.js index 464dc1349d..ff56b87e67 100644 --- a/cocos/core/platform/CCView.js +++ b/cocos/core/platform/CCView.js @@ -320,9 +320,6 @@ class View extends EventTarget { orientation = orientation & cc.macro.ORIENTATION_AUTO; if (orientation && this._orientation !== orientation) { this._orientation = orientation; - var designWidth = this._originalDesignResolutionSize.width; - var designHeight = this._originalDesignResolutionSize.height; - this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); } } diff --git a/cocos/core/utils/index.js b/cocos/core/utils/index.js index 3344201d5d..ecf57159b4 100644 --- a/cocos/core/utils/index.js +++ b/cocos/core/utils/index.js @@ -31,6 +31,7 @@ import * as js from './js'; * !#zh 用于处理文件与目录的路径的模块 */ import * as path from './path'; +export * from './profiler/profiler'; export * from './prefab-helper'; export { @@ -39,4 +40,4 @@ export { }; // export const js = cc.js; -// export const path = cc.path; \ No newline at end of file +// export const path = cc.path; diff --git a/cocos/core/utils/profiler/counter.ts b/cocos/core/utils/profiler/counter.ts new file mode 100644 index 0000000000..b735c85282 --- /dev/null +++ b/cocos/core/utils/profiler/counter.ts @@ -0,0 +1,69 @@ +import { ccclass } from '../../../core/data/class-decorator'; + +export interface ICounterOption { + desc: string; + counter: Counter; + min?: number; + max?: number; + average?: number; + below?: number; + over?: number; + color?: string; +} + +@ccclass('cc.Counter') +export class Counter { + get value (){ + return this._value; + } + + set value (val){ + this._value = val; + } + + protected _id: string; + protected _opts: ICounterOption; + protected _accumStart: number; + protected _total = 0; + protected _value = 0; + protected _averageValue = 0; + protected _accumValue = 0; + protected _accumSamples = 0; + + constructor (id: string, opts: ICounterOption, now: number) { + this._id = id; + this._opts = opts; + this._accumStart = now; + } + + public sample (now: number) { + this._average(this._value, now); + } + + public human () { + const v = this._opts.average ? this._averageValue : this._value; + return Math.round(v * 100) / 100; + } + + public alarm () { + return ( + (this._opts.below && this._value < this._opts.below) || + (this._opts.over && this._value > this._opts.over) + ); + } + + protected _average (v: number, now: number = 0) { + if (this._opts.average) { + this._accumValue += v; + ++this._accumSamples; + + const t = now; + if (t - this._accumStart >= this._opts.average) { + this._averageValue = this._accumValue / this._accumSamples; + this._accumValue = 0; + this._accumStart = t; + this._accumSamples = 0; + } + } + } +} diff --git a/cocos/core/utils/profiler/perf-counter.ts b/cocos/core/utils/profiler/perf-counter.ts new file mode 100644 index 0000000000..6ed9dcaeb1 --- /dev/null +++ b/cocos/core/utils/profiler/perf-counter.ts @@ -0,0 +1,46 @@ +import { ccclass } from '../../../core/data/class-decorator'; +import { Counter, ICounterOption } from './counter'; + +@ccclass('cc.PerfCounter') +export class PerfCounter extends Counter { + private _time: number; + constructor (id: string, opts: ICounterOption, now: number) { + super(id, opts, now); + this._time = now; + } + public start (now: number = 0) { + this._time = now; + + // DISABLE: long time running will cause performance drop down + // window.performance.mark(this._idstart); + } + + public end (now: number = 0) { + this._value = now - this._time; + + // DISABLE: long time running will cause performance drop down + // window.performance.mark(this._idend); + // window.performance.measure(this._id, this._idstart, this._idend); + + this._average(this._value); + } + + public tick () { + this.end(); + this.start(); + } + + public frame (now: number) { + const t = now; + const e = t - this._time; + this._total++; + const avg = this._opts.average || 1000; + + if (e > avg) { + this._value = this._total * 1000 / e; + this._total = 0; + this._time = t; + this._average(this._value); + } + } +} diff --git a/cocos/core/utils/profiler/profiler.ts b/cocos/core/utils/profiler/profiler.ts new file mode 100644 index 0000000000..521f77a298 --- /dev/null +++ b/cocos/core/utils/profiler/profiler.ts @@ -0,0 +1,320 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { CanvasComponent, LabelComponent, UITransformComponent, WidgetComponent} from '../../../3d/ui'; +import { ImageAsset, SpriteFrame } from '../../../assets'; +import { LabelAtlas } from '../../../assets/label-atlas'; +import { GFXDevice } from '../../../gfx/device'; +import { Node } from '../../../scene-graph/node'; +import { ICounterOption } from './counter'; +import { PerfCounter } from './perf-counter'; + +interface IProfilerState { + frame: ICounterOption; + fps: ICounterOption; + draws: ICounterOption; + tricount: ICounterOption; + logic: ICounterOption; + render: ICounterOption; + mode: ICounterOption; +} + +let _showFPS = false; +const _fontSize = 15; +const stringLeft = 'left'; +const stringRight = 'right'; + +let _atlas: LabelAtlas | null = null; +let _stats: IProfilerState | null = null; +let _rootNode: Node | null = null; +const _label = new Map(); +let device: GFXDevice | null = null; + +function initDevice (){ + if (device){ + return; + } + + device = cc.director.root.device; +} + +function generateAtlas () { + if (_atlas) { return; } + + const textureWidth = 256; + const textureHeight = 256; + + const canvas = document.createElement('canvas'); + canvas.width = textureWidth; + canvas.height = textureHeight; + canvas.style.width = `${canvas.width}`; + canvas.style.height = `${canvas.height}`; + + // comment out this to show atlas + // document.body.appendChild(canvas) + + const ctx = canvas.getContext('2d'); + if (!ctx){ + return; + } + + ctx.font = `${_fontSize}px Arial`; + ctx.textBaseline = 'top'; + ctx.textAlign = 'left'; + ctx.fillStyle = '#fff'; + + const space = 2; + let x = space; + let y = space; + const lineHeight = _fontSize; + + _atlas = new LabelAtlas(); + _atlas.fntConfig = { + atlasName: 'profiler-arial', + commonHeight: lineHeight, + fontSize: _fontSize, + kerningDict: {}, + fontDefDictionary: {}, + }; + + _atlas.name = 'profiler-arial'; + _atlas.fontSize = _fontSize; + + const dict = _atlas.fntConfig.fontDefDictionary; + + for (let i = 32; i <= 126; i++) { + const char = String.fromCharCode(i); + const width = ctx.measureText(char).width; + + if ((x + width) >= textureWidth) { + x = space; + y += lineHeight + space; + } + ctx.fillText(char, x, y); + + dict[i] = { + xAdvance: width, + xOffset: 0, + yOffset: 0, + rect: { + x, + y, + width, + height: lineHeight, + }, + }; + + x += width + space; + } + + // const texture = new Texture2D(); + const image = new ImageAsset(canvas); + + const spriteFrame = new SpriteFrame(); + spriteFrame.mipmaps = [image]; + spriteFrame.onLoaded(); + + _atlas.spriteFrame = spriteFrame; +} + +function generateStats () { + _stats = null; + const now = performance.now(); + + const opts = { + frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: 500 }, + fps: { desc: 'Framerate (FPS)', below: 30, average: 500 }, + draws: { desc: 'Draw call' }, + tricount: { desc: 'Triangle' }, + logic: { desc: 'Game Logic (ms)', min: 0, max: 50, average: 500, color: '#080' }, + render: { desc: 'Renderer (ms)', min: 0, max: 50, average: 500, color: '#f90' }, + mode: { desc: cc.game.renderType === cc.game.RENDER_TYPE_WEBGL ? 'WebGL' : 'Canvas', min: 1 }, + }; + + for (const id of Object.keys(opts)) { + opts[id].counter = new PerfCounter(id, opts[id], now); + } + + _stats = opts as IProfilerState; +} + +function generateNode () { + if (_rootNode && _rootNode.isValid) { + return; + } + + _rootNode = new Node('PROFILER-NODE'); + _rootNode.addComponent(UITransformComponent); + _rootNode.addComponent(CanvasComponent); + cc.director.root.ui.debugScreen = _rootNode; + cc.game.addPersistRootNode(_rootNode); + // const camera = cc.director.root. + + const managerNode = new Node('ROOT'); + managerNode.addComponent(UITransformComponent); + managerNode.parent = _rootNode; + managerNode.anchorX = managerNode.anchorY = 0; + const widgetComp = managerNode.addComponent(WidgetComponent); + if (widgetComp) { + widgetComp.isAlignBottom = true; + widgetComp.isAlignLeft = true; + widgetComp.left = 10; + widgetComp.bottom = 10; + } + + // _rootNode.groupIndex = cc.Node.BuiltinGroupIndex.DEBUG; + // cc.Camera._setupDebugCamera(); + + // _rootNode.zIndex = macro.MAX_ZINDEX; + + const left = new Node('LEFT-PANEL'); + left.parent = managerNode; + const leftLabel = left.addComponent(LabelComponent); + left.anchorX = left.anchorY = 0; + if (leftLabel){ + leftLabel.font = _atlas; + leftLabel.fontSize = _fontSize; + leftLabel.lineHeight = _fontSize + 1; + } + + const right = new Node('RIGHT-PANEL'); + right.parent = managerNode; + const rightLabel = right.addComponent(LabelComponent); + right.anchorX = 1; + right.anchorY = 0; + const pos = right.getPosition(); + right.setPosition(200, pos.y, pos.z); + if (rightLabel){ + rightLabel.horizontalAlign = cc.LabelComponent.HorizontalAlign.RIGHT; + rightLabel.font = _atlas; + rightLabel.fontSize = _fontSize; + rightLabel.lineHeight = _fontSize; + } + + _label[stringLeft] = leftLabel; + _label[stringRight] = rightLabel; +} + +function beforeUpdate () { + if (!_stats) { + return; + } + + generateNode(); + + const now = cc.director._lastUpdate; + getCounter('frame').start(now); + getCounter('logic').start(now); +} + +function afterUpdate () { + if (!_stats){ + return; + } + + const now = performance.now(); + if (cc.director.isPaused()) { + getCounter('frame').start(now); + } else { + getCounter('logic').end(now); + } + getCounter('render').start(now); +} + +// function updateLabel (stat: IProfilerStateOption) { +// stat.label.string = stat.desc + ' ' + stat.counter.human(); +// } + +function afterDraw () { + if (!_stats){ + return; + } + + const now = performance.now(); + + getCounter('frame').end(now); + getCounter('fps').frame(now); + getCounter('draws').value = device!.numDrawCalls; + getCounter('tricount').value = device!.numTris; + getCounter('render').end(now); + getCounter('mode').value = device!.gfxAPI; + + let left = ''; + let right = ''; + for (const id of Object.keys(_stats)) { + const stat = _stats[id]; + stat.counter.sample(now); + + left += stat.desc + '\n'; + right += stat.counter.human() + '\n'; + } + + _label[stringLeft].string = left; + _label[stringRight].string = right; +} + +function getCounter (s: string) { + const stats = _stats!; + return stats[s].counter as PerfCounter; +} + +export const profiler = { + isShowingStats () { + return _showFPS; + }, + + hideStats () { + if (_showFPS) { + if (_rootNode) { + _rootNode.active = false; + } + + cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate); + cc.director.off(cc.Director.EVENT_AFTER_UPDATE, afterUpdate); + cc.director.off(cc.Director.EVENT_AFTER_DRAW, afterDraw); + _showFPS = false; + } + }, + + showStats () { + if (!_showFPS) { + initDevice(); + generateAtlas(); + generateStats(); + + if (_rootNode) { + _rootNode.active = true; + } + + cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate); + cc.director.on(cc.Director.EVENT_AFTER_UPDATE, afterUpdate); + cc.director.on(cc.Director.EVENT_AFTER_DRAW, afterDraw); + _showFPS = true; + } + }, +}; + +cc.profiler = profiler; diff --git a/cocos/load-pipeline/downloader.js b/cocos/load-pipeline/downloader.js index f11494a44e..60b6f7a761 100644 --- a/cocos/load-pipeline/downloader.js +++ b/cocos/load-pipeline/downloader.js @@ -135,7 +135,7 @@ var defaultMap = { 'webp' : downloadWebp, 'image' : downloadImage, 'pvr': downloadBinary, - 'etc': downloadBinary, + 'pkm': downloadBinary, // Audio 'mp3' : downloadAudio, diff --git a/cocos/load-pipeline/loader.js b/cocos/load-pipeline/loader.js index 20ebe40f51..6b913674ad 100644 --- a/cocos/load-pipeline/loader.js +++ b/cocos/load-pipeline/loader.js @@ -124,31 +124,83 @@ const PVR_HEADER_WIDTH = 7; const PVR_HEADER_MIPMAPCOUNT = 11; const PVR_HEADER_METADATA = 12; -function loadCompressedTex (item) { +function loadPVRTex (item) { + let buffer = item.content instanceof ArrayBuffer ? item.content : item.content.buffer; // Get a view of the arrayBuffer that represents the DDS header. - let header = new Int32Array(item.content.buffer, 0, PVR_HEADER_LENGTH); + let header = new Int32Array(buffer, 0, PVR_HEADER_LENGTH); // Do some sanity checks to make sure this is a valid DDS file. - if(header[PVR_HEADER_MAGIC] != PVR_MAGIC) { - return new Error("Invalid magic number in PVR header"); + if(header[PVR_HEADER_MAGIC] === PVR_MAGIC) { + // Gather other basic metrics and a view of the raw the DXT data. + let width = header[PVR_HEADER_WIDTH]; + let height = header[PVR_HEADER_HEIGHT]; + let dataOffset = header[PVR_HEADER_METADATA] + 52; + let pvrtcData = new Uint8Array(buffer, dataOffset); + let pvrAsset = { + _data: pvrtcData, + _compressed: true, + width: width, + height: height, + }; + return pvrAsset; } + else if (header[11] === 0x21525650) { + var headerLength = header[0], + height = header[1], + width = header[2] + let pvrtcData = new Uint8Array(buffer, headerLength); + let pvrAsset = { + _data: pvrtcData, + _compressed: true, + width: width, + height: height, + }; + return pvrAsset; + } + else { + return new Error("Invalid magic number in PVR header"); + } +} - // Gather other basic metrics and a view of the raw the DXT data. - let width = header[PVR_HEADER_WIDTH]; - let height = header[PVR_HEADER_HEIGHT]; - let levels = header[PVR_HEADER_MIPMAPCOUNT]; - let dataOffset = header[PVR_HEADER_METADATA] + 52; - let pvrtcData = new Uint8Array(item.content.buffer, dataOffset); +//===============// +// ETC constants // +//===============// - let pvrAsset = { - _data: pvrtcData, +const ETC_PKM_HEADER_SIZE = 16; + +const ETC_PKM_FORMAT_OFFSET = 6; +const ETC_PKM_ENCODED_WIDTH_OFFSET = 8; +const ETC_PKM_ENCODED_HEIGHT_OFFSET = 10; +const ETC_PKM_WIDTH_OFFSET = 12; +const ETC_PKM_HEIGHT_OFFSET = 14; + +const ETC1_RGB_NO_MIPMAPS = 0; +const ETC2_RGB_NO_MIPMAPS = 1; +const ETC2_RGBA_NO_MIPMAPS = 3; + + +function readBEUint16(header, offset) { + return (header[offset] << 8) | header[offset+1]; +} +function loadPKMTex(item) { + let buffer = item.content instanceof ArrayBuffer ? item.content : item.content.buffer; + let header = new Uint8Array(buffer); + let format = readBEUint16(header, ETC_PKM_FORMAT_OFFSET); + if (format !== ETC1_RGB_NO_MIPMAPS && format !== ETC2_RGB_NO_MIPMAPS && format !== ETC2_RGBA_NO_MIPMAPS) { + return new Error("Invalid magic number in ETC header"); + } + let width = readBEUint16(header, ETC_PKM_WIDTH_OFFSET); + let height = readBEUint16(header, ETC_PKM_HEIGHT_OFFSET); + let encodedWidth = readBEUint16(header, ETC_PKM_ENCODED_WIDTH_OFFSET); + let encodedHeight = readBEUint16(header, ETC_PKM_ENCODED_HEIGHT_OFFSET); + let etcData = new Uint8Array(buffer, ETC_PKM_HEADER_SIZE); + let etcAsset = { + _data: etcData, _compressed: true, - width: width, - height: height, + height: height }; - - return pvrAsset; + return etcAsset; } var defaultMap = { @@ -162,8 +214,8 @@ var defaultMap = { 'tiff' : loadImage, 'webp' : loadImage, 'image' : loadImage, - 'pvr' : loadCompressedTex, - 'etc' : loadCompressedTex, + 'pvr' : loadPVRTex, + 'pkm' : loadPKMTex, // Audio 'mp3' : loadAudioAsAsset, diff --git a/cocos/pipeline/culling.ts b/cocos/pipeline/culling.ts index 248c992fe4..d8fa1f230e 100644 --- a/cocos/pipeline/culling.ts +++ b/cocos/pipeline/culling.ts @@ -43,21 +43,20 @@ export const cullSceneWithDirectionalLight = (() => { export const calcDirectionalLightCullFrustum = (() => { const lightPos = cc.v3(); - const lightPosOffset = cc.v3(); + const lightViewCenter = cc.v3(); const lightRot = cc.quat(); const camFrustum = new frustum(); camFrustum.accurate = true; const lightViewMat = cc.mat4(); - const lightProjMat = cc.mat4(); - const lightVPMat = cc.mat4(); - const lightVPMatInv = cc.mat4(); + const lightVeiwMatInv = cc.mat4(); const minBoxCorner = cc.v3(); const maxBoxCorner = cc.v3(); return (out: frustum, sceneCamera: Camera, light: DirectionalLight, near: number, far: number) => { - mat4.invert(lightViewMat, light.node.getWorldMatrix(lightViewMat)); + mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos)); + mat4.invert(lightVeiwMatInv, lightViewMat); sceneCamera.getSplitFrustum(camFrustum, near, far); // transform camera frustum to light space - camFrustum.transform(lightViewMat); + camFrustum.transform(lightVeiwMatInv); vec3.set(minBoxCorner, camFrustum.vertices[0].x, camFrustum.vertices[0].y, camFrustum.vertices[0].z); vec3.copy(maxBoxCorner, minBoxCorner); // calculate the light frustum corner @@ -69,17 +68,11 @@ export const calcDirectionalLightCullFrustum = (() => { maxBoxCorner.y = Math.max(maxBoxCorner.y, camFrustum.vertices[i].y); maxBoxCorner.z = Math.max(maxBoxCorner.z, camFrustum.vertices[i].z); } - // move light to frustum near plane center - vec3.set(lightPosOffset, (minBoxCorner.x + maxBoxCorner.x) / 2, (minBoxCorner.y + maxBoxCorner.y) / 2, maxBoxCorner.z); - vec3.add(minBoxCorner, minBoxCorner, lightPosOffset); - vec3.add(maxBoxCorner, maxBoxCorner, lightPosOffset); - mat4.ortho(lightProjMat, minBoxCorner.x, maxBoxCorner.x, minBoxCorner.y, maxBoxCorner.y, -maxBoxCorner.z, -minBoxCorner.z); - light.node.getPosition(lightPos); - vec3.add(lightPos, lightPos, lightPosOffset); - mat4.fromRT(lightViewMat, light.node.getRotation(lightRot), lightPos); - - mat4.mul(lightVPMat, lightProjMat, lightViewMat); - mat4.invert(lightVPMatInv, lightVPMat); - out.update(lightVPMat, lightVPMatInv); + // calc the light world transform ,suppose that the light's position is at the camera's location. + vec3.set(lightViewCenter, (minBoxCorner.x + maxBoxCorner.x) / 2, (minBoxCorner.y + maxBoxCorner.y) / 2, maxBoxCorner.z); + vec3.transformMat4(lightPos, lightViewCenter, lightViewMat); + mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), lightPos); + // calc the light's frustum + frustum.createOrtho(out, maxBoxCorner.x - minBoxCorner.x, maxBoxCorner.y - minBoxCorner.y, 0, minBoxCorner.z - maxBoxCorner.z, lightViewMat); }; })(); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 61072db082..56826b0b63 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -116,7 +116,7 @@ export class Pass { protected _customizations: string[] = []; protected _handleMap: Record = {}; protected _blocks: IBlock[] = []; - protected _shaderInfo: IShaderInfo | null = null; + protected _shaderInfo: IShaderInfo = null!; protected _defines: IDefineMap = {}; protected _phase: number = 0; // external references @@ -276,8 +276,8 @@ export class Pass { } } - public tryCompile (defines?: IDefineMap) { - if (defines) { Object.assign(this._defines, defines); } + public tryCompile (defineOverrides?: IDefineMap) { + if (defineOverrides) { Object.assign(this._defines, defineOverrides); } const pipeline = cc.director.root.pipeline as RenderPipeline | null; if (!pipeline) { return false; } this._renderPass = pipeline.getRenderPass(this._stage); @@ -285,9 +285,9 @@ export class Pass { this._shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline); if (!this._shader) { console.warn(`create shader ${this._programName} failed`); return false; } if (!this._bindings.length) { - this._bindings = this._shaderInfo!.blocks.map((u) => + this._bindings = this._shaderInfo.blocks.map((u) => ({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER }), - ).concat(this._shaderInfo!.samplers.map((u) => + ).concat(this._shaderInfo.samplers.map((u) => ({ name: u.name, binding: u.binding, type: GFXBindingType.SAMPLER }), )); } @@ -312,7 +312,7 @@ export class Pass { } // bind pipeline builtins const source = cc.director.root.pipeline.globalBindings; - const target = this._shaderInfo!.builtins.globals; + const target = this._shaderInfo.builtins.globals; for (const b of target.blocks) { const info = source.get(b); if (!info || info.type !== GFXBindingType.UNIFORM_BUFFER) { console.warn(`builtin UBO '${b}' not available!`); continue; } @@ -352,8 +352,8 @@ export class Pass { } public serializePipelineStates () { - const instanceName = programLib.getShaderInstaceName(this._programName, this._defines); - let res = `${instanceName},${this._stage},${this._primitive}`; + const shaderKey = programLib.getKey(this._programName, this._defines); + let res = `${shaderKey},${this._stage},${this._primitive}`; res += serializeBlendState(this._bs); res += serializeDepthStencilState(this._dss); res += serializeRasterizerState(this._rs); diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index d01bc7b8eb..988598bf24 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -180,7 +180,6 @@ class ProgramLib { if (!tmpl.globalsInited) { insertBuiltinBindings(tmpl, pipeline.globalBindings, 'globals'); tmpl.globalsInited = true; } const defs = prepareDefines(defines, tmpl.defines); - const instanceName = this.getShaderInstaceName(name, defines, defs); validateDefines(defs, device, tmpl.dependencies); const customDef = defs.reduce((acc, cur) => `${acc}#define ${cur.name} ${cur.result}\n`, ''); @@ -195,7 +194,7 @@ class ProgramLib { } program = device.createShader({ - name: instanceName, + name: this.getShaderInstaceName(name, defines, defs), blocks: tmpl.blocks, samplers: tmpl.samplers, stages: [ diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 9b8f49ac1e..babd7792ae 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -276,7 +276,6 @@ export class Model { for (let i = 0; i < mat.passes.length; i++) { const pass = mat.passes[i]; pass.destroyPipelineState(pso[i]); - pass.tryCompile(); pso[i] = this._doCreatePSO(pass); } } diff --git a/cocos/renderer/ui/renderData.ts b/cocos/renderer/ui/renderData.ts index 8c4c6014a0..ad619abcf5 100644 --- a/cocos/renderer/ui/renderData.ts +++ b/cocos/renderer/ui/renderData.ts @@ -1,15 +1,16 @@ import { Material } from '../../3d/assets/material'; +import Pool from '../../3d/memop/pool'; import RecyclePool from '../../3d/memop/recycle-pool'; import { Color } from '../../core/value-types'; -export class IRenderData { - public x: number = 0; - public y: number = 0; - public z: number = 0; - public u: number = 0; - public v: number = 0; - public color: Color = Color.WHITE; +export interface IRenderData { + x: number; + y: number; + z: number; + u: number; + v: number; + color: Color; } export class BaseRenderData { @@ -30,13 +31,15 @@ export class RenderData extends BaseRenderData { // // Free extra data const value = data.length; let i = 0; + for (i = length; i < value; i++) { + _dataPool.free(data[i]); + } + for (i = value; i < length; i++) { - data[i] = _dataPool.add(); - } - for (i = value; i > length; i--) { - _dataPool.removeAt(i); - data.splice(i, 1); + data[i] = _dataPool.alloc(); } + + data.length = length; } } @@ -149,10 +152,17 @@ export class IARenderData extends BaseRenderData { } } -const _dataPool = new RecyclePool(() => { - return new IRenderData(); +const _dataPool = new Pool(() => { + return { + x: 0, + y: 0, + z: 0, + u: 0, + v: 0, + color: Color.WHITE, + } as IRenderData; }, 128); -const _pool = new RecyclePool( () => { +const _pool = new RecyclePool(() => { return new RenderData(); }, 32); diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index a55111eb27..ecf025318d 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -73,8 +73,24 @@ export class UI { get currBufferBatch () { return this._currMeshBuffer; } + + get debugScreen (){ + return this._debugScreen; + } + + set debugScreen (value){ + this._debugScreen = value; + if (this._debugScreen){ + const screen = this.getScreen(this._debugScreen.visibility); + if (screen) { + this.removeScreen(screen.visibility); + } + } + } + public device: GFXDevice; private _screens: CanvasComponent[] = []; + private _debugScreen: CanvasComponent | null = null; private _bufferBatchPool: RecyclePool = new RecyclePool(() => { return new MeshBuffer(this); }, 128); @@ -400,20 +416,28 @@ export class UI { continue; } - this._walk(screen.node, (c: Node) => { - const render = c.getComponent(UIComponent); - if (render && render.enabledInHierarchy) { - render.updateAssembler(this); - } - }, (c: Node) => { - const render = c.getComponent(UIComponent); - if (render && render.enabledInHierarchy) { - render.postUpdateAssembler(this); - } - }); - + this._recursiveScreenNode(screen.node); this.autoMergeBatches(); } + + if (!CC_EDITOR && this._debugScreen && this._debugScreen.enabledInHierarchy) { + this._recursiveScreenNode(this._debugScreen.node); + this.autoMergeBatches(); + } + } + + private _recursiveScreenNode (screen: Node) { + this._walk(screen, (c: Node) => { + const render = c.getComponent(UIComponent); + if (render && render.enabledInHierarchy) { + render.updateAssembler(this); + } + }, (c: Node) => { + const render = c.getComponent(UIComponent); + if (render && render.enabledInHierarchy) { + render.postUpdateAssembler(this); + } + }); } private _reset () { diff --git a/cocos/scene-graph/private-node.ts b/cocos/scene-graph/private-node.ts index 52e03ca85e..90f37d9ae6 100644 --- a/cocos/scene-graph/private-node.ts +++ b/cocos/scene-graph/private-node.ts @@ -25,8 +25,8 @@ 'use strict'; -import { CCObject } from '../core'; import { ccclass } from '../core/data/class-decorator'; +import { CCObject } from '../core/data/object'; import { Node } from './node'; // const LocalDirtyFlag = Node._LocalDirtyFlag;