diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index f131953a21..f01c2bbac5 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -4,38 +4,39 @@ import ImageAsset from '../../assets/image-asset'; import { Material } from '../assets/material'; import { EffectAsset } from '../assets/effect-asset'; import effects from './effects'; +import { SpriteFrame} from '../../assets/CCSpriteFrame'; let builtinResMgr = { // this should be called after renderer initialized initBuiltinRes: function(device) { builtinResMgr.device = device; - // let canvas = document.createElement('canvas'); - // let context = canvas.getContext('2d'); + let canvas = document.createElement('canvas'); + let context = canvas.getContext('2d'); - // // ============================ - // // builtin textures - // // ============================ + // ============================ + // builtin textures + // ============================ - // // default texture canvas fill - // canvas.width = canvas.height = 128; - // context.fillStyle = '#ddd'; - // context.fillRect(0, 0, 128, 128); - // context.fillStyle = '#555'; - // context.fillRect(0, 0, 64, 64); - // context.fillStyle = '#555'; - // context.fillRect(64, 64, 64, 64); + // default texture canvas fill + canvas.width = canvas.height = 128; + context.fillStyle = '#ddd'; + context.fillRect(0, 0, 128, 128); + context.fillStyle = '#555'; + context.fillRect(0, 0, 64, 64); + context.fillStyle = '#555'; + context.fillRect(64, 64, 64, 64); - // const canvasImage = new ImageAsset(canvas); + const canvasImage = new ImageAsset(canvas); - // // default-texture - // let defaultTexture = new Texture2D(); - // defaultTexture.setMipFilter(Texture2D.Filter.LINEAR); - // defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); - // defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - // defaultTexture._uuid = 'default-texture'; - // defaultTexture.image = canvasImage; + // default-texture + let defaultTexture = new Texture2D(); + defaultTexture.setMipFilter(Texture2D.Filter.LINEAR); + defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); + defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + defaultTexture._uuid = 'default-texture'; + defaultTexture.image = canvasImage; - // // default-texture-cube + // default-texture-cube // let defaultTextureCube = new TextureCube(); // defaultTextureCube._uuid = 'default-texture-cube'; // defaultTextureCube.image = { @@ -47,29 +48,29 @@ let builtinResMgr = { // bottom: canvasImage, // }; - // // black texture canvas fill - // canvas.width = canvas.height = 2; - // context.fillStyle = '#000'; - // context.fillRect(0, 0, 2, 2); + // black texture canvas fill + canvas.width = canvas.height = 2; + context.fillStyle = '#000'; + context.fillRect(0, 0, 2, 2); - // // black-texture - // let blackTexture = new Texture2D(); - // blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - // blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - // blackTexture._uuid = 'black-texture'; - // defaultTexture.image = canvasImage; + // black-texture + let blackTexture = new Texture2D(); + blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + blackTexture._uuid = 'black-texture'; + defaultTexture.image = canvasImage; - // // white texture canvas fill - // canvas.width = canvas.height = 2; - // context.fillStyle = '#fff'; - // context.fillRect(0, 0, 2, 2); + // white texture canvas fill + canvas.width = canvas.height = 2; + context.fillStyle = '#fff'; + context.fillRect(0, 0, 2, 2); - // // white-texture - // let whiteTexture = new Texture2D(); - // blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - // blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - // whiteTexture._uuid = 'white-texture'; - // defaultTexture.image = canvasImage; + // white-texture + let whiteTexture = new Texture2D(); + blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + whiteTexture._uuid = 'white-texture'; + defaultTexture.image = canvasImage; // essential builtin effects let efxs = effects.map(e => { @@ -81,15 +82,22 @@ let builtinResMgr = { let defaultMtl = new Material(); defaultMtl._uuid = 'default-material'; defaultMtl.setDefines({ USE_COLOR: true }); - defaultMtl.effectAsset = efxs[0]; + defaultMtl.effectName = 'builtin-effect-unlit'; defaultMtl.setProperty('color', cc.color('#FF00FF')); + // sprite material + let spriteMtl = new Material(); + spriteMtl._uuid = 'sprite-material'; + spriteMtl.effectName = 'builtin-effect-sprite'; + defaultMtl.setProperty('mainTexture', defaultTexture); + let builtins = { - // [defaultTexture._uuid]: defaultTexture, - // [defaultTextureCube._uuid]: defaultTextureCube, - // [blackTexture._uuid]: blackTexture, - // [whiteTexture._uuid]: whiteTexture, - [defaultMtl._uuid]: defaultMtl + [defaultTexture._uuid]: defaultTexture, + // [defaultTextureCube._uuid]: defaultTextureCub + [blackTexture._uuid]: blackTexture, + [whiteTexture._uuid]: whiteTexture, + [spriteMtl._uuid]: spriteMtl, + [spriteFrame._uuid]:spriteFrame }; return Object.assign(builtinResMgr, builtins); }, diff --git a/cocos/3d/index.js b/cocos/3d/index.js index 32a86b567a..ac1f3a27c7 100644 --- a/cocos/3d/index.js +++ b/cocos/3d/index.js @@ -30,6 +30,7 @@ export * from './memop'; import * as utils from './misc/utils'; import * as primitives from './primitive'; import * as geometry from './geom-utils'; +import './ui'; export { utils, diff --git a/cocos/2d/renderer/webgl/assemblers/index.js b/cocos/3d/ui/assembler/index.js similarity index 89% rename from cocos/2d/renderer/webgl/assemblers/index.js rename to cocos/3d/ui/assembler/index.js index 65a9b28071..27e68b6314 100644 --- a/cocos/2d/renderer/webgl/assemblers/index.js +++ b/cocos/3d/ui/assembler/index.js @@ -23,8 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -require('./sprite'); -require('./mask-assembler'); -require('./graphics'); -require('./label'); -require('./motion-streak'); +// require('./sprite'); +import './sprite/index'; +// require('./mask-assembler'); +// require('./graphics'); +// import './label/index'; +// require('./motion-streak'); diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/index.js b/cocos/3d/ui/assembler/sprite/index.js similarity index 55% rename from cocos/2d/renderer/webgl/assemblers/sprite/index.js rename to cocos/3d/ui/assembler/sprite/index.js index c59947b09c..00ce2ab056 100644 --- a/cocos/2d/renderer/webgl/assemblers/sprite/index.js +++ b/cocos/3d/ui/assembler/sprite/index.js @@ -23,53 +23,56 @@ THE SOFTWARE. ****************************************************************************/ -const Sprite = require('../../../../components/CCSprite'); +// const Sprite = require('../../../../components/CCSprite'); +import { SpriteComponent} from '../../components/sprite-component'; -const SpriteType = Sprite.Type; -const FillType = Sprite.FillType; +const SpriteType = SpriteComponent.Type; +const FillType = SpriteComponent.FillType; -const simpleRenderUtil = require('./simple'); -const slicedRenderUtil = require('./sliced'); -const tiledRenderUtil = require('./tiled'); -const radialFilledRenderUtil = require('./radial-filled'); -const barFilledRenderUtil = require('./bar-filled'); -const meshRenderUtil = require('./mesh'); +import simpleRenderUtil from './simple'; +import slicedRenderUtil from './sliced'; +import tiledRenderUtil from './tiled'; +import radialFilledRenderUtil from './radial-filled'; +import barFilledRenderUtil from './bar-filled'; +import meshRenderUtil from './mesh'; // Inline all type switch to avoid jit deoptimization during inlined function change -let spriteAssembler = { - getAssembler (sprite) { +const spriteAssembler = { + getAssembler(sprite) { let util = simpleRenderUtil; - - switch (sprite.type) { - case SpriteType.SLICED: - util = slicedRenderUtil; - break; - case SpriteType.TILED: - util = tiledRenderUtil; - break; - case SpriteType.FILLED: - if (sprite._fillType === FillType.RADIAL) { - util = radialFilledRenderUtil; - } - else { - util = barFilledRenderUtil; - } - break; - case SpriteType.MESH: - util = meshRenderUtil; - break; - } + + // switch (sprite.type) { + // case SpriteType.SLICED: + // util = slicedRenderUtil; + // break; + // // case SpriteType.TILED: + // // util = tiledRenderUtil; + // // break; + // case SpriteType.FILLED: + // // if (sprite._fillType === FillType.RADIAL) { + // // util = radialFilledRenderUtil; + // // } + // // else { + // util = barFilledRenderUtil; + // // } + // break; + // // case SpriteType.MESH: + // // util = meshRenderUtil; + // // break; + // } return util; }, // Skip invalid sprites (without own _assembler) - updateRenderData (sprite) { + updateRenderData(sprite) { return sprite.__allocedDatas; } }; -Sprite._assembler = spriteAssembler; +export { + spriteAssembler +} -module.exports = spriteAssembler; +SpriteComponent._assembler = spriteAssembler; diff --git a/cocos/3d/ui/assembler/sprite/simple.js b/cocos/3d/ui/assembler/sprite/simple.js new file mode 100644 index 0000000000..ff33bbafa1 --- /dev/null +++ b/cocos/3d/ui/assembler/sprite/simple.js @@ -0,0 +1,165 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + https://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 { vec3 } from '../../../../core/vmath/index'; +// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); +let matrix = cc.mat4(); + +let simple = { + useModel: false, + + createData(sprite) { + let renderData = sprite.requestRenderData(); + renderData.dataLength = 4; + renderData.vertexCount = 4; + renderData.indiceCount = 6; + return renderData; + }, + + updateRenderData(sprite) { + let frame = sprite._spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + // if (frame) { + // if (!frame._original && dynamicAtlasManager) { + // dynamicAtlasManager.insertSpriteFrame(frame); + // } + // if (sprite._material._texture !== frame._texture) { + // sprite._activateMaterial(); + // } + // } + + let renderData = sprite._renderData; + if (renderData && frame) { + if (renderData.vertDirty) { + this.updateVerts(sprite); + } + } + }, + + fillBuffers: (function () { + let vec3_temps = []; + for (let i = 0; i < 4; i++) { + vec3_temps.push(vec3.create()); + } + return function (sprite, /*renderer*/buffer) { + let data = sprite._renderData._data, + node = sprite.node, + color = sprite._color._val; + + node.getWorldMatrix(matrix); + + let /*buffer = renderer._meshBuffer3D,*/ + vertexOffset = buffer.byteOffset >> 2, + indiceOffset = buffer.indiceOffset, + vertexId = buffer.vertexOffset; + + buffer.request(4, 6); + + // buffer data may be realloc, need get reference after request. + let vbuf = buffer.vData, + uintbuf = buffer.uintVData, + ibuf = buffer.iData; + + let data0 = data[0], data3 = data[3]; + vec3.set(vec3_temps[0], data0.x, data0.y, 0); + vec3.set(vec3_temps[1], data3.x, data0.y, 0); + vec3.set(vec3_temps[2], data0.x, data3.y, 0); + vec3.set(vec3_temps[3], data3.x, data3.y, 0); + + // get uv from sprite frame directly + let uv = sprite._spriteFrame.uv; + for (let i = 0; i < 4; i++) { + // vertex + let vertex = vec3_temps[i]; + vec3.transformMat4(vertex, vertex, matrix); + + vbuf[vertexOffset++] = vertex.x; + vbuf[vertexOffset++] = vertex.y; + vbuf[vertexOffset++] = vertex.z; + + // uv + let uvOffset = i * 2; + vbuf[vertexOffset++] = uv[0 + uvOffset]; + vbuf[vertexOffset++] = uv[1 + uvOffset]; + + // color + uintbuf[vertexOffset++] = color; + } + + // fill indice data + ibuf[indiceOffset++] = vertexId; + ibuf[indiceOffset++] = vertexId + 1; + ibuf[indiceOffset++] = vertexId + 2; + ibuf[indiceOffset++] = vertexId + 1; + ibuf[indiceOffset++] = vertexId + 3; + ibuf[indiceOffset++] = vertexId + 2; + }; + })(), + + updateVerts(sprite) { + let renderData = sprite._renderData, + node = sprite.node, + data = renderData._data, + cw = node.width, ch = node.height, + appx = node.anchorX * cw, appy = node.anchorY * ch, + l, b, r, t; + // if (sprite.trim) { + l = -appx; + b = -appy; + r = cw - appx; + t = ch - appy; + // } + // else { + // let frame = sprite.spriteFrame, + // ow = frame._originalSize.width, oh = frame._originalSize.height, + // rw = frame._rect.width, rh = frame._rect.height, + // offset = frame._offset, + // scaleX = cw / ow, scaleY = ch / oh; + // let trimLeft = offset.x + (ow - rw) / 2; + // let trimRight = offset.x - (ow - rw) / 2; + // let trimBottom = offset.y + (oh - rh) / 2; + // let trimTop = offset.y - (oh - rh) / 2; + // l = trimLeft * scaleX - appx; + // b = trimBottom * scaleY - appy; + // r = cw + trimRight * scaleX - appx; + // t = ch + trimTop * scaleY - appy; + // } + + data[0].x = l; + data[0].y = b; + // data[1].x = r; + // data[1].y = b; + // data[2].x = l; + // data[2].y = t; + data[3].x = r; + data[3].y = t; + + renderData.vertDirty = false; + } +}; + +export default simple; diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts new file mode 100644 index 0000000000..50e0a6a7d4 --- /dev/null +++ b/cocos/3d/ui/components/canvas-component.ts @@ -0,0 +1,300 @@ +/**************************************************************************** + 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 { CameraComponent } from '../../../3d/framework/camera-component'; +import { Component } from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import Rect from '../../../core/value-types/rect'; +import Size from '../../../core/value-types/size'; +import { GFXClearFlag } from '../../../gfx/define'; +import { Camera } from '../../../renderer/scene/camera'; + +/** + * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 + * 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。 + * + * @class Canvas + * @extends Component + */ +@ccclass('cc.CanvasComponent') +@executionOrder(100) +@menu('UI/Canvas') +@executeInEditMode +// @disallowMultiple +export class CanvasComponent extends Component { + + @property({ + type: Size, + }) + get designResolution () { + return cc.size(this._designResolution); + } + set designResolution (value: Size) { + this._designResolution.width = value.width; + this._designResolution.height = value.height; + this.applySettings(); + this.alignWithScreen(); + } + + /** + * !#en TODO + * !#zh: 是否优先将设计分辨率高度撑满视图高度。 + * @property {Boolean} fitHeight + * @default false + */ + @property() + get fitHeight () { + return this._fitHeight; + } + set fitHeight (value: boolean) { + if (this._fitHeight !== value) { + this._fitHeight = value; + this.applySettings(); + this.alignWithScreen(); + } + } + + /** + * !#en TODO + * !#zh: 是否优先将设计分辨率宽度撑满视图宽度。 + * @property {Boolean} fitWidth + * @default false + */ + @property() + get fitWidth () { + return this._fitWidth; + } + set fitWidth (value: boolean) { + if (this._fitWidth !== value) { + this._fitWidth = value; + this.applySettings(); + this.alignWithScreen(); + } + } + + /** + * !#en priority in render + * !#zh 显示优先级 + */ + @property + get priority () { + return this._priority; + } + + set priority (value: number) { + this._priority = value; + } + + get visibility () { + if (this._camere) { + return this._camere.view.visibility; + } + + return -1; + } + + get camera () { + return this._camere; + } + + public static views = []; + /** + * !#en The desigin resolution for current scene. + * !#zh 当前场景设计分辨率。 + * @property {Size} designResolution + * @default new cc.Size(960, 640) + */ + @property + private _designResolution = cc.size(960, 640); + @property + private _fitWidth = false; + @property + private _fitHeight = true; + @property + private _priority = 0; + + private _thisOnResized: Function | null = null; + + private _camere: Camera | null = null; + private _cameraInfo: object | 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); + } + + // public onLoad () {} + + public resetInEditor () { + // _Scene._applyCanvasPreferences(this); + } + + public __preload () { + // 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.engine.on('design-resolution-changed', this._thisOnResized); + // } + // else { + // TODO: Need to do editor initiative call + if (!CC_EDITOR) { + // if (cc.sys.isMobile) { + // window.addEventListener('resize', this._thisOnResized); + // } + // else { + // cc.view.on('canvas-resize', this._thisOnResized); + // } + cc.view.on('design-resolution-changed', this._thisOnResized); + } + + this.applySettings(); + this.alignWithScreen(); + } + + public onEnable () { + this._cameraInfo = { + name: 'ui', + clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + node: this.node, + stencil: 0, + projection: CameraComponent.ProjectionType.ORTHO, + orthoHeight: 10, + far: 4096, + near: 0.1, + rect: new Rect(0, 0, 1, 1), + color: cc.color(255, 255, 255, 255), + }; + this._camere = this._getRenderScene().createCamera(this._cameraInfo); + cc.director.root.ui.addScreen(this); + } + + public onDisable () { + if (this._camere) { + this._getRenderScene().destroyCamera(this._cameraInfo); + cc.director.root.ui.removeScreen(this); + } + } + + public onDestroy () { + if (super.onDestroy) { + super.onDestroy(); + } + // if (CC_EDITOR) { + // cc.engine.off('design-resolution-changed', this._thisOnResized); + // } + // else { + // if (cc.sys.isMobile) { + // window.removeEventListener('resize', this._thisOnResized); + // } + // else { + // cc.view.off('canvas-resize', this._thisOnResized); + // } + // } + + cc.view.off('design-resolution-changed', this._thisOnResized); + + // cc.director._uiSystem.removeScreen(this); + + // if (CanvasComponent.instance === this) { + // CanvasComponent.instance = null; + // } + } + + // + + public alignWithScreen () { + if (this._camere) { + this._camere.resize(cc.game.canvas.width, cc.game.canvas.height); + this._camere.orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2; + const viewport = this._camere.viewport; + viewport.x = viewport.y = 0; + viewport.width = cc.game.canvas.width; + viewport.height = cc.game.canvas.height; + } + // if (CC_EDITOR) { + // nodeSize = designSize = cc.engine.getDesignResolutionSize(); + // this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1); + // } + // else { + const canvasSize = cc.visibleRect; + const nodeSize = canvasSize; + const designSize = cc.view.getDesignResolutionSize(); + const clipTopRight = !this.fitHeight && !this.fitWidth; + let offsetX = 0; + let offsetY = 0; + if (clipTopRight) { + // offset the canvas to make it in the center of screen + offsetX = (designSize.width - canvasSize.width) * 0.5; + offsetY = (designSize.height - canvasSize.height) * 0.5; + } + this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1); + // } + // let canvasSize = nodeSize = cc.visibleRect; + // this.node.setPosition(canvasSize.width / 2, canvasSize.height / 2, 1); + this.node.width = nodeSize.width; + this.node.height = nodeSize.height; + } + + public applySettings () { + const ResolutionPolicy = cc.ResolutionPolicy; + let policy; + + if (this.fitHeight && this.fitWidth) { + policy = ResolutionPolicy.SHOW_ALL; + } else if (!this.fitHeight && !this.fitWidth) { + policy = ResolutionPolicy.NO_BORDER; + } else if (this.fitWidth) { + policy = ResolutionPolicy.FIXED_WIDTH; + } else { // fitHeight + policy = ResolutionPolicy.FIXED_HEIGHT; + } + + const designRes = this._designResolution; + // if (CC_EDITOR) { + // cc.engine.setDesignResolutionSize(designRes.width, designRes.height); + // } + // else { + cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy); + // } + } +} diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts new file mode 100644 index 0000000000..b7c9975a7b --- /dev/null +++ b/cocos/3d/ui/components/sprite-component.ts @@ -0,0 +1,617 @@ +/**************************************************************************** + 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. + ****************************************************************************/ +// @ts-check +import atlas from '../../../assets/CCSpriteAtlas'; +import { SpriteFrame } from '../../../assets/CCSpriteFrame'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { clampf } from '../../../core/utils/misc'; +import { Vec2, Enum } from '../../../core/value-types'; +import { MeshBuffer } from '../mesh-buffer'; +import { RenderComponent } from './ui-render-component'; +import { Node } from '../../../scene-graph/node'; +const EventType = Node.EventType; + +/** + * !#en Enum for sprite type. + * !#zh Sprite 类型 + * @enum Sprite.Type + */ +const SpriteType = Enum({ + /** + * !#en The simple type. + * !#zh 普通类型 + * @property {Number} SIMPLE + */ + SIMPLE: 0, + /** + * !#en The sliced type. + * !#zh 切片(九宫格)类型 + * @property {Number} SLICED + */ + SLICED: 1, + // /** + // * !#en The tiled type. + // * !#zh 平铺类型 + // * @property {Number} TILED + // */ + // TILED: 2, + /** + * !#en The filled type. + * !#zh 填充类型 + * @property {Number} FILLED + */ + FILLED: 3, + // /** + // * !#en The mesh type. + // * !#zh 以 Mesh 三角形组成的类型 + // * @property {Number} MESH + // */ + // MESH: 4 +}); + +/** + * !#en Enum for fill type. + * !#zh 填充类型 + * @enum Sprite.FillType + */ +const FillType = cc.Enum({ + /** + * !#en The horizontal fill. + * !#zh 水平方向填充 + * @property {Number} HORIZONTAL + */ + HORIZONTAL: 0, + /** + * !#en The vertical fill. + * !#zh 垂直方向填充 + * @property {Number} VERTICAL + */ + VERTICAL: 1, + // /** + // * !#en The radial fill. + // * !#zh 径向填充 + // * @property {Number} RADIAL + // */ + // RADIAL: 2, +}); + +/** + * !#en Sprite Size can track trimmed size, raw size or none. + * !#zh 精灵尺寸调整模式 + * @enum Sprite.SizeMode + */ +// var SizeMode = cc.Enum({ +// /** +// * !#en Use the customized node size. +// * !#zh 使用节点预设的尺寸 +// * @property {Number} CUSTOM +// */ +// CUSTOM: 0, +// /** +// * !#en Match the trimmed size of the sprite frame automatically. +// * !#zh 自动适配为精灵裁剪后的尺寸 +// * @property {Number} TRIMMED +// */ +// TRIMMED: 1, +// /** +// * !#en Match the raw size of the sprite frame automatically. +// * !#zh 自动适配为精灵原图尺寸 +// * @property {Number} RAW +// */ +// RAW: 2 +// }); + +// var State = cc.Enum({ +// /** +// * !#en The normal state +// * !#zh 正常状态 +// * @property {Number} NORMAL +// */ +// NORMAL: 0, +// /** +// * !#en The gray state, all color will be modified to grayscale value. +// * !#zh 灰色状态,所有颜色会被转换成灰度值 +// * @property {Number} GRAY +// */ +// GRAY: 1 +// }); + +@ccclass('cc.SpriteComponent') +@executionOrder(100) +@menu('UI/Sprite') +@executeInEditMode +export class SpriteComponent extends RenderComponent { + + /** + * !#en The sprite frame of the sprite. + * !#zh 精灵的精灵帧 + * @return {SpriteFrame} + */ + @property({ + type: SpriteFrame, + }) + get spriteFrame () { + return this._spriteFrame; + } + + set spriteFrame (value: SpriteFrame | null) { + if (this._spriteFrame === value) { + return; + } + + const lastSprite = this._spriteFrame; + this._spriteFrame = value; + // render & update render data flag will be triggered while applying new sprite frame + this.markForUpdateRenderData(false); + this._applySpriteFrame(lastSprite); + if (CC_EDITOR) { + // @ts-ignore + this.node.emit('spriteframe-changed', this); + } + } + + /** + * !#en The sprite render type. + * !#zh 精灵渲染类型 + * @property type + * @type {Sprite.Type} + * @example + * sprite.type = cc.Sprite.Type.SIMPLE; + */ + @property({ + type: SpriteType, + }) + get type () { + return this._type; + } + set type (value: number) { + if (this._type !== value) { + this._type = value; + this._updateAssembler(); + } + } + + /** + * !#en + * The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 精灵填充类型,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillType + * @type {Sprite.FillType} + * @example + * sprite.fillType = SpriteComponent.FillType.HORIZONTAL; + */ + @property({ + type: FillType, + }) + get fillType () { + return this._fillType; + } + set fillType (value: number) { + if (value !== this._fillType) { + if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) { + // this.destroyRenderData(/*this._renderData*/); + this._renderData = null; + } else if (this._renderData) { + this.markForUpdateRenderData(true); + } + this._fillType = value; + this._updateAssembler(); + } + } + + /** + * !#en + * The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 填充中心点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillCenter + * @type {Vec2} + * @example + * sprite.fillCenter = new cc.v2(0, 0); + */ + @property + get fillCenter () { + return this._fillCenter; + } + set fillCenter (value: Vec2) { + this._fillCenter.x = value.x; + this._fillCenter.y = value.y; + if (this._type === SpriteType.FILLED && this._renderData) { + this.markForUpdateRenderData(true); + } + } + + /** + * !#en + * The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 填充起始点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillStart + * @type {Number} + * @example + * // -1 To 1 between the numbers + * sprite.fillStart = 0.5; + */ + @property + get fillStart () { + return this._fillStart; + } + + set fillStart (value: number) { + this._fillStart = clampf(value, -1, 1); + if (this._type === SpriteType.FILLED && this._renderData) { + this.markForUpdateRenderData(true); + } + } + + /** + * !#en + * The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. + * !#zh + * 填充范围,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。 + * @property fillRange + * @type {Number} + * @example + * // -1 To 1 between the numbers + * sprite.fillRange = 1; + */ + @property + get fillRange () { + return this._fillRange; + } + set fillRange (value: number) { + // ??? -1 ~ 1 + // this._fillRange = cc.misc.clampf(value, -1, 1); + this._fillRange = clampf(value, 0, 1); + if (this._type === SpriteType.FILLED && this._renderData) { + this.markForUpdateRenderData(true); + } + } + /** + * !#en specify the frame is trimmed or not. + * !#zh 是否使用裁剪模式 + * @property trim + * @type {Boolean} + * @example + * sprite.trim = true; + */ + get trim () { + // return this._isTrimmedMode; + return false; + } + + set trim (value: boolean) { + // if (this._isTrimmedMode !== value) { + // this._isTrimmedMode = value; + // if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) && + // this._renderData) { + // this.markForUpdateRenderData(true); + // } + // } + if (this._spriteFrame) { + this.node.setContentSize(this._spriteFrame.getOriginalSize()); + } + } + + // /** + // * !#en specify the size tracing mode. + // * !#zh 精灵尺寸调整模式 + // * @property sizeMode + // * @type {Sprite.SizeMode} + // * @example + // * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; + // */ + // get sizeMode() { + // return this._sizeMode; + // } + // set sizeMode(value) { + // // this._sizeMode = value; + // // if (value !== SizeMode.CUSTOM) { + // // this._applySpriteSize(); + // // } + // } + + public static FillType = FillType; + public static Type = SpriteType; + @property + public _spriteFrame: SpriteFrame | null = null; + @property + public _type: number = SpriteType.SIMPLE; + @property + public _fillType: number = FillType.HORIZONTAL; + // @property + // _sizeMode = SizeMode.TRIMMED; + @property + public _fillCenter: Vec2 = cc.v2(0, 0); + @property + public _fillStart: number = 0; + @property + public _fillRange: number = 0; + // @property + // _isTrimmedMode = true; + // _state = 0; + // TODO: + @property + public _atlas: atlas | null = null; + public _assembler = null; + public _spriteWidget = null; + // static SizeMode = SizeMode; + // static State = State; + + // /** + // * Change the state of sprite. + // * @method setState + // * @see `SpriteComponent.State` + // * @param state {SpriteComponent.State} NORMAL or GRAY State. + // */ + // getState() { + // return this._state; + // } + + // setState(state) { + // if (this._state === state) return; + // this._state = state; + // this._activateMaterial(); + // } + + // onLoad() {} + + public onEnable () { + super.onEnable(); + if (this._spriteFrame) { + if (!this._spriteFrame.textureLoaded()) { + // this._spriteFrame.once('load', this._onTextureLoaded, this); + this._spriteFrame.ensureLoadTexture(); + } + } + + this._updateAssembler(); + this._activateMaterial(); + + if (!this._spriteFrame) { + this.spriteFrame = cc.BuiltinResMgr['default-spriteframe']; + } + + // this.node.on(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this); + // this.node.on(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this); + } + + public updateRenderData (buffer: MeshBuffer) { + if (!this._spriteFrame || !this.material) { + return; + } + + this._assembler.updateRenderData(this); + this._assembler.fillBuffers(this, buffer); + } + + public onDestroy () { + super.onDestroy(); + this.destroyRenderData(); + } + + public onDisable () { + // this._super(); + super.onDisable(); + + this.node.off(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this); + this.node.off(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this); + } + + public _onNodeSizeDirty () { + if (!this._renderData) { return; } + this.markForUpdateRenderData(true); + } + + public _updateAssembler () { + const assembler = SpriteComponent._assembler.getAssembler(this); + + if (this._assembler !== assembler) { + this.destroyRenderData(); + this._assembler = assembler; + } + + if (!this._renderData) { + this._renderData = this._assembler.createData(this); + this._renderData.material = this.material; + this.markForUpdateRenderData(true); + } + } + + public _activateMaterial () { + const spriteFrame = this._spriteFrame; + let material = this.material; + // WebGL + if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { + if (!material) { + this.material = cc.BuiltinResMgr['sprite-material']; + material = this.material; + if (spriteFrame && spriteFrame.textureLoaded()) { + material.setProperty('mainTexture', spriteFrame); + this.markForUpdateRenderData(true); + } + } else { + if (spriteFrame && spriteFrame.textureLoaded()) { + const matTexture = material.effect && material.effect.getProperty('mainTexture'); + if (matTexture !== spriteFrame) { + material.setProperty('mainTexture', spriteFrame); + this.markForUpdateRenderData(true); + } + } + } + + if (this._renderData) { + this._renderData.material = material; + } + } else { + this.markForUpdateRenderData(true); + // this.markForRender(true); + } + } + + public _applyAtlas (spriteFrame: SpriteFrame | null) { + if (!CC_EDITOR) { + return; + } + // Set atlas + if (spriteFrame && spriteFrame._atlasUuid) { + const self = this; + cc.AssetLibrary.loadAsset(spriteFrame._atlasUuid, function (err, asset) { + self._atlas = asset; + }); + } else { + this._atlas = null; + } + } + + public _canRender () { + if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { + if (!this._enabled) { return false; } + } else { + if (!this._enabled || !this.material) { return false; } + } + + const spriteFrame = this._spriteFrame; + if (!spriteFrame || !spriteFrame.textureLoaded()) { + return false; + } + return true; + } + + public markForUpdateRenderData (enable: boolean) { + if (enable /*&& this._canRender()*/) { + // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; + + const renderData = this._renderData; + if (renderData) { + renderData.uvDirty = true; + renderData.vertDirty = true; + } + } + // else if (!enable) { + // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; + // } + } + + // _applySpriteSize() { + // if (this._spriteFrame) { + // if (SizeMode.RAW === this._sizeMode) { + // var size = this._spriteFrame.getOriginalSize(); + // this.node.setContentSize(size); + // } else if (SizeMode.TRIMMED === this._sizeMode) { + // var rect = this._spriteFrame.getRect(); + // this.node.setContentSize(rect.width, rect.height); + // } + + // this._activateMaterial(); + // } + // } + + // _onTextureLoaded() { + // if (!this.isValid) { + // return; + // } + + // this._applySpriteSize(); + // } + + public _applySpriteFrame (oldFrame: SpriteFrame | null) { + // if (oldFrame && oldFrame.off) { + // oldFrame.off('load', this._onTextureLoaded, this); + // } + + const spriteFrame = this._spriteFrame; + // if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) { + // // disable render flow until texture is loaded + // this.markForRender(false); + // } + + if (spriteFrame) { + if (!oldFrame || spriteFrame !== oldFrame) { + // this.material.setProperty('mainTexture', spriteFrame); + if (spriteFrame.textureLoaded()) { + // this._onTextureLoaded(); + this._activateMaterial(); + } else { + // spriteFrame.once('load', this._onTextureLoaded, this); + spriteFrame.ensureLoadTexture(); + } + } + // else { + // this._applySpriteSize(); + // } + } + + if (CC_EDITOR) { + // Set atlas + this._applyAtlas(spriteFrame); + } + } + + // _resized() { + // if (!CC_EDITOR) { + // return; + // } + + // if (this._spriteFrame) { + // var actualSize = this.node.getContentSize(); + // var expectedW = actualSize.width; + // var expectedH = actualSize.height; + // if (this._sizeMode === SizeMode.RAW) { + // var size = this._spriteFrame.getOriginalSize(); + // expectedW = size.width; + // expectedH = size.height; + // } else if (this._sizeMode === SizeMode.TRIMMED) { + // var rect = this._spriteFrame.getRect(); + // expectedW = rect.width; + // expectedH = rect.height; + + // } + + // if (expectedW !== actualSize.width || expectedH !== actualSize.height) { + // this._sizeMode = SizeMode.CUSTOM; + // } + // } + // } +} + +// if (CC_EDITOR) { +// // override __preload +// Sprite.prototype.__superPreload = cc.Component.prototype.__preload; +// Sprite.prototype.__preload = function () { +// if (this.__superPreload) this.__superPreload(); +// this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); +// }; +// // override onDestroy +// Sprite.prototype.__superOnDestroy = cc.Component.prototype.onDestroy; +// Sprite.prototype.onDestroy = function () { +// if (this.__superOnDestroy) this.__superOnDestroy(); +// this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); +// }; +// } + +// cc.Sprite = module.exports = Sprite; diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts new file mode 100644 index 0000000000..da9c106df0 --- /dev/null +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -0,0 +1,254 @@ +/**************************************************************************** + 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 { RenderableComponent } from '../../../3d/framework/renderable-component'; +// import gfx from '../../renderer/gfx/index'; +import { + ccclass, + executeInEditMode, + executionOrder, + property, + requireComponent, +} from '../../../core/data/class-decorator'; +import macro from '../../../core/platform/CCMacro'; +import { Color } from '../../../core/value-types/index'; +import { RenderData } from '../../../renderer/ui/renderData'; +import { CanvasComponent } from './canvas-component'; +import { UITransformComponent } from './ui-transfrom-component'; + +/** + * !#en + * Base class for components which supports rendering features. + * !#zh + * 所有支持渲染的组件的基类 + * + * @class RenderComponent + * @extends Component + */ +@ccclass('cc.RenderComponent') +@executionOrder(100) +@requireComponent(UITransformComponent) +export class RenderComponent extends RenderableComponent { + + /** + * !#en specify the source Blend Factor, this will generate a custom material object + * please pay attention to the memory cost. + * !#zh 指定原图的混合模式,这会克隆一个新的材质对象,注意这带来的 + * @property srcBlendFactor + * sprite.srcBlendFactor = macro.BlendFactor.ONE; + */ + @property({ + type: macro.BlendFactor, + }) + get srcBlendFactor () { + return this._srcBlendFactor; + } + set srcBlendFactor (value) { + if (this._srcBlendFactor === value) { return; } + this._srcBlendFactor = value; + this._updateBlendFunc(true); + } + + /** + * !#en specify the destination Blend Factor. + * !#zh 指定目标的混合模式 + * @property dstBlendFactor + * @type {macro.BlendFactor} + * @example + * sprite.dstBlendFactor = cc.macro.BlendFactor.ONE; + */ + @property({ + type: macro.BlendFactor, + }) + get dstBlendFactor () { + return this._dstBlendFactor; + } + + set dstBlendFactor (value) { + if (this._dstBlendFactor === value) { return; } + this._dstBlendFactor = value; + this._updateBlendFunc(true); + } + + get color () { + return this._color; + } + + set color (value) { + if (this._color === value) { + return; + } + + this._color = value; + } + + get viewID () { + return this._viewID; + } + + public static assembler = null; + protected _renderDataPoolID: number = -1; + protected _viewID: number = -1; + + protected _srcBlendFactor: number = macro.BlendFactor.SRC_ALPHA; + protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA; + @property + protected _color: Color = Color.WHITE; + protected _renderData: RenderData | null = null; + // _allocedDatas = []; + // _vertexFormat = null; + // _toPostHandle = false; + + constructor () { + super(); + // this._assembler = this.constructor._assembler; + // this._postAssembler = this.constructor._postAssembler; + } + + public onEnable () { + let parent = this.node; + while (parent) { + if (parent) { + const canvasComp = parent.getComponent(CanvasComponent); + if (canvasComp) { + this._viewID = canvasComp.visibility; + break; + } + } + + // @ts-ignore + parent = parent.parent; + } + // if (this.node._renderComponent) { + // this.node._renderComponent.enabled = false; + // } + // this.node._renderComponent = this; + // this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR; + } + + public onDisable () { + this._viewID = -1; + // this.node._renderComponent = null; + // this.disableRender(); + } + + public onDestroy () { + // for (let i = 0, l = this._allocedDatas.length; i < l; i++) { + // RenderData.free(this._allocedDatas[i]); + // } + // this._allocedDatas.length = 0; + this.destroyRenderData(); + this.material = null; + this._renderData = null; + } + + // _canRender() { + // return this._enabled; + // } + + // markForUpdateRenderData(enable) { + // // if (enable && this._canRender()) { + // // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; + // // } + // // else if (!enable) { + // // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; + // // } + // } + + // markForRender(enable) { + // // if (enable && this._canRender()) { + // // this.node._renderFlag |= RenderFlow.FLAG_RENDER; + // // } + // // else if (!enable) { + // // this.node._renderFlag &= ~RenderFlow.FLAG_RENDER; + // // } + // } + + // markForCustomIARender(enable) { + // // if (enable && this._canRender()) { + // // this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER; + // // } + // // else if (!enable) { + // // this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER; + // // } + // } + + // disableRender() { + // // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR); + // } + + public requestRenderData () { + const data = RenderData.add(); + // this._allocedDatas.push(data); + this._renderData = data.data; + this._renderDataPoolID = data.pooID; + return this._renderData; + } + + public destroyRenderData () { + // let index = this._allocedDatas.indexOf(data); + // if (index !== -1) { + // this._allocedDatas.splice(index, 1); + // RenderData.free(data); + // } + if (this._renderDataPoolID === -1) { + return; + } + + RenderData.remove(this._renderDataPoolID); + this._renderDataPoolID = -1; + this._renderData = null; + } + + public _updateColor () { + const material = this.material; + if (material) { + material.setProperty('color', this._color); + // material.updateHash(); + } + } + + // TODO: + public _updateBlendFunc (updateHash) { + // if (!this.material) { + // return; + // } + + // var pass = this.material._mainTech.passes[0]; + // pass.setBlend( + // gfx.BLEND_FUNC_ADD, + // this._srcBlendFactor, this._dstBlendFactor, + // gfx.BLEND_FUNC_ADD, + // this._srcBlendFactor, this._dstBlendFactor + // ); + + // if (updateHash) { + // this.material.updateHash(); + // } + } +} + +// RenderComponent._assembler = null; +// RenderComponent._postAssembler = null; diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts new file mode 100644 index 0000000000..193e1c686b --- /dev/null +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -0,0 +1,286 @@ +import { Component} from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import Event from '../../../core/platform/event-manager/CCEvent.js'; +import Size from '../../../core/value-types/size'; +import Vec2 from '../../../core/value-types/vec2'; +import * as math from '../../../core/vmath/index'; +import { Enum } from '../../../core/value-types'; + +const _vec2a = cc.v2(); +const _vec2b = cc.v2(); +const _mat4_temp = cc.mat4(); +const _worldMatrix = cc.mat4(); + +const EventType = Enum({ + /** + * !#en The event type for size change events. + * Performance note, this event will be triggered every time corresponding properties being changed, + * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. + * !#zh 当节点尺寸改变时触发的事件。 + * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 + * @property {String} SIZE_CHANGED + * @static + */ + SIZE_CHANGED: 'size-changed', + /** + * !#en The event type for anchor point change events. + * Performance note, this event will be triggered every time corresponding properties being changed, + * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario. + * !#zh 当节点锚点改变时触发的事件。 + * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。 + * @property {String} ANCHOR_CHANGED + * @static + */ + ANCHOR_CHANGED: 'anchor-changed', +}); + +@ccclass('cc.UITransformComponent') +@executionOrder(100) +export class UITransformComponent extends Component { + + @property + get contentSize () { + return this._contentSize; + } + + set contentSize (value) { + if (this._contentSize === value) { + return; + } + + this._contentSize = value; + this.node.emit(EventType.SIZE_CHANGED); + } + + get width () { + return this._contentSize.width; + } + + set width (value) { + if (this._contentSize.width === value) { + return; + } + + this._contentSize.width = value; + this.node.emit(EventType.SIZE_CHANGED); + } + + get height () { + return this._contentSize.height; + } + + set height (value) { + if (this._contentSize.height === value) { + return; + } + + this._contentSize.height = value; + this.node.emit(EventType.SIZE_CHANGED); + } + + @property + get anchorPoint () { + return this._anchorPoint; + } + + set anchorPoint (value) { + if (this._anchorPoint === value) { + return; + } + + this._anchorPoint = value; + this.node.emit(EventType.ANCHOR_CHANGED); + } + + get anchorX () { + return this._anchorPoint.x; + } + + set anchorX (value) { + if (this._anchorPoint.x === value) { + return; + } + + this._anchorPoint.x = value; + this.node.emit(EventType.ANCHOR_CHANGED); + } + + get anchorY () { + return this._anchorPoint.y; + } + + set anchorY (value) { + if (this._anchorPoint.y === value) { + return; + } + + this._anchorPoint.y = value; + this.node.emit(EventType.ANCHOR_CHANGED); + } + + public static EventType = EventType; + @property + public _contentSize = new cc.Size(100, 100); + @property + public _anchorPoint = cc.v2(0.5, 0.5); + + public onEnable () { + this.node.uiTransfromComp = this; + } + + public onDisable () { + this.node.uiTransfromComp = null; + } + + /** + * !#en + * Sets the untransformed size of the node.
+ * The contentSize remains the same no matter the node is scaled or rotated.
+ * All nodes has a size. Layer and Scene has the same size of the screen. + * !#zh 设置节点原始大小,不受该节点是否被缩放或者旋转的影响。 + * @method setContentSize + * @param {Size|Number} size - The untransformed size of the node or The untransformed size's width of the node. + * @param {Number} [height] - The untransformed size's height of the node. + * @example + * node.setContentSize(cc.size(100, 100)); + * node.setContentSize(100, 100); + */ + public setContentSize (size: Size, height: number) { + const locContentSize = this._contentSize; + // var clone; + if (height === undefined) { + if ((size.width === locContentSize.width) && (size.height === locContentSize.height)) { + return; + } + // if (CC_EDITOR) { + // clone = cc.size(locContentSize.width, locContentSize.height); + // } + locContentSize.width = size.width; + locContentSize.height = size.height; + } else { + if ((size === locContentSize.width) && (height === locContentSize.height)) { + return; + } + // if (CC_EDITOR) { + // clone = cc.size(locContentSize.width, locContentSize.height); + // } + locContentSize.width = size; + locContentSize.height = height; + } + // if (CC_EDITOR) { + // this.emit(EventType.SIZE_CHANGED, clone); + // } + // else { + this.node.emit(EventType.SIZE_CHANGED); + // } + } + + /** + * !#en + * Sets the anchor point in percent.
+ * anchor point is the point around which all transformations and positioning manipulations take place.
+ * It's like a pin in the node where it is "attached" to its parent.
+ * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
+ * But you can use values higher than (1,1) and lower than (0,0) too.
+ * The default anchor point is (0.5,0.5), so it starts at the center of the node. + * !#zh + * 设置锚点的百分比。
+ * 锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。
+ * 锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。
+ * 但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。
+ * 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。
+ * 注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 + * @method setAnchorPoint + * @param {Vec2|Number} point - The anchor point of node or The x axis anchor of node. + * @param {Number} [y] - The y axis anchor of node. + * @example + * node.setAnchorPoint(cc.v2(1, 1)); + * node.setAnchorPoint(1, 1); + */ + public setAnchorPoint (point: Vec2, y: number) { + const locAnchorPoint = this._anchorPoint; + if (y === undefined) { + if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y)) { + return; + } + locAnchorPoint.x = point.x; + locAnchorPoint.y = point.y; + } else { + if ((point === locAnchorPoint.x) && (y === locAnchorPoint.y)) { + return; + } + locAnchorPoint.x = point; + locAnchorPoint.y = y; + } + // this.setLocalDirty(LocalDirtyFlag.POSITION); + // if (this._eventMask & ANCHOR_ON) { + this.node.emit(EventType.ANCHOR_CHANGED); + // } + } + + public isHit (point: Vec2, listener: Event) { + const w = this._contentSize.width; + const h = this._contentSize.height; + const cameraPt = _vec2a; + const testPt = _vec2b; + + const renderComp = this.node.getComponent(cc.RenderComponent); + if (!renderComp) { + return false; + } + const canvas = cc.CanvasComponent.findView(renderComp); + if (!canvas) { + return; + } + + canvas.node.getWorldRT(_mat4_temp); + + const m12 = _mat4_temp.m12; + const m13 = _mat4_temp.m13; + + const center = cc.visibleRect.center; + // let size = cc.view.getFrameSize(); + // let center = cc.v2(size.width / 2, size.height / 2); + // let center = cc.v2(cc.game._renderer._device._gl.canvas.width / 2, cc.game._renderer._device._gl.canvas.height / 2); + _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13); + _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13); + + // if (out !== _mat4_temp) { + // mat4.copy(out, _mat4_temp); + // } + math.mat4.invert(_mat4_temp, _mat4_temp); + math.vec2.transformMat4(cameraPt, point, _mat4_temp); + // let camera = cc.Camera.findCamera(this); + // if (camera) { + // camera.getCameraToWorldPoint(point, cameraPt); + // } + // else { + // cameraPt.set(point); + // } + + this.node.getWorldMatrix(_worldMatrix); + math.mat4.invert(_mat4_temp, _worldMatrix); + math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); + testPt.x += this._anchorPoint.x * w; + testPt.y += this._anchorPoint.y * h; + + if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { + if (listener && listener.mask) { + const mask = listener.mask; + const parent = this; + // find mask parent, should hit test it + if (parent === mask.node) { + const comp = parent.getComponent(cc.Mask); + return (comp && comp.enabledInHierarchy) ? comp._hitTest(cameraPt) : true; + } else { + listener.mask = null; + return true; + } + } else { + return true; + } + } else { + return false; + } + } +} diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts new file mode 100644 index 0000000000..46d62b4fe9 --- /dev/null +++ b/cocos/3d/ui/index.ts @@ -0,0 +1,30 @@ + +import { CanvasComponent} from './components/canvas-component'; +import {RenderComponent} from './components/ui-render-component'; +import { SpriteComponent} from './components/sprite-component'; +import { UITransformComponent } from './components/ui-transfrom-component'; +// import LabelComponent from './components/label-component'; +// import UIRectComponent fro./components/ui-transfrom-componentent'; +// import ButtonComponent from './components/button-component'; +// import ToggleGroupComponent from './components/toggle-group-component'; +// import ToggleComponent from './components/toggle-component'; +// import ToggleContainerComponent from './components/toggle-container-component'; +// import SliderComponent from './components/slider-component'; +// import ProgressBarComponent from './components/progress-bar-component'; +// import WidgetComponent from './components/widget-component'; +// import EditBoxComponent from './components/editbox/edit-box-component'; +import './assembler/index'; + +cc.CanvasComponent = CanvasComponent; +cc.RenderComponent = RenderComponent; +cc.SpriteComponent = SpriteComponent; +// cc.LabelComponent = LabelComponent; +// cc.UIRectComponent = UIRectComponent; +// cc.ButtonComponent = ButtonComponent; +// cc.ToggleGroupComponent = ToggleGroupComponent; +// cc.ToggleComponent = ToggleComponent; +// cc.ToggleContainerComponent = ToggleContainerComponent; +// cc.SliderComponent = SliderComponent; +// cc.ProgressBarComponent = ProgressBarComponent; +// cc.WidgetComponent = WidgetComponent; +// cc.EditBoxComponent = EditBoxComponent; diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts new file mode 100644 index 0000000000..614e42afa1 --- /dev/null +++ b/cocos/3d/ui/mesh-buffer.ts @@ -0,0 +1,214 @@ +// import gfx from '../gfx/index'; +// import VertexFormat from '../gfx/vertex-format'; +// import { UI } from './ui'; +import { GFXDevice } from '../../gfx/device'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from '../../gfx/define'; +import { IGFXInputAttribute } from '../../gfx/input-assembler'; +// import UISystem from '../UISystem'; + +export class MeshBuffer { + public byteStart: number = 0; + public byteOffset: number = 0; + public indiceStart: number = 0; + public indiceOffset: number = 0; + public vertexStart: number = 0; + public vertexOffset: number = 0; + public _vertexBytes: number = 0; + public _vb: GFXBuffer | null = null; + public _ib: GFXBuffer | null = null; + public vData: Float32Array | null = null; + public iData: Uint16Array | null = null; + public uintVData: Uint32Array | null = null; + + private _vertexFormat: IGFXInputAttribute[] = []; + // private _renderer: UI|null = null; + + private _initVDataCount: number = 0; // actually 256 * 4 * (vertexFormat._bytes / 4) + private _initIDataCount: number = 256 * 6; + private _dirty: boolean = false; + + constructor (device: GFXDevice, vertexFormat: IGFXInputAttribute[]) { + + // const device = cc.game._renderContext; + this._vertexFormat = vertexFormat; + + // TODO: calculate + this._vertexBytes = this.calculateBytes(vertexFormat)/*this._vertexFormat._bytes*/; + // this._vb = new gfx.VertexBuffer( + // device, + // vertexFormat, + // gfx.USAGE_DYNAMIC, + // new ArrayBuffer(0), + // 0, + // ); + // this._vb = device.createBuffer({ + // usage: GFXBufferUsageBit.VERTEX, + // memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + // size: 0, + // stride: 0, + // }); + // this._ib = new gfx.IndexBuffer( + // device, + // gfx.INDEX_FMT_UINT16, + // gfx.USAGE_STATIC, + // new ArrayBuffer(0), + // 0, + // ); + + // this._ib = device.createBuffer({ + // usage: GFXBufferUsageBit.INDEX, + // memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + // size: 0, + // stride: 2, + // }); + // this._renderer = renderer; + this._initVDataCount = 256 * this._vertexBytes; + this._reallocBuffer(); + } + + public uploadData () { + if (this.byteOffset === 0 || !this._dirty) { + return; + } + + // update vertext data + // const vertexsData = new Float32Array(this.vData!.buffer, 0, this.byteOffset >> 2); + // const indicesData = new Uint16Array(this.iData!.buffer, 0, this.indiceOffset); + + // const vb = this._vb; + // vb.update(0, vertexsData); + + // const ib = this._ib; + // ib.update(0, indicesData); + + this._dirty = false; + } + + public requestStatic (vertexCount, indiceCount) { + const byteOffset = this.byteOffset + vertexCount * this._vertexBytes; + const indiceOffset = this.indiceOffset + indiceCount; + + let byteLength = this.vData!.byteLength; + let indiceLength = this.iData!.length; + if (byteOffset > byteLength || indiceOffset > indiceLength) { + while (byteLength < byteOffset || indiceLength < indiceOffset) { + this._initVDataCount *= 2; + this._initIDataCount *= 2; + + byteLength = this._initVDataCount * 4; + indiceLength = this._initIDataCount; + } + + this._reallocBuffer(); + } + + this.vertexOffset += vertexCount; + this.indiceOffset += indiceCount; + + this.byteOffset = byteOffset; + + this._dirty = true; + } + + public request (vertexCount, indiceCount) { + // There used to be two buffer, quad and mesh, now together. + // if (this._renderer!.buffer !== this) { + // this._renderer!.flush(); + // this._renderer!.buffer = this; + // } + + this.requestStatic(vertexCount, indiceCount); + } + + public _reallocBuffer () { + this._reallocVData(true); + this._reallocIData(true); + } + + public _reallocVData (copyOldData) { + let oldVData; + if (this.vData) { + oldVData = new Uint8Array(this.vData.buffer); + } + + this.vData = new Float32Array(this._initVDataCount); + this.uintVData = new Uint32Array(this.vData.buffer); + const newData = new Uint8Array(this.uintVData.buffer); + + if (oldVData && copyOldData) { + for (let i = 0, l = oldVData.length; i < l; i++) { + newData[i] = oldVData[i]; + } + } + + // this._vb._bytes = this.vData.byteLength; + } + + public _reallocIData (copyOldData) { + const oldIData = this.iData; + + this.iData = new Uint16Array(this._initIDataCount); + + if (oldIData && copyOldData) { + const iData = this.iData; + for (let i = 0, l = oldIData.length; i < l; i++) { + iData[i] = oldIData[i]; + } + } + + // this._ib._bytes = this.iData.byteLength; + } + + public reset () { + this.byteStart = 0; + this.byteOffset = 0; + this.indiceStart = 0; + this.indiceOffset = 0; + this.vertexStart = 0; + this.vertexOffset = 0; + this._dirty = false; + } + + public destroy () { + // this._ib.destroy(); + // this._vb.destroy(); + } + + private calculateBytes (vertexFormat: IGFXInputAttribute[]) { + let bytes = 0; + let num = 0; + for (const attr of vertexFormat) { + let name = GFXFormat[attr.format].toString(); + if (name.startsWith('RGBA')) { + num = 4; + } else if (name.startsWith('RGB')) { + num = 3; + } else if (name.startsWith('RG')) { + num = 2; + } else { + num = 1; + } + + name = name.substring(num); + switch (name) { + case '8I': + case '8UI': + bytes += num; + break; + case '16I': + case '16UI': + bytes += num * 2; + break; + case '32I': + case '32UI': + case '32F': + bytes += num * 2; + break; + } + } + + return bytes; + } +} +cc.MeshBuffer = MeshBuffer; diff --git a/cocos/assets/index.js b/cocos/assets/index.js index 1124f26705..b4981657a6 100644 --- a/cocos/assets/index.js +++ b/cocos/assets/index.js @@ -29,7 +29,7 @@ export { Asset } from './asset'; export {default as Prefab} from './CCPrefab'; export * from './CCScripts'; export {default as SceneAsset} from './CCSceneAsset'; -export {default as SpriteFrame} from './CCSpriteFrame'; +export { SpriteFrame } from './CCSpriteFrame'; export {default as SpriteAtlas} from './CCSpriteAtlas'; export {default as TextAsset} from './CCTextAsset'; export {default as JsonAsset} from './CCJsonAsset'; diff --git a/cocos/components/CCCanvas.js b/cocos/components/CCCanvas.js deleted file mode 100644 index 6fe2a72a16..0000000000 --- a/cocos/components/CCCanvas.js +++ /dev/null @@ -1,243 +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. - ****************************************************************************/ - -import Camera from '../camera/CCCamera'; -import { Component } from './component'; -import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from '../core/data/class-decorator'; - -/** - * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 - * 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。 - * - * @class Canvas - * @extends Component - */ -@ccclass('cc.Canvas') -@menu('UI/Canvas') -@help('i18n:COMPONENT.help_url.canvas') -@executeInEditMode -@disallowMultiple -export default class Canvas extends Component { - /** - * !#en Current active canvas, the scene should only have one active canvas at the same time. - * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 - * @property {Canvas} instance - * @static - */ - static instance = null; - - /** - * !#en The desigin resolution for current scene. - * !#zh 当前场景设计分辨率。 - * @property {Size} designResolution - * @default new cc.Size(960, 640) - */ - @property - _designResolution = cc.size(960, 640); - @property({ - tooltip: CC_DEV && 'i18n:COMPONENT.canvas.design_resolution', - type: cc.Size - }) - get designResolution () { - return cc.size(this._designResolution); - } - set designResolution (value) { - this._designResolution.width = value.width; - this._designResolution.height = value.height; - this.applySettings(); - this.alignWithScreen(); - } - - @property - _fitWidth = false; - @property - _fitHeight = true; - - /** - * !#en TODO - * !#zh: 是否优先将设计分辨率高度撑满视图高度。 - * @property {Boolean} fitHeight - * @default false - */ - @property({ - tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_height' - }) - get fitHeight () { - return this._fitHeight; - } - set fitHeight (value) { - if (this._fitHeight !== value) { - this._fitHeight = value; - this.applySettings(); - this.alignWithScreen(); - } - } - - /** - * !#en TODO - * !#zh: 是否优先将设计分辨率宽度撑满视图宽度。 - * @property {Boolean} fitWidth - * @default false - */ - @property({ - tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_width' - }) - get fitWidth () { - return this._fitWidth; - } - set fitWidth (value) { - if (this._fitWidth !== value) { - this._fitWidth = value; - this.applySettings(); - this.alignWithScreen(); - } - } - - constructor () { - super(); - this._thisOnResized = this.alignWithScreen.bind(this); - } - - resetInEditor () { - _Scene._applyCanvasPreferences(this); - } - - __preload () { - if (CC_DEV) { - var Flags = cc.Object.Flags; - this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked); - } - - if (Canvas.instance) { - return cc.errorID(6700, - this.node.name, Canvas.instance.node.name); - } - Canvas.instance = this; - - if (CC_EDITOR) { - cc.engine.on('design-resolution-changed', this._thisOnResized); - } - else { - if (cc.sys.isMobile) { - window.addEventListener('resize', this._thisOnResized); - } - else { - cc.view.on('canvas-resize', this._thisOnResized); - } - } - - this.applySettings(); - this.alignWithScreen(); - - // Camera could be removed in canvas render mode - // let cameraNode = cc.find('Main Camera', this.node); - // if (!cameraNode) { - // cameraNode = new cc.Node('Main Camera'); - // cameraNode.parent = this.node; - // cameraNode.setSiblingIndex(0); - // } - // let camera = cameraNode.getComponent(Camera); - // if (!camera) { - // camera = cameraNode.addComponent(Camera); - - // let ClearFlags = Camera.ClearFlags; - // camera.clearFlags = ClearFlags.COLOR | ClearFlags.DEPTH | ClearFlags.STENCIL; - // camera.depth = -1; - // } - // Camera.main = camera; - } - - onDestroy () { - if (CC_EDITOR) { - cc.engine.off('design-resolution-changed', this._thisOnResized); - } - else { - if (cc.sys.isMobile) { - window.removeEventListener('resize', this._thisOnResized); - } - else { - cc.view.off('canvas-resize', this._thisOnResized); - } - } - - if (Canvas.instance === this) { - Canvas.instance = null; - } - } - - // - - alignWithScreen () { - var designSize, nodeSize; - if (CC_EDITOR) { - nodeSize = designSize = cc.engine.getDesignResolutionSize(); - this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1); - } - else { - var canvasSize = nodeSize = cc.visibleRect; - designSize = cc.view.getDesignResolutionSize(); - var clipTopRight = !this.fitHeight && !this.fitWidth; - var offsetX = 0; - var offsetY = 0; - if (clipTopRight) { - // offset the canvas to make it in the center of screen - offsetX = (designSize.width - canvasSize.width) * 0.5; - offsetY = (designSize.height - canvasSize.height) * 0.5; - } - this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1); - } - this.node.width = nodeSize.width; - this.node.height = nodeSize.height; - } - - applySettings () { - var ResolutionPolicy = cc.ResolutionPolicy; - var policy; - - if (this.fitHeight && this.fitWidth) { - policy = ResolutionPolicy.SHOW_ALL; - } - else if (!this.fitHeight && !this.fitWidth) { - policy = ResolutionPolicy.NO_BORDER; - } - else if (this.fitWidth) { - policy = ResolutionPolicy.FIXED_WIDTH; - } - else { // fitHeight - policy = ResolutionPolicy.FIXED_HEIGHT; - } - - var designRes = this._designResolution; - if (CC_EDITOR) { - cc.engine.setDesignResolutionSize(designRes.width, designRes.height); - } - else { - cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy); - } - } -} - -cc.Canvas = Canvas; diff --git a/cocos/core/value-types/mat4.ts b/cocos/core/value-types/mat4.ts new file mode 100644 index 0000000000..e9a7db86a2 --- /dev/null +++ b/cocos/core/value-types/mat4.ts @@ -0,0 +1,449 @@ +/**************************************************************************** + Copyright (c) 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 { Vec3 } from 'cannon'; +import CCClass from '../data/class'; +import { mat4 } from '../vmath'; +import Quat from './quat'; +import { ValueType } from './value-type'; + +/** + * !#en Representation of 4*4 matrix. + * !#zh 表示 4*4 矩阵 + */ +export default class Mat4 extends ValueType { + public m00: number; + public m01: number; + public m02: number; + public m03: number; + public m04: number; + public m05: number; + public m06: number; + public m07: number; + public m08: number; + public m09: number; + public m10: number; + public m11: number; + public m12: number; + public m13: number; + public m14: number; + public m15: number; + + /** + * !#en + * Constructor + * see {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * + * @param other + */ + constructor (other: Mat4); + + /** + * !#en + * Constructor + * see {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * !#zh + * 构造函数,可查看 {{#crossLink "cc/mat4:method"}}cc.mat4{{/crossLink}} + * + * @param m00 Component in column 0, row 0 position (index 0) + * @param m01 Component in column 0, row 1 position (index 1) + * @param m02 Component in column 0, row 2 position (index 2) + * @param m03 Component in column 0, row 3 position (index 3) + * @param m10 Component in column 1, row 0 position (index 4) + * @param m11 Component in column 1, row 1 position (index 5) + * @param m12 Component in column 1, row 2 position (index 6) + * @param m13 Component in column 1, row 3 position (index 7) + * @param m20 Component in column 2, row 0 position (index 8) + * @param m21 Component in column 2, row 1 position (index 9) + * @param m22 Component in column 2, row 2 position (index 10) + * @param m23 Component in column 2, row 3 position (index 11) + * @param m30 Component in column 3, row 0 position (index 12) + * @param m31 Component in column 3, row 1 position (index 13) + * @param m32 Component in column 3, row 2 position (index 14) + * @param m33 Component in column 3, row 3 position (index 15) + */ + constructor ( + m00?: number, m01?: number, m02?: number, m03?: number, + m04?: number, m05?: number, m06?: number, m07?: number, + m08?: number, m09?: number, m10?: number, m11?: number, + m12?: number, m13?: number, m14?: number, m15?: number); + + constructor ( + m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, + m04 = 0, m05 = 1, m06 = 0, m07 = 0, + m08 = 0, m09 = 0, m10 = 1, m11 = 0, + m12 = 0, m13 = 0, m14 = 0, m15 = 1) { + super(); + if (typeof m00 === 'object') { + this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; this.m04 = m00.m04; + this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; + this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; this.m12 = m00.m12; + this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; this.m00 = m00.m00; + } else { + this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; + this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; + this.m09 = m09; this.m10 = m10; this.m11 = m11; this.m12 = m12; + this.m13 = m13; this.m14 = m14; this.m15 = m15; this.m00 = m00; + } + } + + /** + * !#en clone a Mat4 object + * !#zh 克隆一个 Mat4 对象 + * + * @return + */ + public clone () { + const t = this; + return new Mat4( + t.m00, t.m01, t.m02, t.m03, + t.m04, t.m05, t.m06, t.m07, + t.m08, t.m09, t.m10, t.m11, + t.m12, t.m13, t.m14, t.m15); + } + + /** + * !#en Sets the matrix with another one's value + * !#zh 用另一个矩阵设置这个矩阵的值。 + * + * @param srcObj + * @return returns this + * @chainable + */ + public set (other: Mat4) { + const t = this; + t.m00 = other.m00; + t.m01 = other.m01; + t.m02 = other.m02; + t.m03 = other.m03; + t.m04 = other.m04; + t.m05 = other.m05; + t.m06 = other.m06; + t.m07 = other.m07; + t.m08 = other.m08; + t.m09 = other.m09; + t.m10 = other.m10; + t.m11 = other.m11; + t.m12 = other.m12; + t.m13 = other.m13; + t.m14 = other.m14; + t.m15 = other.m15; + return this; + } + + /** + * !#en Check whether two matrix equal + * !#zh 当前的矩阵是否与指定的矩阵相等。 + * + * @param other + * @return + */ + public equals (other: Mat4) { + return mat4.exactEquals(this, other); + } + + /** + * !#en Check whether two matrix equal with default degree of variance. + * !#zh + * 近似判断两个矩阵是否相等。
+ * 判断 2 个矩阵是否在默认误差范围之内,如果在则返回 true,反之则返回 false。 + * + * @param other + * @return + */ + public fuzzyEquals (other: Mat4) { + return mat4.equals(this, other); + } + + /** + * !#en Transform to string with matrix informations + * !#zh 转换为方便阅读的字符串。 + * + * @return + */ + public toString () { + const t = this; + return '[\n' + + t.m00 + ', ' + t.m01 + ', ' + t.m02 + ', ' + t.m03 + ',\n' + + t.m04 + ', ' + t.m05 + ', ' + t.m06 + ', ' + t.m07 + ',\n' + + t.m08 + ', ' + t.m09 + ', ' + t.m10 + ', ' + t.m11 + ',\n' + + t.m12 + ', ' + t.m13 + ', ' + t.m14 + ', ' + t.m15 + '\n' + + ']' + ; + } + + /** + * Set the matrix to the identity matrix + * + * @return self + * @chainable + */ + public identity () { + return mat4.identity(this); + } + + /** + * Transpose the values of a mat4 + * + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public transpose (out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.transpose(out, this); + } + + /** + * Inverts a mat4 + * + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public invert (out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.invert(out, this); + } + + /** + * Calculates the adjugate of a mat4 + * + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public adjoint (out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.adjoint(out, this); + } + + /** + * Calculates the determinant of a mat4 + * + * @return determinant of a + */ + public determinant () { + return mat4.determinant(this); + } + + /** + * Adds two Mat4 + * + * @param other the second operand + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public add (other: Mat4, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.add(out, this, other); + } + + /** + * Subtracts the current matrix with another one + * + * @param other the second operand + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public sub (other: Mat4, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.subtract(out, this, other); + } + + /** + * Subtracts the current matrix with another one + * + * @param other the second operand + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public mul (other: Mat4, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.multiply(out, this, other); + } + + /** + * Multiply each element of the matrix by a scalar. + * + * @param number amount to scale the matrix's elements by + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public mulScalar (num: number, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.scale(out, this, num); + } + + /** + * Translate a mat4 by the given vector + * + * @param v vector to translate by + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public translate (v: Vec3, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.translate(out, this, v); + } + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param v vector to scale by + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public scale (v: Vec3, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.scale(out, this, v); + } + + /** + * Rotates a mat4 by the given angle around the given axis + * + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @param [out] The receiving matrix, can be `this`; if absent, a new matrix would be created. + * @return out + */ + public rotate (rad: number, axis: Vec3, out?: Mat4) { + out = out || new cc.Mat4(); + return mat4.rotate(out, this, rad, axis); + } + + /** + * Returns the translation vector component of a transformation matrix. + * + * @param {Vec3} out Vector to receive translation component, if not provided, a new vec3 will be created + * @return out + */ + public getTranslation (out?: Mat4) { + out = out || new cc.Vec3(); + return mat4.getTranslation(out, this); + } + + /** + * Returns the scale factor component of a transformation matrix + * + * @param out Vector to receive scale component, if not provided, a new vec3 will be created + * @return out + */ + public getScale (out: Vec3) { + out = out || new cc.Vec3(); + return mat4.getScaling(out, this); + } + + /** + * Returns the rotation factor component of a transformation matrix + * + * @param out Vector to receive rotation component, if not provided, a new quaternion object will be created + * @return out + */ + public getRotation (out: Quat) { + out = out || new Quat(); + return mat4.getRotation(out, this); + } + + /** + * Restore the matrix values from a quaternion rotation, vector translation and vector scale + * + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @return the current mat4 object + * @chainable + */ + public fromRTS (q: Quat, v: Vec3, s: Vec3) { + return mat4.fromRTS(this, q, v, s); + } + + /** + * Restore the matrix values from a quaternion rotation + * + * @param q Rotation quaternion + * @return the current mat4 object + * @chainable + */ + public fromQuat (quat: Quat) { + return mat4.fromQuat(this, quat); + } +} + +CCClass.fastDefine('cc.Mat4', Mat4, { + m00: 1, m01: 0, m02: 0, m03: 0, + m04: 0, m05: 1, m06: 0, m07: 0, + m08: 0, m09: 0, m10: 1, m11: 0, + m12: 0, m13: 0, m14: 0, m15: 1, +}); +cc.Mat4 = Mat4; + +/** + * !#en The convenience method to create a new {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}} 对象。 + * + * @param other + * @return + */ +function m4 (other: Mat4): Mat4; + +/** + * !#en The convenience method to create a new {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}}. + * !#zh 通过该简便的函数进行创建 {{#crossLink "Mat4"}}cc.Mat4{{/crossLink}} 对象。 + * + * @param m00 Component in column 0, row 0 position (index 0) + * @param m01 Component in column 0, row 1 position (index 1) + * @param m02 Component in column 0, row 2 position (index 2) + * @param m03 Component in column 0, row 3 position (index 3) + * @param m10 Component in column 1, row 0 position (index 4) + * @param m11 Component in column 1, row 1 position (index 5) + * @param m12 Component in column 1, row 2 position (index 6) + * @param m13 Component in column 1, row 3 position (index 7) + * @param m20 Component in column 2, row 0 position (index 8) + * @param m21 Component in column 2, row 1 position (index 9) + * @param m22 Component in column 2, row 2 position (index 10) + * @param m23 Component in column 2, row 3 position (index 11) + * @param m30 Component in column 3, row 0 position (index 12) + * @param m31 Component in column 3, row 1 position (index 13) + * @param m32 Component in column 3, row 2 position (index 14) + * @param m33 Component in column 3, row 3 position (index 15) + * @return + */ +function m4 ( + m00?: number, m01?: number, m02?: number, m03?: number, + m10?: number, m11?: number, m12?: number, m13?: number, + m20?: number, m21?: number, m22?: number, m23?: number, + m30?: number, m31?: number, m32?: number, m33?: number): Mat4; + +function m4 ( + m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, + m10 = 0, m11 = 1, m12 = 0, m13 = 0, + m20 = 0, m21 = 0, m22 = 1, m23 = 0, + m30 = 0, m31 = 0, m32 = 0, m33 = 1) { + return new Mat4(m00 as any, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); +} + +export { m4 as mat4 }; + +cc.mat4 = m4; diff --git a/cocos/gfx/vertex-format-sample.ts b/cocos/gfx/vertex-format-sample.ts new file mode 100644 index 0000000000..78483b64fa --- /dev/null +++ b/cocos/gfx/vertex-format-sample.ts @@ -0,0 +1,20 @@ +import { GFXAttributeName, GFXFormat } from './define'; + +const vfmt = [ + { + name: GFXAttributeName.ATTR_POSITION, + format: GFXFormat.RGB32F, + }, + { + name: GFXAttributeName.ATTR_COLOR, + format: GFXFormat.RGBA8UI, + }, + { + name: GFXAttributeName.ATTR_TEX_COORD, + format: GFXFormat.RG32F, + }, +]; + +export { + vfmt, +}; diff --git a/cocos/renderer/ui/renderData.ts b/cocos/renderer/ui/renderData.ts index 0312e598e5..589e6642cc 100644 --- a/cocos/renderer/ui/renderData.ts +++ b/cocos/renderer/ui/renderData.ts @@ -79,7 +79,7 @@ export class RenderData extends BaseRenderData { } } -const _dataPool = new RecyclePool(128, () => { +const _dataPool = new RecyclePool(() => { return { x: 0.0, y: 0.0, @@ -88,8 +88,8 @@ const _dataPool = new RecyclePool(128, () => { v: 0.0, color: 0, }; -}); +}, 128); -const _pool = new RecyclePool(32, () => { +const _pool = new RecyclePool( () => { return new RenderData(); -}); +}, 32); diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 11d35a655d..53556fcf88 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -1,7 +1,9 @@ -// import { vfmt3D } from '../../2d/renderer/webgl/vertex-format'; import RecyclePool from '../../3d/memop/recycle-pool'; import { CachedArray } from '../../core/memop/cached-array'; +import { MeshBuffer } from '../../3d/ui/mesh-buffer'; +import { Material } from '../../3d/assets/material'; +import { SpriteFrame } from '../../assets/CCSpriteFrame'; import { Root } from '../../core/root'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXCommandBufferType, IGFXRect } from '../../gfx/define'; @@ -9,7 +11,15 @@ import { GFXDevice } from '../../gfx/device'; import { GFXFramebuffer } from '../../gfx/framebuffer'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; +import { CanvasComponent } from '../../3d/ui/components/canvas-component'; +import { LabelComponent } from '../../3d/ui/components/label-component'; +import { SpriteComponent } from '../../3d/ui/components/sprite-component'; import { UIBatchModel } from './ui-batch-model'; +import { vfmt } from '../../gfx/vertex-format-sample'; +// import { GFXBuffer } from '../../gfx/buffer'; +// import { RenderComponent } from '../../3d/ui/components/ui-render-component'; + +// import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; export interface IUIRenderItem { camera: Camera; @@ -18,21 +28,24 @@ export interface IUIRenderItem { } export class UI { - // private _buffer: MeshBuffer | null = new MeshBuffer(this, vfmt3D); + private _screens: CanvasComponent[] = []; + private _buffer: MeshBuffer | null = null; + private _currScreen: CanvasComponent | null = null; + private _currMaterail: Material | null = null; + private _currSpriteFrame: SpriteFrame | null = null; + private _currUserKey = 0; + private _dummyNode: Node | null = null; private _batchedModels: UIBatchModel[] = []; - private _iaPool: RecyclePool | null = new RecyclePool(16, () => { - // return this._root.device.createInputAssembler({ - - // }); - }); - private _modelPool: RecyclePool = new RecyclePool(16, () => { - return this._scene.createModel(UIBatchModel); - }); + private _iaPool: RecyclePool | null = null; + private _modelPool: RecyclePool | null = null; private _device: GFXDevice; private _cmdBuff: GFXCommandBuffer | null = null; private _renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; private _scene: RenderScene; private _items: CachedArray; + // private _vb: GFXBuffer | null = null; + // private _ib: GFXBuffer | null = null; + // private _renderComps: RenderComponent[] = []; constructor (private _root: Root) { this._device = _root.device; @@ -41,6 +54,17 @@ export class UI { }); this._items = new CachedArray(64); + this._buffer = new MeshBuffer(this._root.device, vfmt); + this._modelPool = new RecyclePool(() => { + return this._scene.createModel(UIBatchModel); + }, 16); + // this._iaPool = new RecyclePool(() => { + // return this._root.device.createInputAssembler({ + // attributes: vfmt, + // vertexBuffers: [this._buffer._vb], + // indexBuffer: this._buffer._ib, + // }); + // }, 16); } public initialize () { @@ -63,21 +87,173 @@ export class UI { } public addScreen (comp) { + this._screens.push(comp); } public removeScreen (comp) { + const idx = this._screens.indexOf(comp); + if (idx !== -1) { + this._screens.splice(idx, 1); + } } public update (dt: number) { this._items.clear(); // TODO: Merge batch here. + this._renderScreens(); this.render(); } - private _emit (): UIBatchModel[] { - return this._batchedModels; + public _walk (node, fn1, fn2, level = 0) { + level += 1; + const len = node.children.length; + + for (let i = 0; i < len; ++i) { + const child = node.children[i]; + const continueWalk = fn1(child, node, level); + + if (continueWalk === false) { + fn2(child, node, level); + break; + } + + this._walk(child, fn1, fn2, level); + // fn2(child, node, level); + } + } + + // public flush () { + // const material = this._currMaterail; + // const buffer = this._buffer; + // const indiceStart = buffer!.indiceStart; + // const indiceOffset = buffer!.indiceOffset; + // const indiceCount = indiceOffset - indiceStart; + // if (!material || indiceCount <= 0) { + // return; + // } + + // // Generate ia + // const ia = this._iaPool.add(); + // ia._vertexBuffer = buffer!._vb; + // ia._indexBuffer = buffer!._ib; + // ia._start = indiceStart; + // ia._count = indiceCount; + + // // Check stencil state and modify pass + // // TODO: Matching new structure + // // _setStencil( + // // material, + // // false, + // // gfx.DS_FUNC_ALWAYS, + // // 0, + // // 0, + // // gfx.STENCIL_OP_KEEP, + // // gfx.STENCIL_OP_KEEP, + // // gfx.STENCIL_OP_KEEP, + // // 0, + // // ); + + // // Generate model + // const model = this._modelPool.add(); + // this._batchedModels.push(model); + // model.setNode(this._dummyNode); + // // model.setEffect(material.effect); + // model.setInputAssembler(ia); + // model._viewID = this._currScreen!.visibility; + // model.setUserKey(this._currUserKey++); + + // // const item = this._UIRenderItemPool.add(); + // // item.model = model; + // // item.camera = this._currScreen!.camera; + // // cc.director._renderSystem._scene.addModel(model); + + // // buffer!.byteStart = buffer!.byteOffset; + // // buffer!.indiceStart = buffer!.indiceOffset; + // // buffer!.vertexStart = buffer!.vertexOffset; + // } + + private _renderScreens () { + // this._renderComps.length = 0; + for (const screen of this._screens) { + if (!screen.enabledInHierarchy) { + continue; + } + this._currScreen = screen; + this._buffer!.reset(); + // const view = screen._view; + // // let canvasWidth = screen.designResolution.width; + // // let canvasHeight = screen.designResolution.height; + // screen.node.getWorldRT(view._matView); + // mat4.invert(view._matView, view._matView); + // // let aspect = canvasWidth / canvasHeight; + // const aspect = cc.game.canvas.width / cc.game.canvas.height; + // // let orthoHeight = canvasHeight / 2; + // const orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2; + // const x = orthoHeight * aspect; + // const y = orthoHeight; + // mat4.ortho(view._matProj, + // -x, x, -y, y, 0, 4096, + // ); + + // // mat4.ortho(view._matProj, 0, canvasWidth, 0, canvasHeight, -100, 100); + // mat4.mul(view._matViewProj, view._matProj, view._matView); + // // mat4.copy(view._matViewProj, view._matProj); + // mat4.invert(view._matInvViewProj, view._matViewProj); + // view._rect.x = view._rect.y = 0; + // // view._rect.w = cc.game._renderer._device._gl.canvas.width; + // // view._rect.h = cc.game._renderer._device._gl.canvas.height; + // view._rect.w = cc.game.canvas.width; + // view._rect.h = cc.game.canvas.height; + + this._walk(screen.node, (c) => { + const image = c.getComponent(SpriteComponent); + if (image && image.enabledInHierarchy) { + this._commitComp(image); + // this._renderComps.push(image); + } + + const label = c.getComponent(LabelComponent); + if (label && label.enabledInHierarchy) { + this._commitComp(label); + // this._renderComps.push(label); + } + }, null); + + // this.flush(); + + this._emit( + new Float32Array(this._buffer!.vData!.buffer, 0, this._buffer!.byteOffset >> 2), + new Uint16Array(this._buffer!.iData!.buffer, 0, this._buffer!.indiceOffset), + ); + } + } + + private _commitComp (comp) { + // if ((this._currMaterail && this._currMaterail.hash !== comp.material.hash) + // || this._currSpriteFrame !== comp.spriteFrame) { + // this.flush(); + // this._dummyNode = comp.node; + // this._currMaterail = comp.material; + // this._currSpriteFrame = comp.spriteFrame; + // } + comp.updateRenderData(this._buffer); + } + + private _reset () { + // for (const model of this._batchedModels) { + // cc.director._renderSystem._scene.removeModel(model); + // } + + this._modelPool.reset(); + // this._iaPool.reset(); + this._batchedModels.length = 0; + } + + private _emit (vertecies: Float32Array, indecies: Uint16Array) { + // return this._batchedModels; + } private render () { @@ -108,3 +284,16 @@ export class UI { } } } + +// function _setStencil (mat, enabled, func, ref, mask, failOp, zFailOp, zPassOp, writeMask) { +// const tech = mat.effect.getTechnique(0); +// for (let i = 0; i < tech.passes.length; ++i) { +// const pass = tech.passes[i]; +// pass.setStencilFront( +// enabled, func, ref, mask, failOp, zFailOp, zPassOp, writeMask, +// ); +// pass.setStencilBack( +// enabled, func, ref, mask, failOp, zFailOp, zPassOp, writeMask, +// ); +// } +// } diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index b9125e0327..0ce432a035 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -2,6 +2,7 @@ import { ccclass, mixins, property } from '../core/data/class-decorator'; import { EventTarget } from '../core/event'; import { Enum, Mat4, Quat, Vec3 } from '../core/value-types'; import { mat4, quat, vec3 } from '../core/vmath'; +import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component'; import { BaseNode } from './base-node'; import { Layers } from './layers'; @@ -31,6 +32,8 @@ class Node extends BaseNode { public static isNode (obj: object) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); } + public uiTransfromComp: UITransformComponent | null = null; + // local transform @property protected _lpos = new Vec3(); @@ -57,6 +60,9 @@ class Node extends BaseNode { protected _matDirty = false; protected _eulerDirty = false; + protected _bubblingListeners: EventTarget|null = null; + protected _capturingListeners: EventTarget | null = null; + @property({ type: Vec3, }) @@ -79,9 +85,72 @@ class Node extends BaseNode { return this._layer; } + get width () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.width; + } + + set width (value) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.width = value; + } + + get height () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.height; + } + + set height (value) { + if (!this.uiTransfromComp) { + return; + } + this.uiTransfromComp.height = value; + } + + get anchorX () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.anchorX; + } + + set anchorX (value) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.anchorX = value; + } + + get anchorY () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.anchorY; + } + + set anchorY (value) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.anchorY = value; + } + constructor (name: string) { super(name); - EventTarget.call(this); + // EventTarget.call(this); } // =============================== @@ -646,6 +715,355 @@ class Node extends BaseNode { } return mat4.fromRT(out, this._rot, this._pos); } + + public getAnchorPoint () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.anchorPoint; + } + + public setAnchorPoint (point: Vec2, y: number) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.setAnchorPoint(point, y); + } + + public getContentSize () { + if (!this.uiTransfromComp) { + return; + } + + return this.uiTransfromComp.contentSize; + } + + public setContentSize (size: Size, height: number = 0) { + if (!this.uiTransfromComp) { + return; + } + + this.uiTransfromComp.setContentSize(size.height); + } + + // EVENT TARGET + + public _checknSetupSysEvent (type) { + let newAdded = false; + let forDispatch = false; + if (_touchEvents.indexOf(type) !== -1) { + if (!this._touchListener) { + this._touchListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + owner: this, + mask: _searchMaskInParent(this), + onTouchBegan: _touchStartHandler, + onTouchMoved: _touchMoveHandler, + onTouchEnded: _touchEndHandler, + onTouchCancelled: _touchCancelHandler, + }); + eventManager.addListener(this._touchListener, this); + newAdded = true; + } + forDispatch = true; + } else if (_mouseEvents.indexOf(type) !== -1) { + if (!this._mouseListener) { + this._mouseListener = cc.EventListener.create({ + event: cc.EventListener.MOUSE, + _previousIn: false, + owner: this, + mask: _searchMaskInParent(this), + onMouseDown: _mouseDownHandler, + onMouseMove: _mouseMoveHandler, + onMouseUp: _mouseUpHandler, + onMouseScroll: _mouseWheelHandler, + }); + eventManager.addListener(this._mouseListener, this); + newAdded = true; + } + forDispatch = true; + } + if (newAdded && !this._activeInHierarchy) { + cc.director.getScheduler().schedule(function () { + if (!this._activeInHierarchy) { + eventManager.pauseTarget(this); + } + }, this, 0, 0, 0, false); + } + return forDispatch; + } + + /** + * !#en + * Register a callback of a specific event type on Node.
+ * Use this method to register touch or mouse event permit propagation based on scene graph,
+ * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
+ * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
+ * 2. At target phase: dispatch to the listeners of the real target
+ * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
+ * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
+ * It's the recommended way to register touch/mouse event for Node,
+ * please do not use cc.eventManager directly for Node.
+ * You can also register custom event and use `emit` to trigger custom event on Node.
+ * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
+ * You can also pass event callback parameters with `emit` by passing parameters after `type`. + * !#zh + * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
+ * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
+ * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
+ * 2. 目标阶段:派发给目标节点的监听器。
+ * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
+ * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
+ * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
+ * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
+ * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表 + * @method on + * @param {String|Node.EventType} type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event|any} [callback.event] event or first argument when emit + * @param {any} [callback.arg2] arg2 + * @param {any} [callback.arg3] arg3 + * @param {any} [callback.arg4] arg4 + * @param {any} [callback.arg5] arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase. + * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. + * @typescript + * on(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. + * node.on(cc.Node.EventType.TOUCH_START, callback, this); + * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this); + * node.on(cc.Node.EventType.TOUCH_END, callback, this); + * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this); + * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); + */ + public on (type, callback, target, useCapture) { + const forDispatch = this._checknSetupSysEvent(type); + if (forDispatch) { + return this._onDispatch(type, callback, target, useCapture); + } else { + // switch (type) { + // case EventType.POSITION_CHANGED: + // this._eventMask |= POSITION_ON; + // break; + // case EventType.SCALE_CHANGED: + // this._eventMask |= SCALE_ON; + // break; + // case EventType.ROTATION_CHANGED: + // this._eventMask |= ROTATION_ON; + // break; + // case EventType.SIZE_CHANGED: + // this._eventMask |= SIZE_ON; + // break; + // case EventType.ANCHOR_CHANGED: + // this._eventMask |= ANCHOR_ON; + // break; + // } + if (!this._bubblingListeners) { + this._bubblingListeners = new EventTarget(); + } + return this._bubblingListeners.on(type, callback, target); + } + } + + // /** + // * !#en + // * Register an callback of a specific event type on the Node, + // * the callback will remove itself after the first time it is triggered. + // * !#zh + // * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。 + // * + // * @method once + // * @param {String} type - A string representing the event type to listen for. + // * @param {Function} callback - The callback that will be invoked when the event is dispatched. + // * The callback is ignored if it is a duplicate (the callbacks are unique). + // * @param {Event|any} [callback.event] event or first argument when emit + // * @param {any} [callback.arg2] arg2 + // * @param {any} [callback.arg3] arg3 + // * @param {any} [callback.arg4] arg4 + // * @param {any} [callback.arg5] arg5 + // * @param {Object} [target] - The target (this object) to invoke the callback, can be null + // * @typescript + // * once(type: string, callback: T, target?: any, useCapture?: boolean): T + // * @example + // * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback); + // */ + // once(type, callback, target, useCapture) { + // let forDispatch = this._checknSetupSysEvent(type); + // let eventType_hasOnceListener = '__ONCE_FLAG:' + type; + + // let listeners = null; + // if (forDispatch && useCapture) { + // listeners = this._capturingListeners = this._capturingListeners || new EventTarget(); + // } + // else { + // listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget(); + // } + + // let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target); + // if (!hasOnceListener) { + // let self = this; + // let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { + // self.off(type, onceWrapper, target); + // listeners.remove(eventType_hasOnceListener, callback, target); + // callback.call(this, arg1, arg2, arg3, arg4, arg5); + // }; + // this.on(type, onceWrapper, target); + // listeners.add(eventType_hasOnceListener, callback, target); + // } + // } + + public _onDispatch (type, callback, target, useCapture) { + // Accept also patameters like: (type, callback, useCapture) + if (typeof target === 'boolean') { + useCapture = target; + target = undefined; + } else { useCapture = !!useCapture; } + if (!callback) { + cc.errorID(6800); + return; + } + + let listeners = null; + if (useCapture) { + listeners = this._capturingListeners = this._capturingListeners || new EventTarget(); + } else { + listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget(); + } + + if (!listeners.hasEventListener(type, callback, target)) { + listeners.add(type, callback, target); + + if (target && target.__eventTargets) { + target.__eventTargets.push(this); + } + } + + return callback; + } + + /** + * !#en + * Removes the callback previously registered with the same type, callback, target and or useCapture. + * This method is merely an alias to removeEventListener. + * !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。 + * @method off + * @param {String} type - A string representing the event type being removed. + * @param {Function} [callback] - The callback to remove. + * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase. + * @example + * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this); + * node.off(cc.Node.EventType.TOUCH_START, callback, this.node); + * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this); + */ + public off (type, callback, target, useCapture) { + const touchEvent = _touchEvents.indexOf(type) !== -1; + const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1; + if (touchEvent || mouseEvent) { + this._offDispatch(type, callback, target, useCapture); + + if (touchEvent) { + if (this._touchListener && !_checkListeners(this, _touchEvents)) { + eventManager.removeListener(this._touchListener); + this._touchListener = null; + } + } else if (mouseEvent) { + if (this._mouseListener && !_checkListeners(this, _mouseEvents)) { + eventManager.removeListener(this._mouseListener); + this._mouseListener = null; + } + } + } else if (this._bubblingListeners) { + this._bubblingListeners.off(type, callback, target); + + const hasListeners = this._bubblingListeners.hasEventListener(type); + // All listener removed + // if (!hasListeners) { + // switch (type) { + // case EventType.POSITION_CHANGED: + // this._eventMask &= ~POSITION_ON; + // break; + // case EventType.SCALE_CHANGED: + // this._eventMask &= ~SCALE_ON; + // break; + // case EventType.ROTATION_CHANGED: + // this._eventMask &= ~ROTATION_ON; + // break; + // case EventType.SIZE_CHANGED: + // this._eventMask &= ~SIZE_ON; + // break; + // case EventType.ANCHOR_CHANGED: + // this._eventMask &= ~ANCHOR_ON; + // break; + // } + // } + } + } + + public _offDispatch (type, callback, target, useCapture) { + // Accept also patameters like: (type, callback, useCapture) + if (typeof target === 'boolean') { + useCapture = target; + target = undefined; + } else { useCapture = !!useCapture; } + if (!callback) { + this._capturingListeners && this._capturingListeners.removeAll(type); + this._bubblingListeners && this._bubblingListeners.removeAll(type); + } else { + const listeners = useCapture ? this._capturingListeners : this._bubblingListeners; + if (listeners) { + listeners.remove(type, callback, target); + + if (target && target.__eventTargets) { + js.array.fastRemove(target.__eventTargets, this); + } + } + + } + } + + /** + * !#en + * Trigger an event directly with the event name and necessary arguments. + * !#zh + * 通过事件名发送自定义事件 + * + * @method emit + * @param {String} type - event type + * @param {*} [arg1] - First argument in callback + * @param {*} [arg2] - Second argument in callback + * @param {*} [arg3] - Third argument in callback + * @param {*} [arg4] - Fourth argument in callback + * @param {*} [arg5] - Fifth argument in callback + * @example + * + * eventTarget.emit('fire', event); + * eventTarget.emit('fire', message, emitter); + */ + public emit (type, ...args: any[]) { + if (this._bubblingListeners) { + this._bubblingListeners.emit(type, ...args); + } + } + + /** + * !#en + * Dispatches an event into the event flow. + * The event target is the EventTarget object upon which the dispatchEvent() method is called. + * !#zh 分发事件到事件流中。 + * + * @method dispatchEvent + * @param {Event} event - The Event object that is dispatched into the event flow + */ + public dispatchEvent (event) { + _doDispatchEvent(this, event); + _cachedArray.length = 0; + } } if (CC_EDITOR) {