From 607a1a5d2d43109a438df04332beccaf6be7018b Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Wed, 21 Jun 2023 17:43:07 +0800 Subject: [PATCH] Serialize BufferAsset as CCON --- cocos/asset/assets/buffer-asset.ts | 52 +++++++++++++++++------------- 1 file changed, 30 insertions(+), 22 deletions(-) diff --git a/cocos/asset/assets/buffer-asset.ts b/cocos/asset/assets/buffer-asset.ts index c22ac469ba8..70da8d1367e 100644 --- a/cocos/asset/assets/buffer-asset.ts +++ b/cocos/asset/assets/buffer-asset.ts @@ -22,8 +22,8 @@ THE SOFTWARE. */ -import { ccclass, override } from 'cc.decorator'; -import { assertIsNonNullable, cclegacy } from '../../core'; +import { ccclass, override, serializable } from 'cc.decorator'; +import { cclegacy } from '../../core'; import { Asset } from './asset'; /** @@ -35,36 +35,44 @@ import { Asset } from './asset'; */ @ccclass('cc.BufferAsset') export class BufferAsset extends Asset { - private _buffer: ArrayBuffer | null = null; - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @zh 缓冲数据的字节视图。 + * @en Byte view of the buffered data. */ - @override - get _nativeAsset () { - return this._buffer as ArrayBuffer; + get bytes () { + return this._bytes; } - set _nativeAsset (bin: ArrayBufferView | ArrayBuffer) { - if (bin instanceof ArrayBuffer) { - this._buffer = bin; - } else { - this._buffer = bin.buffer; - } + + set bytes (value) { + this._bytes = value; + this._bytesLegacy = undefined; } /** - * @zh 获取此资源中的缓冲数据。 - * @en Get the ArrayBuffer data of this asset. - * @returns @en The ArrayBuffer. @zh 缓冲数据。 + * @zh **复制** `this.bytes`,并返回副本的 `ArrayBuffer`。 + * @en **Clones** `this.bytes` and returns `ArrayBuffer` of the copy. + * @returns @en The `ArrayBuffer`. @zh `ArrayBuffer`。 + * @deprecated @zh 自 3.9.0,此方法废弃,调用此方法将带来可观的性能开销;请转而使用 `this.bytes`。 + * @en Since 3.9.0, this method is deprecated. + * Invocation on this method leads to significate cost. Use `this.bytes` instead. */ public buffer () { - assertIsNonNullable(this._buffer); - return this._buffer; + if (!this._bytesLegacy) { + this._bytesLegacy = new Uint8Array(this.bytes); + } + return this._bytesLegacy.buffer; } - public validate () { - return !!this._buffer; - } + @serializable + private _bytes: Uint8Array = new Uint8Array(); + + /** + * This field is preserved here for compatibility purpose: + * prior to 3.9.0, `buffer()` returns `ArrayBuffer`. + * We can't directly returns `this._bytes` in `this.buffer()` + * since `this._bytes` does not view entire underlying buffer. + */ + private _bytesLegacy: undefined | Uint8Array = undefined; } cclegacy.BufferAsset = BufferAsset;