diff --git a/cocos/3d/assets/texture-cube.js b/cocos/3d/assets/texture-cube.js
deleted file mode 100644
index 8b22687e16..0000000000
--- a/cocos/3d/assets/texture-cube.js
+++ /dev/null
@@ -1,285 +0,0 @@
-/****************************************************************************
- 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 GFXTextureCube from '../../renderer/gfx/texture-cube';
-import TextureBase from '../../assets/texture-base';
-import { ccclass, property } from '../../core/data/class-decorator';
-import ImageAsset from '../../assets/image-asset';
-
-/**
- * @typedef {import("../../assets/texture-2d")} Texture2D
- * @typedef {import("../../assets/texture-base").ImageSource} ImageSource
- * @typedef {import("../../assets/texture-base").TextureUpdateOpts} TextureUpdateOpts
- * @typedef {import("../../assets/texture-base").HTMLImageSource} HTMLImageSource
- * @typedef {{front: HTMLImageSource, back: HTMLImageSource, left: HTMLImageSource, right: HTMLImageSource, top: HTMLImageSource, bottom: HTMLImageSource}} MipmapHTMLImageSource
- * @typedef {{front: ImageAsset, back: ImageAsset, left: ImageAsset, right: ImageAsset, top: ImageAsset, bottom: ImageAsset}} Mipmap
- */
-
-/**
- * @enum {number}
- */
-const FaceIndex = cc.Enum({
- right: 0,
- left: 1,
- top: 2,
- bottom: 3,
- front: 4,
- back: 5
-});
-
-@ccclass('cc.TextureCube')
-export default class TextureCube extends TextureBase {
- /**
- * @type {Mipmap[]}
- */
- @property
- _mipmaps = [];
-
- constructor() {
- super();
-
- /**
- * @type {GFXTextureCube}
- */
- this._texture = null;
- }
-
- /**
- * Gets the mipmap images.
- * Note that the result do not contains the auto generated mipmaps.
- * @type {Mipmap[]}
- */
- get mipmaps() {
- return this._mipmaps;
- }
-
- /**
- * Sets the mipmaps images.
- * @type {Mipmap[]}
- */
- set mipmaps(value) {
- this._setMipmaps(value);
- }
-
- /**
- * Gets the mipmap image at level 0.
- * @type {Mipmap}
- */
- get image() {
- return this._mipmaps.length === 0 ? null : this._mipmaps[0];
- }
-
- /**
- * Sets the mipmap images as a single mipmap image.
- * @type {Mipmap}
- */
- set image(value) {
- this.mipmaps = [value];
- }
-
- /**
- * Gets the underlying texture object.
- */
- getImpl () {
- return this._texture;
- }
-
- /**
- * !#en
- * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
- * After destroy, this object is not usable any more.
- * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
- * !#zh
- * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
- * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
- * @method destroy
- * @return {Boolean} inherit from the CCObject
- */
- destroy () {
- this.releaseTexture();
- // TODO cc.textureUtil ?
- // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
- return super.destroy();
- }
-
- /**
- * !#en
- * Release texture, please use destroy instead.
- * !#zh 释放纹理,请使用 destroy 替代。
- * @method releaseTexture
- * @deprecated since v2.0
- */
- releaseTexture () {
- this._setMipmaps([]);
- this._texture && this._texture.destroy();
- }
-
- /**
- * Sets the _mipmaps to specified value, and updates the width and height accordingly.
- * If available, synchronize the mipmap data to underlying texture.
- * @param {Mipmap[]} mipmaps
- */
- _setMipmaps(mipmaps) {
- this._mipmaps = mipmaps;
- if (mipmaps.length === 0) {
- super.update({
- width: 0,
- height: 0
- });
- } else {
- super.update({
- width: this._mipmaps[0].front.width,
- height: this._mipmaps[0].front.height,
- format: this._mipmaps[0].front._format
- });
- }
-
- let counter = 0;
- const inc = () => {
- ++counter;
- if (counter === this._mipmaps.length * 6) {
- this._updateMipmaps(this._mipmaps.map(mipmap => TextureCube._toMipmapArray(mipmap)));
- }
- };
- mipmaps.forEach(mipmap => {
- TextureCube._forEachFace(mipmap, face => {
- if (face.loaded) {
- inc();
- } else {
- face.addEventListener("load", () => inc());
- }
- });
- });
- }
-
- /**
- * Updates mipmaps of the underlying texture.
- * @param {ImageSource[][]} mipmapSources
- */
- _updateMipmaps(mipmapSources) {
- const opts = this._getOpts();
- opts.images = mipmapSources;
- if (!this._texture) {
- this._texture = new GFXTextureCube(cc.game._renderContext, opts);
- } else {
- this._texture.update(opts);
- }
- }
-
- /**
- * Update texture options, not available in Canvas render mode.
- * image, format, premultiplyAlpha can not be updated in native.
- * @method update
- */
- update (options) {
- if (!options) return;
-
- super.update(options);
-
- // TODO: options.image
-
- if (this._texture) {
- this._texture.update(options);
- }
- }
-
- /**
- * @param {Mipmap} mipmap
- * @return {ImageSource[]}
- */
- static _toMipmapArray(mipmap) {
- /** @type {ImageSource[]} */
- const result = new Array();
- result[FaceIndex.front] = mipmap.front.data;
- result[FaceIndex.back] = mipmap.back.data;
- result[FaceIndex.left] = mipmap.left.data;
- result[FaceIndex.right] = mipmap.right.data;
- result[FaceIndex.top] = mipmap.top.data;
- result[FaceIndex.bottom] = mipmap.bottom.data;
- return result;
- }
-
- /**
- * @param {Mipmap} mipmap
- * @param {(face: ImageAsset) => void} callback
- */
- static _forEachFace(mipmap, callback) {
- for (let face in mipmap) {
- callback(mipmap[face]);
- }
- }
-
- /**
- * @param {Texture2D[]} textures
- */
- static fromTexture2DArray(textures, out) {
- let res = [], mips = textures.length / 6;
- for (let i = 0; i < mips; i++) {
- res.push(textures.splice(0, 6).reduce((acc, img, i) => {
- acc[FaceIndex[i]] = img.image;
- return acc;
- }, {}));
- }
- if (!out) out = new TextureCube();
- out.mipmaps = res;
- return out;
- }
-
- _serialize() {
- return {
- base: super._serialize(),
- mipmaps: this._mipmaps.map(mipmap => {return {
- front: mipmap.front._uuid,
- back: mipmap.back._uuid,
- left: mipmap.left._uuid,
- right: mipmap.right._uuid,
- top: mipmap.top._uuid,
- bottom: mipmap.bottom._uuid,
- };})
- };
- }
-
- _deserialize (data, handle) {
- super._deserialize(data.base);
-
- this._mipmaps = new Array(data.mipmaps.length);
- this._mipmaps.fill({});
- for (let i = 0; i < data.mipmaps.length; ++i) {
- const mipmap = data.mipmaps[i];
- handle.result.push(this._mipmaps[i], `front`, mipmap.front);
- handle.result.push(this._mipmaps[i], `back`, mipmap.back);
- handle.result.push(this._mipmaps[i], `left`, mipmap.left);
- handle.result.push(this._mipmaps[i], `right`, mipmap.right);
- handle.result.push(this._mipmaps[i], `top`, mipmap.top);
- handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom);
- }
- }
-
- onLoaded() {
- this.mipmaps = this._mipmaps;
- }
-}
-
-cc.TextureCube = TextureCube;
diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts
new file mode 100644
index 0000000000..9a9ce7ccb3
--- /dev/null
+++ b/cocos/3d/assets/texture-cube.ts
@@ -0,0 +1,248 @@
+/****************************************************************************
+ 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 { Texture2D } from '../../assets';
+import ImageAsset from '../../assets/image-asset';
+import TextureBase from '../../assets/texture-base';
+import { ccclass, property } from '../../core/data/class-decorator';
+import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define';
+
+interface ITextureCubeMipmap {
+ front: ImageAsset;
+ back: ImageAsset;
+ left: ImageAsset;
+ right: ImageAsset;
+ top: ImageAsset;
+ bottom: ImageAsset;
+}
+
+@ccclass('cc.TextureCube')
+export default class TextureCube extends TextureBase {
+ /**
+ * Gets the mipmap images.
+ * Note that the result do not contains the auto generated mipmaps.
+ */
+ get mipmaps () {
+ return this._mipmaps;
+ }
+
+ /**
+ * Sets the mipmaps images.
+ */
+ set mipmaps (value) {
+ this._mipmaps = value;
+ this._recreateTexture();
+ }
+
+ /**
+ * Gets the mipmap image at level 0.
+ */
+ get image () {
+ return this._mipmaps.length === 0 ? null : this._mipmaps[0];
+ }
+
+ /**
+ * Sets the mipmap images as a single mipmap image.
+ */
+ set image (value) {
+ this.mipmaps = value ? [value] : [];
+ }
+
+ /**
+ * @param textures
+ * @deprecated Manually assign to mipmaps property instead.
+ */
+ public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) {
+ const mipmaps: ITextureCubeMipmap[] = [];
+ const nMipmaps = textures.length / 6;
+ for (let i = 0; i < nMipmaps; i++) {
+ const x = i * 6;
+ mipmaps.push({
+ front: textures[x + FaceIndex.front].image!,
+ back: textures[x + FaceIndex.back].image!,
+ left: textures[x + FaceIndex.left].image!,
+ right: textures[x + FaceIndex.right].image!,
+ top: textures[x + FaceIndex.top].image!,
+ bottom: textures[x + FaceIndex.bottom].image!,
+ });
+ }
+ if (!out) { out = new TextureCube(); }
+ out.mipmaps = mipmaps;
+ return out;
+ }
+
+ @property
+ public _mipmaps: ITextureCubeMipmap[] = [];
+
+ constructor () {
+ super();
+ }
+
+ /**
+ * !#en
+ * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more.
+ * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
+ * !#zh
+ * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
+ */
+ public destroy () {
+ this._mipmaps = [];
+ return super.destroy();
+ }
+
+ /**
+ * !#en
+ * Release texture, please use destroy instead.
+ * !#zh 释放纹理,请使用 destroy 替代。
+ * @deprecated Since v2.0.
+ */
+ public releaseTexture () {
+ this.mipmaps = [];
+ }
+
+ public _serialize () {
+ return {
+ base: super._serialize(),
+ mipmaps: this._mipmaps.map((mipmap) => {return {
+ front: mipmap.front._uuid,
+ back: mipmap.back._uuid,
+ left: mipmap.left._uuid,
+ right: mipmap.right._uuid,
+ top: mipmap.top._uuid,
+ bottom: mipmap.bottom._uuid,
+ }; }),
+ };
+ }
+
+ public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) {
+ const data = serializedData as ITextureCubeSerializeData;
+ super._deserialize(data.base, handle);
+
+ this._mipmaps = new Array(data.mipmaps.length);
+ for (let i = 0; i < data.mipmaps.length; ++i) {
+ // Prevent resource load failed
+ this._mipmaps[i] = {
+ front: new ImageAsset(),
+ back: new ImageAsset(),
+ left: new ImageAsset(),
+ right: new ImageAsset(),
+ top: new ImageAsset(),
+ bottom: new ImageAsset(),
+ };
+ const mipmap = data.mipmaps[i];
+ handle.result.push(this._mipmaps[i], `front`, mipmap.front);
+ handle.result.push(this._mipmaps[i], `back`, mipmap.back);
+ handle.result.push(this._mipmaps[i], `left`, mipmap.left);
+ handle.result.push(this._mipmaps[i], `right`, mipmap.right);
+ handle.result.push(this._mipmaps[i], `top`, mipmap.top);
+ handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom);
+ }
+ }
+
+ protected _createTexture () {
+ if (this._mipmaps.length === 0) {
+ return;
+ }
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ this._texture = gfxDevice.createTexture({
+ type: GFXTextureType.TEX2D,
+ /* tslint:disable:no-bitwise */
+ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST,
+ /* tslint:enable:no-bitwise */
+ format: this._getGfxFormat(),
+ width: this.width,
+ height: this.height,
+ mipLevel: this._mipmaps.length,
+ arrayLayer: 6,
+ });
+
+ this._mipmaps.forEach((mipmap, level) => {
+ _forEachFace(mipmap, (face, faceIndex) => {
+ this._assignImage(face, level, faceIndex);
+ });
+ });
+ }
+
+ protected _createTextureView () {
+ if (!this._texture) {
+ return;
+ }
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ this._textureView = gfxDevice.createTextureView({
+ texture: this._texture,
+ type: GFXTextureViewType.TV2D_ARRAY,
+ format: this._getGfxFormat(),
+ });
+ }
+}
+
+/* tslint:disable:no-string-literal */
+cc['TextureCube'] = TextureCube;
+
+interface ITextureCubeSerializeData {
+ base: string;
+ mipmaps: Array<{
+ front: string;
+ back: string;
+ left: string;
+ right: string;
+ top: string;
+ bottom: string;
+ }>;
+}
+
+enum FaceIndex {
+ right = 0,
+ left = 1,
+ top = 2,
+ bottom = 3,
+ front = 4,
+ back = 5,
+}
+
+/**
+ * @param {Mipmap} mipmap
+ * @param {(face: ImageAsset) => void} callback
+ */
+function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) {
+ callback(mipmap.front, FaceIndex.front);
+ callback(mipmap.back, FaceIndex.back);
+ callback(mipmap.left, FaceIndex.left);
+ callback(mipmap.right, FaceIndex.right);
+ callback(mipmap.top, FaceIndex.top);
+ callback(mipmap.bottom, FaceIndex.bottom);
+}
diff --git a/cocos/assets/image-asset.js b/cocos/assets/image-asset.js
deleted file mode 100644
index 9644ebed06..0000000000
--- a/cocos/assets/image-asset.js
+++ /dev/null
@@ -1,243 +0,0 @@
-/****************************************************************************
- 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 {ccclass, property} from "../core/data/class-decorator";
-import EventTarget from '../core/event/event-target';
-import {addon} from '../core/utils/js';
-
-/**
- * @typedef {{ _data: ArrayBufferView, _compressed: boolean, width: number, height: number, format: number}} RawImageData
- */
-
-const CHAR_CODE_0 = 48; // '0'
-
-/**
- * Class ImageAsset.
- */
-@ccclass('cc.ImageAsset')
-export default class ImageAsset extends cc.Asset {
-
- static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc'];
-
- /**
- * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} nativeAsset
- */
- constructor(nativeAsset = undefined) {
- super();
- EventTarget.call(this);
-
- /**
- * !#en
- * The url of the texture, this could be empty if the texture wasn't created via a file.
- * !#zh
- * 图像文件的 url,当图像不是由文件创建时值可能为空
- * @property url
- * @type {String}
- * @readonly
- */
- // TODO - use nativeUrl directly
- this.url = "";
-
- /**
- * @type {HTMLCanvasElement | HTMLImageElement | RawImageData}
- */
- this._nativeData = {
- _data: null,
- width: 0,
- height: 0,
- format: 0,
- _compressed: false
- };
-
- if (CC_EDITOR) {
- this._exportedExts = null;
- }
-
- if (nativeAsset !== undefined) {
- this._nativeAsset = nativeAsset;
- }
- }
-
- /**
- * @type {HTMLCanvasElement | HTMLImageElement | RawImageData}
- */
- @property({
- override: true
- })
- get _nativeAsset () {
- // maybe returned to pool in webgl
- return this._nativeData;
- }
-
- /**
- * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} value
- */
- set _nativeAsset (value) {
- this.reset(value);
- }
-
- /**
- * @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView}
- */
- get data() {
- return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
- }
-
- /**
- * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data
- */
- reset(data) {
- if (!(data instanceof HTMLElement)) {
- this._nativeData = Object.create(data);
- this._onDataComplete();
- } else {
- this._nativeData = data;
- if (CC_WECHATGAME || CC_QQPLAY || data.complete || data instanceof HTMLCanvasElement) {
- this._onDataComplete();
- } else {
- this.loaded = false;
- data.addEventListener('load', () => {
- this._onDataComplete();
- });
- data.addEventListener('error', (err) => {
- cc.warnID(3119, err.message);
- });
- }
- }
- }
-
- get width() {
- return this._nativeData.width;
- }
-
- get height() {
- return this._nativeData.height;
- }
-
- get format() {
- if (this._nativeData instanceof HTMLElement) {
- return undefined;
- }
- return this._nativeData.format;
- }
-
- // destroy() {
- // if (cc.macro.CLEANUP_IMAGE_CACHE) {
- // if (this._data instanceof HTMLImageElement) {
- // this._data.src = "";
- // cc.loader.removeItem(this._data.id);
- // }
- // }
- // }
-
- // SERIALIZATION
-
- _serialize () {
- let extId = "";
- let exportedExts = this._exportedExts;
- if (!exportedExts && this._native) {
- exportedExts = [this._native];
- }
- if (exportedExts) {
- let exts = [];
- for (let i = 0; i < exportedExts.length; i++) {
- let extId = "";
- let ext = exportedExts[i];
- if (ext) {
- // ext@format
- let extFormat = ext.split('@');
- extId = ImageAsset.extnames.indexOf(extFormat[0]);
- if (extId < 0) {
- extId = ext;
- }
- if (extFormat[1]) {
- extId += '@' + extFormat[1];
- }
- }
- exts.push(extId);
- }
- extId = exts.join('_');
- }
- return "" + extId;
- }
-
- _deserialize (data, handle) {
- let fields = data.split(',');
- // decode extname
- var extIdStr = fields[0];
- if (extIdStr) {
- let extIds = extIdStr.split('_');
-
- let extId = 999;
- let ext = '';
- let format = this._format;
- let SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS;
- for (let i = 0; i < extIds.length; i++) {
- let extFormat = extIds[i].split('@');
- let tmpExt = extFormat[0];
- tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0;
- tmpExt = ImageAsset.extnames[tmpExt] || extFormat;
-
- let index = SupportTextureFormats.indexOf(tmpExt);
- if (index !== -1 && index < extId) {
- extId = index;
- ext = tmpExt;
- format = extFormat[1] ? parseInt(extFormat[1]) : this._format;
- }
- }
-
- if (ext) {
- this._setRawAsset(ext);
- this._format = format;
- }
-
- // preset uuid to get correct nativeUrl
- let loadingItem = handle.customEnv;
- let uuid = loadingItem && loadingItem.uuid;
- if (uuid) {
- this._uuid = uuid;
- var url = this.nativeUrl;
- this.url = url;
- }
- }
- }
-
- _onDataComplete() {
- this.loaded = true;
- this.emit("load");
- }
-}
-
-/**
- * !#zh
- * 当该资源加载成功后触发该事件
- * !#en
- * This event is emitted when the asset is loaded
- *
- * @event load
- */
-addon(ImageAsset.prototype, EventTarget.prototype);
-
-cc.ImageAsset = ImageAsset;
\ No newline at end of file
diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts
new file mode 100644
index 0000000000..b43319850c
--- /dev/null
+++ b/cocos/assets/image-asset.ts
@@ -0,0 +1,231 @@
+/****************************************************************************
+ 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 {ccclass, property} from '../core/data/class-decorator';
+import EventTarget from '../core/event/event-target';
+import {addon} from '../core/utils/js';
+import { Asset } from './asset';
+
+export interface IMemoryImageSource {
+ _data: ArrayBufferView | null;
+ _compressed: boolean;
+ width: number;
+ height: number;
+ format: number;
+}
+
+type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource;
+
+/**
+ * Class ImageAsset.
+ */
+@ccclass('cc.ImageAsset')
+export default class ImageAsset extends Asset {
+
+ @property({override: true})
+ get _nativeAsset () {
+ // Maybe returned to pool in webgl.
+ return this._nativeData;
+ }
+
+ set _nativeAsset (value: ImageSource) {
+ this.reset(value);
+ }
+
+ get data () {
+ return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
+ }
+
+ get width () {
+ return this._nativeData.width;
+ }
+
+ get height () {
+ return this._nativeData.height;
+ }
+
+ get format () {
+ if (this._nativeData instanceof HTMLElement) {
+ return undefined;
+ }
+ return this._nativeData.format;
+ }
+
+ /**
+ * !#en
+ * The url of the texture, this could be empty if the texture wasn't created via a file.
+ * !#zh
+ * 图像文件的 url,当图像不是由文件创建时值可能为空
+ */
+ // TODO - use nativeUrl directly
+ get url () {
+ return this._url;
+ }
+
+ private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc'];
+
+ private _nativeData: ImageSource;
+
+ private _url: string;
+
+ private _exportedExts: string[] | null | undefined = undefined;
+
+ private _format: string = '';
+
+ /**
+ * @param nativeAsset
+ */
+ constructor (nativeAsset?: ImageSource) {
+ super();
+ // @ts-ignore
+ EventTarget.call(this);
+
+ this._url = '';
+
+ this._nativeData = {
+ _data: null,
+ width: 0,
+ height: 0,
+ format: 0,
+ _compressed: false,
+ };
+
+ if (CC_EDITOR) {
+ this._exportedExts = null;
+ }
+
+ if (nativeAsset !== undefined) {
+ this._nativeAsset = nativeAsset;
+ }
+ }
+
+ public reset (data: ImageSource) {
+ if (!(data instanceof HTMLElement)) {
+ this._nativeData = Object.create(data);
+ this._onDataComplete();
+ } else {
+ this._nativeData = data;
+ if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) {
+ this._onDataComplete();
+ } else {
+ this.loaded = false;
+ data.addEventListener('load', () => {
+ this._onDataComplete();
+ });
+ data.addEventListener('error', (err) => {
+ cc.warnID(3119, err.message);
+ });
+ }
+ }
+ }
+
+ // destroy() {
+ // if (cc.macro.CLEANUP_IMAGE_CACHE) {
+ // if (this._data instanceof HTMLImageElement) {
+ // this._data.src = "";
+ // cc.loader.removeItem(this._data.id);
+ // }
+ // }
+ // }
+
+ // SERIALIZATION
+
+ public _serialize () {
+ let targetExtensions = this._exportedExts;
+ if (!targetExtensions && this._native) {
+ targetExtensions = [this._native];
+ }
+
+ if (!targetExtensions) {
+ return '';
+ }
+
+ const extensionIndices: string[] = [];
+ for (const targetExtension of targetExtensions) {
+ const extensionFormat = targetExtension.split('@');
+ const i = ImageAsset.extnames.indexOf(extensionFormat[0]);
+ let exportedExtensionID = i < 0 ? targetExtension : `${i}`;
+ if (extensionFormat[1]) {
+ exportedExtensionID += '@' + extensionFormat[1];
+ }
+ extensionIndices.push(exportedExtensionID);
+ }
+ return extensionIndices.join('_');
+ }
+
+ public _deserialize (data: string, handle: any) {
+ const extensionIDs = data.split('_');
+
+ let preferedExtensionIndex = Number.MAX_VALUE;
+ let format = this._format;
+ let ext = '';
+ const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[];
+ for (const extensionID of extensionIDs) {
+ const extFormat = extensionID.split('@');
+
+ const i = parseInt(extFormat[0], undefined);
+ const tmpExt = ImageAsset.extnames[i] || extFormat.join();
+
+ const index = SupportTextureFormats.indexOf(tmpExt);
+ if (index !== -1 && index < preferedExtensionIndex) {
+ preferedExtensionIndex = index;
+ ext = tmpExt;
+ format = extFormat[1] ? extFormat[1] : this._format;
+ }
+ }
+
+ if (ext) {
+ // @ts-ignore
+ this._setRawAsset(ext);
+ this._format = format;
+ }
+
+ // preset uuid to get correct nativeUrl
+ const loadingItem = handle.customEnv;
+ const uuid = loadingItem && loadingItem.uuid;
+ if (uuid) {
+ this._uuid = uuid;
+ this._url = this.nativeUrl;
+ }
+ }
+
+ public _onDataComplete () {
+ this.loaded = true;
+ // @ts-ignore
+ this.emit('load');
+ }
+}
+
+/**
+ * !#zh
+ * 当该资源加载成功后触发该事件
+ * !#en
+ * This event is emitted when the asset is loaded
+ *
+ * @event load
+ */
+addon(ImageAsset.prototype, EventTarget.prototype);
+
+cc.ImageAsset = ImageAsset;
diff --git a/cocos/assets/render-texture.js b/cocos/assets/render-texture.js
deleted file mode 100644
index 5b3302620f..0000000000
--- a/cocos/assets/render-texture.js
+++ /dev/null
@@ -1,135 +0,0 @@
-import gfx from '../renderer/gfx';
-import Texture2D from './texture-2d';
-import { ccclass } from '../core/data/class-decorator';
-
-/**
- * Render textures are textures that can be rendered to.
- * @class RenderTexture
- * @extends Texture2D
- */
-@ccclass('cc.RenderTexture')
-export default class RenderTexture extends Texture2D {
-
- constructor () {
- super();
- this._framebuffer = null;
- }
-
- /**
- * !#en
- * Init the render texture with size.
- * !#zh
- * 初始化 render texture
- * @param {Number} [width]
- * @param {Number} [height]
- * @param {Number} [depthStencilFormat]
- * @method initWithSize
- */
- initWithSize (width, height, depthStencilFormat) {
- this.width = Math.floor(width || cc.visibleRect.width);
- this.height = Math.floor(height || cc.visibleRect.height);
- this._resetUnderlyingMipmaps();
-
- let opts = {
- colors: [ this._texture ],
- };
- if (depthStencilFormat) {
- if (this.depthStencilBuffer) this.depthStencilBuffer.destroy();
- let depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height);
- if (depthStencilFormat === gfx.RB_FMT_D24S8) {
- opts.depthStencil = depthStencilBuffer;
- }
- else if (depthStencilFormat === gfx.RB_FMT_S8) {
- opts.stencil = depthStencilBuffer;
- }
- else if (depthStencilFormat === gfx.RB_FMT_D16) {
- opts.depth = depthStencilBuffer;
- }
- this.depthStencilBuffer = depthStencilBuffer;
- this.depthStencilFormat = depthStencilFormat;
- }
-
- if (this._framebuffer) this._framebuffer.destroy();
- this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts);
-
- this.loaded = true;
- this.emit("load");
- }
-
- updateSize(width, height) {
- this.width = Math.floor(width || cc.visibleRect.width);
- this.height = Math.floor(height || cc.visibleRect.height);
- this._resetUnderlyingMipmaps();
-
- let rbo = this.depthStencilBuffer;
- if (rbo) rbo.update(this.width, this.height);
- this._framebuffer._width = width;
- this._framebuffer._height = height;
- }
-
- /**
- * !#en Draw a texture to the specified position
- * !#zh 将指定的图片渲染到指定的位置上
- * @param {Texture2D} texture
- * @param {Number} x
- * @param {Number} y
- */
- drawTextureAt (texture, x, y) {
- if (!texture._image) return;
-
- this._texture.updateSubImage({
- x, y,
- image: texture._image,
- width: texture.width,
- height: texture.height,
- level: 0,
- flipY: false,
- premultiplyAlpha: texture._premultiplyAlpha
- })
- }
-
- /**
- * !#en
- * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array.
- * It will return a new (width * height * 4) length Uint8Array by default。
- * You can specify a data to store the pixels to reuse the data,
- * you and can specify other params to specify the texture region to read.
- * !#zh
- * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。
- * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。
- * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。
- * @method readPixels
- * @param {Uint8Array} [data]
- * @param {Number} [x]
- * @param {Number} [y]
- * @param {Number} [w]
- * @param {Number} [h]
- * @return {Uint8Array}
- */
- readPixels (data, x, y, w, h) {
- if (!this._framebuffer || !this._texture) return data;
-
- x = x || 0;
- y = y || 0;
- let width = w || this.width;
- let height = h || this.height;
- data = data || new Uint8Array(width * height * 4);
-
- let gl = cc.game._renderContext._gl;
- let oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
- gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID);
- gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
- gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO);
-
- return data;
- }
-
- destroy () {
- super.destroy();
- if (this._framebuffer) {
- this._framebuffer.destroy();
- }
- }
-}
-
-cc.RenderTexture = RenderTexture;
diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts
new file mode 100644
index 0000000000..72d001bcc6
--- /dev/null
+++ b/cocos/assets/render-texture.ts
@@ -0,0 +1,220 @@
+import { ccclass } from '../core/data/class-decorator';
+import { IRect2D, normalizeRect2D } from '../core/vmath/rect';
+import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
+import { GFXFramebuffer } from '../gfx/framebuffer';
+import { GFXTexture } from '../gfx/texture';
+import { GFXTextureView } from '../gfx/texture-view';
+import { RenderPassStage } from '../pipeline/render-pipeline';
+import ImageAsset from './image-asset';
+import Texture2D from './texture-2d';
+
+enum DepthStencilFormat {
+ D24S8 = GFXFormat.D24S8,
+
+ S8 = GFXFormat.R8UI,
+
+ D16 = GFXFormat.D16,
+}
+
+function toGfxDepthStencilFormat (depthStencilFormat: DepthStencilFormat): GFXFormat {
+ return depthStencilFormat as unknown as GFXFormat;
+}
+
+/**
+ * Render textures are textures that can be rendered to.
+ * @class RenderTexture
+ * @extends Texture2D
+ */
+@ccclass('cc.RenderTexture')
+export default class RenderTexture extends Texture2D {
+ private _framebuffer: GFXFramebuffer | null = null;
+
+ private _depthStencilTexture: GFXTexture | null = null;
+
+ private _depthStencilTextureView: GFXTextureView | null = null;
+
+ constructor () {
+ super();
+ }
+
+ /**
+ * !#en
+ * Init the render texture with size.
+ * !#zh
+ * 初始化 render texture
+ * @param [width]
+ * @param [height]
+ * @param [depthStencilFormat]
+ * @method initWithSize
+ */
+ public initWithSize (width?: number, height?: number, depthStencilFormat?: DepthStencilFormat) {
+ this.destroy();
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ const w = Math.floor(width || cc.visibleRect.width);
+ const h = Math.floor(height || cc.visibleRect.height);
+ const image = new ImageAsset({
+ width: w,
+ height: h,
+ format: GFXFormat.RGBA8UI,
+ _data: new Uint8Array(w * h * 4),
+ _compressed: false,
+ });
+
+ this.image = image;
+
+ if (!this._texture) {
+ return;
+ }
+
+ const colorView = gfxDevice.createTextureView({
+ texture: this._texture,
+ type: GFXTextureViewType.TV2D,
+ format: this._getGfxFormat(),
+ });
+
+ if (!colorView) {
+ return;
+ }
+
+ if (depthStencilFormat !== undefined) {
+ this._depthStencilTexture = gfxDevice.createTexture({
+ type: GFXTextureType.TEX2D,
+ usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT,
+ format: toGfxDepthStencilFormat(depthStencilFormat),
+ width: w,
+ height: h,
+ });
+ if (!this._depthStencilTexture) {
+ return;
+ }
+ this._depthStencilTextureView = gfxDevice.createTextureView({
+ texture: this._depthStencilTexture,
+ type: GFXTextureViewType.TV2D,
+ format: toGfxDepthStencilFormat(depthStencilFormat),
+ });
+ }
+
+ if (this._depthStencilTextureView === null) {
+ return;
+ }
+
+ this._framebuffer = gfxDevice.createFramebuffer({
+ renderPass: cc.director.root.pipeline.getRenderPass(RenderPassStage.DEFAULT),
+ colorViews: [ colorView ],
+ depthStencilView: this._depthStencilTextureView === null ? undefined : this._depthStencilTextureView,
+ isOffscreen: true,
+ });
+
+ this.loaded = true;
+ // @ts-ignore
+ this.emit('load');
+ }
+
+ public destroy () {
+ if (this._framebuffer) {
+ this._framebuffer.destroy();
+ this._framebuffer = null;
+ }
+ if (this._depthStencilTextureView) {
+ this._depthStencilTextureView.destroy();
+ this._depthStencilTextureView = null;
+ }
+ if (this._depthStencilTexture) {
+ this._depthStencilTexture.destroy();
+ this._depthStencilTexture = null;
+ }
+ return super.destroy();
+ }
+
+ // TODO:
+ // public updateSize (width, height) {
+ // this.width = Math.floor(width || cc.visibleRect.width);
+ // this.height = Math.floor(height || cc.visibleRect.height);
+ // this._resetUnderlyingMipmaps();
+
+ // const rbo = this.depthStencilBuffer;
+ // if (rbo) { rbo.update(this.width, this.height); }
+ // this._framebuffer._width = width;
+ // this._framebuffer._height = height;
+ // }
+
+ /**
+ * !#en Draw a texture to the specified position
+ * !#zh 将指定的图片渲染到指定的位置上
+ * @param texture
+ * @param x
+ * @param y
+ */
+ public drawTextureAt (texture: Texture2D, x: number, y: number) {
+ if (!this._texture) {
+ return;
+ }
+
+ const image = texture.image;
+
+ if (!image) {
+ return;
+ }
+
+ this._assignImage(image, 0);
+ }
+
+ /**
+ * !#en
+ * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array.
+ * It will return a new (width * height * 4) length Uint8Array by default。
+ * You can specify a data to store the pixels to reuse the data,
+ * you and can specify other params to specify the texture region to read.
+ * !#zh
+ * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。
+ * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。
+ * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。
+ * @param [data]
+ * @param [rect]
+ */
+ public readPixels (data?: Uint8Array, rect: IRect2D = {}) {
+ if (!this._framebuffer || !this._texture) {
+ return undefined;
+ }
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ const normalizedRect = normalizeRect2D(rect, this.width, this.height);
+
+ data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4);
+
+ gfxDevice.copyFramebufferToBuffer(this._framebuffer, data.buffer, [{
+ buffOffset: 0,
+ buffStride: 0,
+ buffTexHeight: 0,
+ texOffset: {
+ x: normalizedRect.x,
+ y: normalizedRect.y,
+ z: 0,
+ },
+ texExtent: {
+ width: normalizedRect.width,
+ height: normalizedRect.height,
+ depth: 1,
+ },
+ texSubres: {
+ baseMipLevel: 0,
+ levelCount: 1,
+ baseArrayLayer: 0,
+ layerCount: 1,
+ },
+ }]);
+
+ return data;
+ }
+}
+
+cc.RenderTexture = RenderTexture;
diff --git a/cocos/assets/texture-2d.js b/cocos/assets/texture-2d.js
deleted file mode 100644
index 544984835b..0000000000
--- a/cocos/assets/texture-2d.js
+++ /dev/null
@@ -1,327 +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.
- ****************************************************************************/
-// @ts-check
-import GFXTexture2D from '../renderer/gfx/texture-2d';
-import {ccclass, property} from '../core/data/class-decorator';
-import TextureBase from './texture-base';
-import ImageAsset from './image-asset';
-
-/**
- * @typedef {import("./texture-base").ImageSource} ImageSource
- * @typedef {import("./texture-base").TextureUpdateOpts} TextureUpdateOpts
- */
-
-/**
- *
- * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
- * The created cc.Texture2D object will always have power-of-two dimensions.
- * Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
- * Be aware that the content of the generated textures will be upside-down!