impl texture-assets using gfx

This commit is contained in:
Leslie
2019-01-08 19:28:00 +08:00
parent 69f38e6da6
commit aacd60fa92
7 changed files with 783 additions and 861 deletions
+118 -161
View File
@@ -23,39 +23,26 @@
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 GFXTextureCube from '../../renderer/gfx/texture-cube';
import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define';
/**
* @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,
});
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.
* @type {Mipmap[]}
*/
get mipmaps () {
return this._mipmaps;
@@ -63,15 +50,14 @@ export default class TextureCube extends TextureBase {
/**
* Sets the mipmaps images.
* @type {Mipmap[]}
*/
set mipmaps (value) {
this._setMipmaps(value);
this._mipmaps = value;
this._recreateTexture();
}
/**
* Gets the mipmap image at level 0.
* @type {Mipmap}
*/
get image () {
return this._mipmaps.length === 0 ? null : this._mipmaps[0];
@@ -79,73 +65,39 @@ export default class TextureCube extends TextureBase {
/**
* Sets the mipmap images as a single mipmap image.
* @type {Mipmap}
*/
set image (value) {
this.mipmaps = [value];
this.mipmaps = value ? [value] : [];
}
/**
* @param {Mipmap} mipmap
* @return {ImageSource[]}
* @param textures
* @deprecated Manually assign to mipmaps property instead.
*/
public 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
*/
public static _forEachFace (mipmap, callback) {
for (const face in mipmap) {
callback(mipmap[face]);
}
}
/**
* @param {Texture2D[]} textures
*/
public static fromTexture2DArray (textures, out) {
const 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;
}, {}));
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 = res;
out.mipmaps = mipmaps;
return out;
}
/**
* @type {Mipmap[]}
*/
@property
public _mipmaps = [];
public _mipmaps: ITextureCubeMipmap[] = [];
constructor () {
super();
/**
* @type {GFXTextureCube}
*/
this._texture = null;
}
/**
* Gets the underlying texture object.
*/
public getImpl () {
return this._texture;
}
/**
@@ -156,13 +108,9 @@ export default class TextureCube extends TextureBase {
* !#zh
* 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
* @method destroy
* @return {Boolean} inherit from the CCObject
*/
public destroy () {
this.releaseTexture();
// TODO cc.textureUtil ?
// cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
this._mipmaps = [];
return super.destroy();
}
@@ -170,81 +118,10 @@ export default class TextureCube extends TextureBase {
* !#en
* Release texture, please use destroy instead.
* !#zh 释放纹理,请使用 destroy 替代。
* @method releaseTexture
* @deprecated since v2.0
* @deprecated Since v2.0.
*/
public 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
*/
public _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
*/
public _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
*/
public update (options) {
if (!options) { return; }
super.update(options);
// TODO: options.image
if (this._texture) {
this._texture.update(options);
}
this.mipmaps = [];
}
public _serialize () {
@@ -261,12 +138,21 @@ export default class TextureCube extends TextureBase {
};
}
public _deserialize (data, handle) {
super._deserialize(data.base);
public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) {
const data = serializedData as ITextureCubeSerializeData;
super._deserialize(data.base, handle);
this._mipmaps = new Array(data.mipmaps.length);
this._mipmaps.fill({});
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);
@@ -280,6 +166,77 @@ export default class TextureCube extends TextureBase {
public onLoaded () {
this.mipmaps = this._mipmaps;
}
protected _createTexture () {
if (this._mipmaps.length === 0) {
return;
}
this._texture = this._getGlobalDevice().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;
}
this._textureView = this._getGlobalDevice().createTextureView({
texture: this._texture,
type: GFXTextureViewType.TV2D_ARRAY,
format: this._getGfxFormat(),
});
}
}
cc.TextureCube = TextureCube;
/* 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);
}
+127 -139
View File
@@ -26,108 +26,38 @@
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';
/**
* @typedef {{ _data: ArrayBufferView, _compressed: boolean, width: number, height: number, format: number}} RawImageData
*/
export interface IMemoryImageSource {
_data: ArrayBufferView | null;
_compressed: boolean;
width: number;
height: number;
format: number;
}
const CHAR_CODE_0 = 48; // '0'
type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource;
/**
* Class ImageAsset.
*/
@ccclass('cc.ImageAsset')
export default class ImageAsset extends cc.Asset {
export default class ImageAsset extends Asset {
public 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,
})
@property({override: true})
get _nativeAsset () {
// maybe returned to pool in webgl
// Maybe returned to pool in webgl.
return this._nativeData;
}
/**
* @param {HTMLCanvasElement | HTMLImageElement | RawImageData} value
*/
set _nativeAsset (value) {
set _nativeAsset (value: ImageSource) {
this.reset(value);
}
/**
* @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView}
*/
get data () {
return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
}
/**
* @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data
*/
public 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;
}
@@ -143,6 +73,74 @@ export default class ImageAsset extends cc.Asset {
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) {
@@ -155,77 +153,67 @@ export default class ImageAsset extends cc.Asset {
// SERIALIZATION
public _serialize () {
let extId = '';
let exportedExts = this._exportedExts;
if (!exportedExts && this._native) {
exportedExts = [this._native];
let targetExtensions = this._exportedExts;
if (!targetExtensions && this._native) {
targetExtensions = [this._native];
}
if (exportedExts) {
const exts = [];
for (let i = 0; i < exportedExts.length; i++) {
let extId = '';
const ext = exportedExts[i];
if (ext) {
// ext@format
const extFormat = ext.split('@');
extId = ImageAsset.extnames.indexOf(extFormat[0]);
if (extId < 0) {
extId = ext;
}
if (extFormat[1]) {
extId += '@' + extFormat[1];
}
}
exts.push(extId);
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];
}
extId = exts.join('_');
extensionIndices.push(exportedExtensionID);
}
return '' + extId;
return extensionIndices.join('_');
}
public _deserialize (data, handle) {
const fields = data.split(',');
// decode extname
const extIdStr = fields[0];
if (extIdStr) {
const extIds = extIdStr.split('_');
public _deserialize (data: string, handle: any) {
const extensionIDs = data.split('_');
let extId = 999;
let ext = '';
let format = this._format;
const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS;
for (let i = 0; i < extIds.length; i++) {
const extFormat = extIds[i].split('@');
let tmpExt = extFormat[0];
tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0;
tmpExt = ImageAsset.extnames[tmpExt] || extFormat;
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 index = SupportTextureFormats.indexOf(tmpExt);
if (index !== -1 && index < extId) {
extId = index;
ext = tmpExt;
format = extFormat[1] ? parseInt(extFormat[1]) : this._format;
}
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) {
this._setRawAsset(ext);
this._format = 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;
const url = this.nativeUrl;
this.url = url;
}
// 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');
}
}
+154 -75
View File
@@ -1,7 +1,25 @@
import { ccclass } from '../core/data/class-decorator';
import gfx from '../renderer/gfx';
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
@@ -9,10 +27,14 @@ import Texture2D from './texture-2d';
*/
@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();
this._framebuffer = null;
}
/**
@@ -20,70 +42,123 @@ export default class RenderTexture extends Texture2D {
* Init the render texture with size.
* !#zh
* 初始化 render texture
* @param {Number} [width]
* @param {Number} [height]
* @param {Number} [depthStencilFormat]
* @param [width]
* @param [height]
* @param [depthStencilFormat]
* @method initWithSize
*/
public initWithSize (width, height, depthStencilFormat) {
this.width = Math.floor(width || cc.visibleRect.width);
this.height = Math.floor(height || cc.visibleRect.height);
this._resetUnderlyingMipmaps();
public initWithSize (width?: number, height?: number, depthStencilFormat?: DepthStencilFormat) {
this.destroy();
const opts = {
colors: [ this._texture ],
};
if (depthStencilFormat) {
if (this.depthStencilBuffer) { this.depthStencilBuffer.destroy(); }
const 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;
const gfxDevice = this._getGlobalDevice();
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;
}
if (this._framebuffer) { this._framebuffer.destroy(); }
this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts);
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 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;
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 {Texture2D} texture
* @param {Number} x
* @param {Number} y
* @param texture
* @param x
* @param y
*/
public drawTextureAt (texture, x, y) {
if (!texture._image) { return; }
public drawTextureAt (texture: Texture2D, x: number, y: number) {
if (!this._texture) {
return;
}
this._texture.updateSubImage({
x, y,
image: texture._image,
width: texture.width,
height: texture.height,
level: 0,
flipY: false,
premultiplyAlpha: texture._premultiplyAlpha,
});
const image = texture.image;
if (!image) {
return;
}
this._assignImage(image, 0);
}
/**
@@ -96,38 +171,42 @@ export default class RenderTexture extends Texture2D {
* 从 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}
* @param [data]
* @param [rect]
*/
public readPixels (data, x, y, w, h) {
if (!this._framebuffer || !this._texture) { return data; }
public readPixels (data?: Uint8Array, rect: IRect2D = {}) {
if (!this._framebuffer || !this._texture) {
return undefined;
}
x = x || 0;
y = y || 0;
const width = w || this.width;
const height = h || this.height;
data = data || new Uint8Array(width * height * 4);
const normalizedRect = normalizeRect2D(rect, this.width, this.height);
const gl = cc.game._renderContext._gl;
const 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);
data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4);
this._getGlobalDevice().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;
}
public destroy () {
super.destroy();
if (this._framebuffer) {
this._framebuffer.destroy();
}
}
}
cc.RenderTexture = RenderTexture;
+72 -177
View File
@@ -24,53 +24,19 @@
THE SOFTWARE.
****************************************************************************/
// @ts-check
import {ccclass, property} from '../core/data/class-decorator';
import GFXTexture2D from '../renderer/gfx/texture-2d';
import { ccclass, property } from '../core/data/class-decorator';
import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
import ImageAsset from './image-asset';
import TextureBase from './texture-base';
/**
* @typedef {import("./texture-base").ImageSource} ImageSource
* @typedef {import("./texture-base").TextureUpdateOpts} TextureUpdateOpts
*/
/**
* <p>
* This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data. <br/>
* The created cc.Texture2D object will always have power-of-two dimensions. <br/>
* Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions <br/>
* i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0). <br/>
* Be aware that the content of the generated textures will be upside-down! </p>
* @class Texture2D
* @extends TextureBase
* Represents a 2-dimension texture.
*/
@ccclass('cc.Texture2D')
export default class Texture2D extends TextureBase {
@property({
override: true,
})
public _flipY = true;
/**
* @type {ImageAsset[]}
*/
@property([ImageAsset])
public _mipmaps = [];
constructor () {
super();
/**
* @type {GFXTexture2D}
*/
this._texture = null;
}
/**
* Gets the mipmap images.
* Note that the result do not contains the auto generated mipmaps.
* @return {ImageAsset[]}
*/
get mipmaps () {
return this._mipmaps;
@@ -78,15 +44,14 @@ export default class Texture2D extends TextureBase {
/**
* Sets the mipmaps images.
* @param {ImageAsset[]} value
*/
set mipmaps (value) {
this._setMipmaps(value);
this._mipmaps = value;
this._recreateTexture();
}
/**
* Gets the mipmap image at level 0.
* @return {ImageAsset}
*/
get image () {
return this._mipmaps.length === 0 ? null : this._mipmaps[0];
@@ -94,17 +59,16 @@ export default class Texture2D extends TextureBase {
/**
* Sets the mipmap images as a single mipmap image.
* @param {ImageAsset} value
*/
set image (value) {
this.mipmaps = [value];
this.mipmaps = value ? [value] : [];
}
/**
* Gets the underlying texture object.
*/
public getImpl () {
return this._texture;
@property([ImageAsset])
public _mipmaps: ImageAsset[] = [];
constructor () {
super(true);
}
/**
@@ -115,82 +79,33 @@ export default class Texture2D extends TextureBase {
}
/**
* Update texture options, not available in Canvas render mode.
* image, format, premultiplyAlpha can not be updated in native.
* @method update
* @param {TextureUpdateOpts} options
* Updates mipmaps at level 0.
*/
public update (options) {
if (!options) {
return;
}
super.update(options);
if (options.image) {
options.images = [options.image];
}
if (options.images !== undefined && options.images.length !== 0) {
this._setMipmaps(options.images.map((image) => {
const mipmap = new ImageAsset();
mipmap.reset(image instanceof HTMLElement ? image : {
_data: image,
width: this.width,
height: this.height,
format: this._format,
_compressed: false,
});
return mipmap;
}));
}
if (this._texture) {
this._texture.update(options);
}
}
/**
*
* @param {ImageSource} source
*/
public updateImage (source) {
this.updateMipmaps([source]);
public updateImage () {
this.updateMipmaps(0);
}
/**
* Updates mipmaps at specified range of levels.
* @param {ImageSource[]} sources The image sources.
* @param {number} firstLevel The first level from which the sources update.
* @param sources The image sources.
* @param firstLevel The first level from which the sources update.
* @description
* If the range specified by [firstLevel, firstLevel + sources.length) exceeds
* the actually range of mipmaps this texture contains, only overlaped mipmaps are updated.
* Use this method if your mipmap data are modified.
*/
public updateMipmaps (sources, firstLevel = 0) {
if (firstLevel >= sources.length) {
public updateMipmaps (firstLevel: number, count?: number) {
if (firstLevel >= this._mipmaps.length) {
return;
}
const nUpdate = Math.min(sources.length, this._mipmaps.length - firstLevel);
const nUpdate = Math.min(
count === undefined ? this._mipmaps.length : count,
this._mipmaps.length - firstLevel);
for (let i = 0; i < nUpdate; ++i) {
const level = firstLevel + i;
const mipmap = this._mipmaps[level];
const source = sources[i];
mipmap.reset(source instanceof HTMLElement ? source : {
_data: source,
width: mipmap.width,
height: mipmap.height,
format: mipmap._format,
_compressed: false,
});
this._texture.updateImage({
width: this.width,
height: this.height,
level,
image: sources[i],
flipY: false,
premultiplyAlpha: false,
});
this._uploadImage(this._mipmaps[level], level);
}
}
@@ -214,13 +129,9 @@ export default class Texture2D extends TextureBase {
* !#zh
* 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
* @method destroy
* @return {Boolean} inherit from the CCObject
*/
public destroy () {
this.releaseTexture();
// TODO cc.textureUtil ?
// cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
this._mipmaps = [];
return super.destroy();
}
@@ -228,76 +139,20 @@ export default class Texture2D extends TextureBase {
* !#en
* Description of cc.Texture2D.
* !#zh cc.Texture2D 描述。
* @method description
* @returns {String}
*/
public description () {
return '<cc.Texture2D | Name = ' + (this._mipmaps[0] ? this._mipmaps[0].url : '') + ' | Dimensions = ' + this.width + ' x ' + this.height + '>';
const url = this._mipmaps[0] ? this._mipmaps[0].url : '';
return `<cc.Texture2D | Name = ${url} | Dimension = ${this.width} x ${this.height}>`;
}
/**
* !#en
* Release texture, please use destroy instead.
* !#zh 释放纹理,请使用 destroy 替代。
* @method releaseTexture
* @deprecated since v2.0, use destroy instead.
* @deprecated Since v2.0, use destroy instead.
*/
public 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 {ImageAsset[]} mipmaps
*/
public _setMipmaps (mipmaps) {
this._mipmaps = mipmaps;
if (mipmaps.length === 0) {
super.update({
width: 0,
height: 0,
});
} else {
const level0 = this._mipmaps[0];
super.update({
width: level0.width,
height: level0.height,
format: level0._format,
});
}
let counter = 0;
const inc = () => {
++counter;
if (counter === mipmaps.length) {
this._resetUnderlyingMipmaps(mipmaps.map((mipmap) => mipmap.data));
}
};
mipmaps.forEach((mipmap) => {
if (mipmap.loaded) {
inc();
} else {
mipmap.addEventListener('load', () => {
inc();
});
}
});
}
/**
* Resets sources and amount of the underlying texture's the mipmaps.
* @param {ImageSource[]} mipmapSources
*/
public _resetUnderlyingMipmaps (mipmapSources = [null]) {
const opts = this._getOpts();
opts.images = mipmapSources;
if (!this._texture) {
this._texture = new GFXTexture2D(cc.game._renderContext, opts);
} else {
this._texture.update(opts);
}
this.mipmaps = [];
}
public _serialize () {
@@ -307,8 +162,9 @@ export default class Texture2D extends TextureBase {
};
}
public _deserialize (data, handle) {
super._deserialize(data.base);
public _deserialize (serializedData: any, handle: any) {
const data = serializedData as ITexture2DSerializeData;
super._deserialize(data.base, handle);
this._mipmaps = new Array(data.mipmaps.length);
for (let i = 0; i < data.mipmaps.length; ++i) {
@@ -322,6 +178,45 @@ export default class Texture2D extends TextureBase {
public onLoaded () {
this.mipmaps = this._mipmaps;
}
protected _createTexture () {
if (this._mipmaps.length === 0) {
return;
}
this._texture = this._getGlobalDevice().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,
});
this._mipmaps.forEach((mipmap, level) => {
this._assignImage(mipmap, level);
});
}
protected _createTextureView () {
if (!this._texture) {
return;
}
this._textureView = this._getGlobalDevice().createTextureView({
texture: this._texture,
type: GFXTextureViewType.TV2D,
format: this._getGfxFormat(),
});
}
}
cc.Texture2D = Texture2D;
/* tslint:disable:no-string-literal */
cc['Texture2D'] = Texture2D;
interface ITexture2DSerializeData {
base: string;
mipmaps: string[];
}
+299 -307
View File
@@ -28,30 +28,17 @@ import {ccclass, property} from '../core/data/class-decorator';
import EventTarget from '../core/event/event-target';
import IDGenerator from '../core/utils/id-generator';
import {addon} from '../core/utils/js';
import Enum from '../core/value-types/enum';
import {enums} from '../renderer/gfx/enums';
import Asset from './CCAsset';
/**
* @typedef {import("../renderer/gfx/texture-2d").HTMLImageSource} HTMLImageSource
* @typedef {import("../renderer/gfx/texture-2d").ImageSource} ImageSource
* @typedef {import("../renderer/gfx/texture-2d").TextureUpdateOpts} TextureUpdateOpts
*
* @exports HTMLImageSource
* @exports ImageSource
* @exports TextureUpdateOpts
*/
const _images = [];
import { ccenum } from '../core/value-types/enum';
import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat } from '../gfx/define';
import { GFXDevice } from '../gfx/device';
import { GFXSampler } from '../gfx/sampler';
import { GFXTexture } from '../gfx/texture';
import { GFXTextureView } from '../gfx/texture-view';
import { Asset } from './asset';
import ImageAsset from './image-asset';
const CHAR_CODE_1 = 49; // '1'
const GL_NEAREST = 9728; // gl.NEAREST
const GL_LINEAR = 9729; // gl.LINEAR
const GL_REPEAT = 10497; // gl.REPEAT
const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE
const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT
const idGenerator = new IDGenerator('Tex');
/**
@@ -60,187 +47,145 @@ const idGenerator = new IDGenerator('Tex');
* other formats are supported by compressed file types or raw data.
* @enum {number}
*/
const PixelFormat = Enum({
export enum PixelFormat {
/**
* 16-bit texture without Alpha channel
* @property RGB565
* @readonly
* @type {Number}
*/
RGB565: enums.TEXTURE_FMT_R5_G6_B5,
RGB565 = GFXFormat.R5G6B5,
/**
* 16-bit textures: RGB5A1
* @property RGB5A1
* @readonly
* @type {Number}
*/
RGB5A1: enums.TEXTURE_FMT_R5_G5_B5_A1,
RGB5A1 = GFXFormat.RGB5A1,
/**
* 16-bit textures: RGBA4444
* @property RGBA4444
* @readonly
* @type {Number}
*/
RGBA4444: enums.TEXTURE_FMT_R4_G4_B4_A4,
RGBA4444 = GFXFormat.RGBA4,
/**
* 24-bit texture: RGB888
* @property RGB888
* @readonly
* @type {Number}
*/
RGB888: enums.TEXTURE_FMT_RGB8,
RGB888 = GFXFormat.RGB8UI,
/**
* 32-bit texture: RGBA8888
* @property RGBA8888
* @readonly
* @type {Number}
*/
RGBA8888: enums.TEXTURE_FMT_RGBA8,
RGBA8888 = GFXFormat.RGBA8UI,
/**
* 32-bit float texture: RGBA32F
* @property RGBA32F
* @readonly
* @type {Number}
*/
RGBA32F: enums.TEXTURE_FMT_RGBA32F,
RGBA32F = GFXFormat.RGBA32F,
/**
* 8-bit textures used as masks
* @property A8
* @readonly
* @type {Number}
*/
A8: enums.TEXTURE_FMT_A8,
A8 = GFXFormat.R8UI,
/**
* 8-bit intensity texture
* @property I8
* @readonly
* @type {Number}
*/
I8: enums.TEXTURE_FMT_L8,
I8 = GFXFormat.R8UI,
/**
* 16-bit textures used as masks
* @property AI88
* @readonly
* @type {Number}
*/
AI8: enums.TEXTURE_FMT_L8_A8,
AI8 = GFXFormat.RG8UI,
/**
* rgb 2 bpp pvrtc
* @property RGB_PVRTC_2BPPV1
* @readonly
* @type {Number}
*/
RGB_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_2BPPV1,
RGB_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGB2,
/**
* rgba 2 bpp pvrtc
* @property RGBA_PVRTC_2BPPV1
* @readonly
* @type {Number}
*/
RGBA_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_2BPPV1,
RGBA_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGBA2,
/**
* rgb 4 bpp pvrtc
* @property RGB_PVRTC_4BPPV1
* @readonly
* @type {Number}
*/
RGB_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_4BPPV1,
RGB_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGB4,
/**
* rgba 4 bpp pvrtc
* @property RGBA_PVRTC_4BPPV1
* @readonly
* @type {Number}
*/
RGBA_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1,
});
RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4,
}
ccenum(PixelFormat);
function toGfxFormat (pixelFormat: PixelFormat) {
return pixelFormat as unknown as GFXFormat;
}
/**
* The texture wrap mode
* The texture wrap mode.
* @enum {number}
*/
export const WrapMode = Enum({
export enum WrapMode {
/**
* The constant variable equals gl.REPEAT for texture
* @property REPEAT
* @type {Number}
* @readonly
* Specifies that the repeat warp mode will be used.
*/
REPEAT: GL_REPEAT,
REPEAT = GFXAddress.WRAP,
/**
* The constant variable equals gl.CLAMP_TO_EDGE for texture
* @property CLAMP_TO_EDGE
* @type {Number}
* @readonly
* Specifies that the clamp to edge warp mode will be used.
*/
CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE,
CLAMP_TO_EDGE = GFXAddress.CLAMP,
/**
* The constant variable equals gl.MIRRORED_REPEAT for texture
* @property MIRRORED_REPEAT
* @type {Number}
* @readonly
* Specifies that the mirrored repeat warp mode will be used.
*/
MIRRORED_REPEAT: GL_MIRRORED_REPEAT,
});
MIRRORED_REPEAT = GFXAddress.MIRROR,
/**
* Specifies that the clamp to border wrap mode will be used.
*/
CLAMP_TO_BORDER = GFXAddress.BORDER,
}
ccenum(WrapMode);
function toGfxAddressMode (wrapMode: WrapMode) {
return wrapMode as unknown as GFXAddress;
}
/**
* The texture filter mode
* @enum {number}
*/
export const Filter = Enum({
export enum Filter {
/**
* The constant variable equals gl.LINEAR for texture
* @property LINEAR
* @type {Number}
* @readonly
* Specifies linear filtering.
*/
LINEAR: GL_LINEAR,
LINEAR = GFXFilter.LINEAR,
/**
* The constant variable equals gl.NEAREST for texture
* @property NEAREST
* @type {Number}
* @readonly
* Specifies nearest filtering.
*/
NEAREST: GL_NEAREST,
});
NEAREST = GFXFilter.POINT,
}
ccenum(Filter);
const FilterIndex = {
9728: 0, // GL_NEAREST
9729: 1, // GL_LINEAR
};
/**
* @type TextureUpdateOpts
*/
const _sharedOpts = {
width: undefined,
height: undefined,
minFilter: undefined,
magFilter: undefined,
mipFilter: undefined,
wrapS: undefined,
wrapT: undefined,
format: undefined,
mipmap: undefined,
images: undefined,
image: undefined,
flipY: undefined,
premultiplyAlpha: undefined,
anisotropy: undefined,
};
function _getSharedOptions () {
for (const key in _sharedOpts) {
_sharedOpts[key] = undefined;
}
_images.length = 0;
_sharedOpts.images = _images;
_sharedOpts.flipY = false;
return _sharedOpts;
function toGfxFilterMode (filter: Filter) {
return filter as unknown as GFXFilter;
}
@ccclass('cc.TextureBase')
export default class TextureBase extends Asset {
/**
* !#en
* Texture width, in pixels.
* For 2D texture, the width of texture is equal to its very first mipmap's width;
* For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width.
* !#zh
* 贴图像素宽度
* @property width
* @type {Number}
*/
public get width (): number {
return this._width;
}
/**
* !#en
* Texture height, in pixels.
* For 2D texture, the height of texture is equal to its very first mipmap's height;
* For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height.
* !#zh
* 贴图像素高度
* @property height
* @type {Number}
*/
public get height (): number {
return this._height;
}
public static PixelFormat = PixelFormat;
public static WrapMode = WrapMode;
@@ -249,45 +194,61 @@ export default class TextureBase extends Asset {
/**
*
* @param {TextureBase} texture
* @param texture
*/
public static _isCompressed (texture) {
public static _isCompressed (texture: TextureBase) {
return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1;
}
@property
public _genMipmap = false;
protected _texture: GFXTexture | null = null;
protected _textureView: GFXTextureView | null = null;
@property
public _format = PixelFormat.RGBA8888;
private _genMipmap = false;
@property
public _premultiplyAlpha = false;
private _format: PixelFormat = PixelFormat.RGBA8888;
@property
public _flipY = false;
private _premultiplyAlpha = false;
@property
public _minFilter = Filter.LINEAR;
private _flipY = false;
@property
public _magFilter = Filter.LINEAR;
private _minFilter = Filter.LINEAR;
@property
public _mipFilter = Filter.LINEAR;
private _magFilter = Filter.LINEAR;
@property
public _wrapS = WrapMode.CLAMP_TO_EDGE;
private _mipFilter = Filter.LINEAR;
@property
public _wrapT = WrapMode.CLAMP_TO_EDGE;
private _wrapS: WrapMode = WrapMode.CLAMP_TO_EDGE;
@property
public _anisotropy = 1;
private _wrapT: WrapMode = WrapMode.CLAMP_TO_EDGE;
constructor () {
@property
private _anisotropy = 1;
private _width: number = 0;
private _height: number = 0;
private _sampler: GFXSampler | null = null;
private _id: string;
protected constructor (flipY: boolean = false) {
super();
// @ts-ignore
EventTarget.call(this);
this._flipY = flipY;
// Id for generate hash in material
this._id = idGenerator.getNewId();
@@ -299,109 +260,27 @@ export default class TextureBase extends Asset {
* @property loaded
* @type {Boolean}
*/
// @ts-ignore
this.loaded = false;
/**
* !#en
* Texture width, in pixels.
* For 2D texture, the width of texture is equal to its very first mipmap's width;
* For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width.
* !#zh
* 贴图像素宽度
* @property width
* @type {Number}
*/
this.width = 0;
/**
* !#en
* Texture height, in pixels.
* For 2D texture, the height of texture is equal to its very first mipmap's height;
* For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height.
* !#zh
* 贴图像素高度
* @property height
* @type {Number}
*/
this.height = 0;
}
/**
* Gets the underlying texture object.
* @deprecated Use getGfxTexture() instead.
*/
public getImpl () {
return this._texture;
}
public getId () {
return this._id;
}
/**
* Update texture sampler options.
* @method update
* @param {TextureUpdateOpts} options
*/
public update (options) {
if (!options) {
return;
}
if (options.width !== undefined) {
this.width = options.width;
}
if (options.height !== undefined) {
this.height = options.height;
}
if (options.minFilter !== undefined) {
this._minFilter = options.minFilter;
options.minFilter = FilterIndex[options.minFilter];
}
if (options.magFilter !== undefined) {
this._magFilter = options.magFilter;
options.magFilter = FilterIndex[options.magFilter];
}
if (options.mipFilter !== undefined) {
this._mipFilter = options.mipFilter;
options.mipFilter = FilterIndex[options.mipFilter];
}
if (options.wrapS !== undefined) {
this._wrapS = options.wrapS;
}
if (options.wrapT !== undefined) {
this._wrapT = options.wrapT;
}
if (options.format !== undefined) {
this._format = options.format;
}
if (options.flipY !== undefined) {
this._flipY = options.flipY;
}
if (options.premultiplyAlpha !== undefined) {
this._premultiplyAlpha = options.premultiplyAlpha;
}
if (options.anisotropy !== undefined) {
this._anisotropy = options.anisotropy;
}
if (options.mipmap !== undefined) {
this._genMipmap = options.mipmap;
}
}
public _getOpts () {
const opts = _getSharedOptions();
opts.width = this.width;
opts.height = this.height;
opts.mipmap = this._genMipmap;
opts.format = this._format;
opts.premultiplyAlpha = this._premultiplyAlpha;
opts.anisotropy = this._anisotropy;
opts.flipY = this._flipY;
opts.minFilter = FilterIndex[this._minFilter];
opts.magFilter = FilterIndex[this._magFilter];
opts.mipFilter = FilterIndex[this._mipFilter];
opts.wrapS = this._wrapS;
opts.wrapT = this._wrapT;
return opts;
}
/**
* !#en
* Pixel format of the texture.
* !#zh 获取纹理的像素格式。
* @method getPixelFormat
* @return {Number}
* @return
*/
public getPixelFormat () {
// support only in WebGl rendering mode
@@ -412,8 +291,7 @@ export default class TextureBase extends Asset {
* !#en
* Whether or not the texture has their Alpha premultiplied.
* !#zh 检查纹理在上传 GPU 时预乘选项是否开启。
* @method hasPremultipliedAlpha
* @return {Boolean}
* @return
*/
public hasPremultipliedAlpha () {
return this._premultiplyAlpha || false;
@@ -422,8 +300,7 @@ export default class TextureBase extends Asset {
/**
* !#en Anisotropy of the texture.
* !#zh 获取纹理的各向异性。
* @method getAnisotropy
* @return {Number}
* @return
*/
public getAnisotropy () {
return this._anisotropy;
@@ -433,8 +310,7 @@ export default class TextureBase extends Asset {
* !#en
* Whether or not to generate mipmap.
* !#zh 检查纹理在上传 GPU 时是否生成 mipmap。
* @method hasMipmap
* @return {Boolean}
* @return
*/
public genMipmap () {
return this._genMipmap || false;
@@ -445,46 +321,40 @@ export default class TextureBase extends Asset {
* If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}.
* !#zh 设置纹理包装模式。
* 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。
* @method setTexParameters
* @param {WrapMode} wrapS
* @param {WrapMode} wrapT
* @param wrapS
* @param wrapT
*/
public setWrapMode (wrapS, wrapT) {
public setWrapMode (wrapS: WrapMode, wrapT: WrapMode) {
if (this._wrapS !== wrapS || this._wrapT !== wrapT) {
const opts = _getSharedOptions();
opts.wrapS = wrapS;
opts.wrapT = wrapT;
this.update(opts);
this._wrapS = wrapS;
this._wrapT = wrapT;
this._updateSampler();
}
}
/**
* !#en Sets the minFilter and magFilter options
* !#zh 设置纹理贴图缩小和放大过滤器算法选项。
* @method setFilters
* @param {Filter} minFilter
* @param {Filter} magFilter
* @param minFilter
* @param magFilter
*/
public setFilters (minFilter, magFilter) {
public setFilters (minFilter: Filter, magFilter: Filter) {
if (this._minFilter !== minFilter || this._magFilter !== magFilter) {
const opts = _getSharedOptions();
opts.minFilter = minFilter;
opts.magFilter = magFilter;
this.update(opts);
this._minFilter = minFilter;
this._magFilter = magFilter;
this._updateSampler();
}
}
/**
* !#en Sets the mipFilter options
* !#zh 设置纹理Mipmap过滤算法选项。
* @method setMipFilter
* @param {Filter} mipFilter
* @param mipFilter
*/
public setMipFilter (mipFilter) {
public setMipFilter (mipFilter: Filter) {
if (this._mipFilter !== mipFilter) {
const opts = _getSharedOptions();
opts.mipFilter = mipFilter;
this.update(opts);
this._mipFilter = mipFilter;
this._updateSampler();
}
}
@@ -492,14 +362,12 @@ export default class TextureBase extends Asset {
* !#en
* Sets the flipY options
* !#zh 设置贴图的纵向翻转选项。
* @method setFlipY
* @param {Boolean} flipY
* @param flipY
*/
public setFlipY (flipY) {
public setFlipY (flipY: boolean) {
if (this._flipY !== flipY) {
const opts = _getSharedOptions();
opts.flipY = flipY;
this.update(opts);
this._flipY = flipY;
this._updateSampler();
}
}
@@ -507,28 +375,24 @@ export default class TextureBase extends Asset {
* !#en
* Sets the premultiply alpha options
* !#zh 设置贴图的预乘选项。
* @method setPremultiplyAlpha
* @param {Boolean} premultiply
* @param premultiply
*/
public setPremultiplyAlpha (premultiply) {
public setPremultiplyAlpha (premultiply: boolean) {
if (this._premultiplyAlpha !== premultiply) {
const opts = _getSharedOptions();
opts.premultiplyAlpha = premultiply;
this.update(opts);
this._premultiplyAlpha = premultiply;
this._updateSampler();
}
}
/**
* !#en Sets the anisotropy of the texture
* !#zh 设置贴图的各向异性。
* @method setAnisotropy
* @param {number} anisotropy
* @param anisotropy
*/
public setAnisotropy (anisotropy) {
public setAnisotropy (anisotropy: number) {
if (this._anisotropy !== anisotropy) {
const opts = _getSharedOptions();
opts.anisotropy = anisotropy;
this.update(opts);
this._anisotropy = anisotropy;
this._updateSampler();
}
}
@@ -536,23 +400,43 @@ export default class TextureBase extends Asset {
* !#en
* Sets whether generate mipmaps for the texture
* !#zh 是否为纹理设置生成 mipmaps。
* @method setGenerateMipmap
* @param {Boolean} mipmap
* @param mipmap
*/
public setGenMipmap (mipmap) {
public setGenMipmap (mipmap: boolean) {
if (this._genMipmap !== mipmap) {
const opts = _getSharedOptions();
opts.mipmap = mipmap;
this.update(opts);
this._genMipmap = mipmap;
this._updateSampler();
}
}
public destroy () {
this._destroyTexture();
if (this._sampler) {
this._sampler.destroy();
}
return true;
}
public getGFXTexture () {
return this._texture;
}
public getGFXTextureView () {
return this._textureView;
}
public getGFXSampler () {
return this._sampler;
}
// SERIALIZATION
/**
* @return {any}
* @return
*/
public _serialize () {
public _serialize (): any {
return this._minFilter + ',' + this._magFilter + ',' +
this._wrapS + ',' + this._wrapT + ',' +
(this._premultiplyAlpha ? 1 : 0) + ',' +
@@ -563,32 +447,141 @@ export default class TextureBase extends Asset {
/**
*
* @param {string} data
* @param data
*/
public _deserialize (data) {
public _deserialize (serializedData: any, handle: any) {
const data = serializedData as string;
const fields = data.split(',');
fields.unshift('');
if (fields.length >= 6) {
// decode filters
this._minFilter = parseInt(fields[1]);
this._magFilter = parseInt(fields[2]);
this._minFilter = parseInt(fields[1], undefined);
this._magFilter = parseInt(fields[2], undefined);
// decode wraps
this._wrapS = parseInt(fields[3]);
this._wrapT = parseInt(fields[4]);
this._wrapS = parseInt(fields[3], undefined);
this._wrapT = parseInt(fields[4], undefined);
// decode premultiply alpha
this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1;
}
if (fields.length >= 8) {
this._mipFilter = parseInt(fields[6]);
this._anisotropy = parseInt(fields[7]);
this._mipFilter = parseInt(fields[6], undefined);
this._anisotropy = parseInt(fields[7], undefined);
}
if (fields.length >= 10) {
this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1;
this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1;
}
}
protected _getGlobalDevice (): GFXDevice {
return cc.director.root.device;
}
protected _getGfxFormat () {
return toGfxFormat(this._format);
}
protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) {
const upload = () => { this._uploadImage(image, level, arrayIndex); };
// @ts-ignore
if (image.loaded) {
upload();
} else {
// @ts-ignore
image.addEventListener('load', () => {
upload();
});
}
}
protected _uploadImage (image: ImageAsset, level: number, arrayIndex?: number) {
if (!this._texture) {
return;
}
if (level >= this._texture.mipLevel) {
return;
}
const data = image.data;
if (!data) {
return;
}
const region: GFXBufferTextureCopy = {
buffOffset: 0,
buffStride: 0,
buffTexHeight: 0,
texOffset: {
x: 0,
y: 0,
z: 0,
},
texExtent: {
width: this._texture.width,
height: this._texture.height,
depth: 1,
},
texSubres: {
baseMipLevel: level,
levelCount: 1,
baseArrayLayer: arrayIndex || 0,
layerCount: 1,
},
};
if (data instanceof HTMLElement) {
this._getGlobalDevice().copyImageSourceToTexture(data, this._texture, [region]);
} else {
this._getGlobalDevice().copyBufferToTexture(data.buffer, this._texture, [region]);
}
}
protected _recreateTexture () {
this._destroyTexture();
this._createTexture();
if (this._texture) {
this._width = this._texture.width;
this._height = this._texture.height;
}
this._createTextureView();
}
protected _createTexture () {
return;
}
protected _createTextureView () {
return;
}
private _destroyTexture () {
if (this._textureView) {
this._textureView.destroy();
this._textureView = null;
}
if (this._texture) {
this._texture.destroy();
this._texture = null;
}
}
private _updateSampler () {
this._sampler = this._getGlobalDevice().createSampler({
name: `Sampler of ${this.name}`,
minFilter: toGfxFilterMode(this._minFilter),
magFilter: toGfxFilterMode(this._magFilter),
addressU: toGfxAddressMode(this._wrapS),
addressV: toGfxAddressMode(this._wrapT),
maxAnisotropy: this._anisotropy,
});
}
}
/* tslint:disable:no-string-literal */
cc['TextureBase'] = TextureBase;
/**
* !#zh
* 当该资源加载成功后触发该事件
@@ -599,4 +592,3 @@ export default class TextureBase extends Asset {
*/
addon(TextureBase.prototype, EventTarget.prototype);
cc.TextureBase = TextureBase;
+2 -2
View File
@@ -40,8 +40,8 @@ export class CCObject {
protected _destruct(): void;
protected _destroyImmediate(): void;
protected _serialize: (exporting: boolean) => object | null;
protected _deserialize: (data: object, ctx: object) => object | null;
protected _serialize?(): any;
protected _deserialize?(data: any, ctx: any): any;
protected _onPreDestroy: () => void | null;
protected Flags: object;
}
+11
View File
@@ -118,4 +118,15 @@ if (CC_DEV) {
}
}
/**
*
* @param {Object} enumx
*/
export function ccenum(enumx) {
if ('__enums__' in enumx) {
return;
}
js.value(enumx, '__enums__', null, true);
}
cc.Enum = Enum;