diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index a84c01d38d..fbee4f14d1 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -619,7 +619,7 @@ export class Label extends UIRenderer { get outlineColor (): Color { return this._outlineColor; } - set outlineColor (value) { + set outlineColor (value: Readonly) { if (this._outlineColor === value) return; this._outlineColor.set(value); this.markForUpdateRenderData(); @@ -673,7 +673,7 @@ export class Label extends UIRenderer { get shadowColor (): Color { return this._shadowColor; } - set shadowColor (value) { + set shadowColor (value: Readonly) { if (this._shadowColor === value) return; this._shadowColor.set(value); this.markForUpdateRenderData(); diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index 4cb13d13d4..c22a86bf04 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -488,7 +488,10 @@ export class Mask extends Component { get color (): Color | null { warnID(9007); if (this.subComp) { - return this.subComp.color; + // FIXME: the type of subComp is Sprite | graphics, and Sprite.color returns Readonly. + // so have to use as Color here. And i don't want to change the return type to Readonly + // as it will break compatibility. + return this.subComp.color as Color; } return null; } diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index 706d30f656..7e6bac165c 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -95,7 +95,7 @@ export class RenderEntity { // this._renderEntityType = val; // } - protected _color: Color = Color.WHITE; + protected _color: Color = Color.WHITE.clone(); get color (): Color { return this._color; } diff --git a/cocos/3d/lights/light-component.ts b/cocos/3d/lights/light-component.ts index 48db01d921..332bed635e 100644 --- a/cocos/3d/lights/light-component.ts +++ b/cocos/3d/lights/light-component.ts @@ -139,8 +139,8 @@ export class Light extends Component { get color (): Readonly { return this._color; } - set color (val) { - this._color = val; + set color (val: Readonly) { + this._color = val.clone(); if (this._light) { _color_tmp.x = val.r / 255.0; _color_tmp.y = val.g / 255.0; @@ -330,5 +330,7 @@ export class Light extends Component { } } - protected _onUpdateReceiveDirLight (): void {} + protected _onUpdateReceiveDirLight (): void { + // do nothing + } } diff --git a/cocos/3d/reflection-probe/reflection-probe-component.ts b/cocos/3d/reflection-probe/reflection-probe-component.ts index 4e00b7df9b..b0de6dee06 100644 --- a/cocos/3d/reflection-probe/reflection-probe-component.ts +++ b/cocos/3d/reflection-probe/reflection-probe-component.ts @@ -240,7 +240,7 @@ export class ReflectionProbe extends Component { if (camera) { this.visibility = camera.visibility; this.clearFlag = camera.clearFlags; - this.backgroundColor = camera.clearColor; + this.backgroundColor = camera.clearColor as Color; if (this.probeType === ProbeType.PLANAR) { this.probe.switchProbeType(this.probeType, camera.camera); } diff --git a/cocos/core/curves/gradient.ts b/cocos/core/curves/gradient.ts index 9d1b76ac11..faea844750 100644 --- a/cocos/core/curves/gradient.ts +++ b/cocos/core/curves/gradient.ts @@ -151,7 +151,7 @@ export class Gradient { */ public evaluateFast (out: Color, time: number): Color { this.getRGB(out, time); - out._set_a_unsafe(this.getAlpha(time)!); + out.a = this.getAlpha(time)!; return out; } @@ -175,7 +175,7 @@ export class Gradient { const c = this.colorKeys[Math.trunc(random() * this.colorKeys.length)]; const a = this.alphaKeys[Math.trunc(random() * this.alphaKeys.length)]; out.set(c.color); - out._set_a_unsafe(a.alpha); + out.a = a.alpha; return out; } diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index 2c97fb4694..a700bae82a 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -1,6 +1,6 @@ /* Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2023 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2017-2024 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -58,11 +58,10 @@ export class Color extends ValueType { */ public static clone (a: Out): Color { const out = new Color(); - if (a._val) { - out._val = a._val; - } else { - out._val = ((a.a << 24) >>> 0) + (a.b << 16) + (a.g << 8) + a.r; - } + out.r = a.r; + out.g = a.g; + out.b = a.b; + out.a = a.a; return out; } @@ -101,10 +100,10 @@ export class Color extends ValueType { */ public static toVec4 (color: Color, out?: Vec4): Vec4 { out = out !== undefined ? out : new Vec4(); - out.x = color.r * toFloat; - out.y = color.g * toFloat; - out.z = color.b * toFloat; - out.w = color.a * toFloat; + out.x = color._r * toFloat; + out.y = color._g * toFloat; + out.z = color._b * toFloat; + out.w = color._a * toFloat; return out; } /** @@ -118,10 +117,10 @@ export class Color extends ValueType { */ public static fromVec4 (value: Vec4, out?: Color): Color { out = out === undefined ? new Color() : out; - out.r = Math.floor(value.x / toFloat); - out.g = Math.floor(value.y / toFloat); - out.b = Math.floor(value.z / toFloat); - out.a = Math.floor(value.w / toFloat); + out.r = value.x / toFloat; + out.g = value.y / toFloat; + out.b = value.z / toFloat; + out.a = value.w / toFloat; return out; } /** @@ -141,11 +140,11 @@ export class Color extends ValueType { if (hex.length === 6) { hex += 'FF'; } else if (hex.length === 3) { - hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + 'FF'; + hex = `${hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]}FF`; } else if (hex.length === 4) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3]; } - hexNumber = Number('0x' + hex); + hexNumber = Number(`0x${hex}`); } else { if (hex < 0x1000000) { hex = (hex << 8) + 0xff; @@ -156,7 +155,6 @@ export class Color extends ValueType { out.g = (hexNumber & 0x00ff0000) >>> 16; out.b = (hexNumber & 0x0000ff00) >>> 8; out.a = hexNumber & 0x000000ff; - out._val = ((out.a << 24) >>> 0) + (out.b << 16) + (out.g << 8) + out.r; return out; } @@ -226,15 +224,15 @@ export class Color extends ValueType { * @zh 逐通道颜色线性插值:A + t * (B - A) */ public static lerp (out: Out, from: Out, to: Out, ratio: number): Out { - let r = from.r; - let g = from.g; - let b = from.b; - let a = from.a; - r += (to.r - r) * ratio; - g += (to.g - g) * ratio; - b += (to.b - b) * ratio; - a += (to.a - a) * ratio; - out._val = Math.floor(((a << 24) >>> 0) + (b << 16) + (g << 8) + r); + const fromR = from.r; + const fromG = from.g; + const fromB = from.b; + const fromA = from.a; + out.r = fromR + ((to.r - fromR) * ratio); + out.g = fromG + ((to.g - fromG) * ratio); + out.b = fromB + ((to.b - fromB) * ratio); + out.a = fromA + ((to.a - fromA) * ratio); + return out; } @@ -275,7 +273,13 @@ export class Color extends ValueType { * @returns @en The `out` object @zh `out` 对象 */ public static fromUint32 (out: Out, uint32: number): Out { - out._val = uint32; + // Make sure it is an unsigned value. + uint32 >>>= 0; + + out.r = uint32 & 0xff; + out.g = (uint32 >> 8) & 0xff; + out.b = (uint32 >> 16) & 0xff; + out.a = (uint32 >> 24) & 0xff; return out; } @@ -288,7 +292,7 @@ export class Color extends ValueType { * @returns @en The converted unsigned 32 bit integer. @zh 32 位无符号整数。 */ public static toUint32 (color: IColorLike): number { - return color._val; + return (color.a << 24 | color.b << 16 | color.g << 8 | color.r) >>> 0; } /** @@ -319,17 +323,21 @@ export class Color extends ValueType { return ((a.r * 255) << 24 | (a.g * 255) << 16 | (a.b * 255) << 8 | a.a * 255) >>> 0; } + private _r = 0; + private _g = 0; + private _b = 0; + private _a = 0; + /** * @en Get or set red channel value. * @zh 获取或设置当前颜色的 Red 通道。 */ get r (): number { - return this._val & 0x000000ff; + return this._r; } - set r (red) { - red = ~~clamp(red, 0, 255); - this._val = ((this._val & 0xffffff00) | red) >>> 0; + set r (red: number) { + this._r = ~~clamp(red, 0, 255); } /** @@ -337,12 +345,11 @@ export class Color extends ValueType { * @zh 获取或设置当前颜色的 Green 通道。 */ get g (): number { - return (this._val & 0x0000ff00) >> 8; + return this._g; } - set g (green) { - green = ~~clamp(green, 0, 255); - this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; + set g (green: number) { + this._g = ~~clamp(green, 0, 255); } /** @@ -350,47 +357,40 @@ export class Color extends ValueType { * @zh 获取或设置当前颜色的 Blue 通道。 */ get b (): number { - return (this._val & 0x00ff0000) >> 16; + return this._b; } - set b (blue) { - blue = ~~clamp(blue, 0, 255); - this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; + set b (blue: number) { + this._b = ~~clamp(blue, 0, 255); } /** @en Get or set alpha channel value. * @zh 获取或设置当前颜色的透明度通道。 */ get a (): number { - return (this._val & 0xff000000) >>> 24; + return this._a; } - set a (alpha) { - alpha = ~~clamp(alpha, 0, 255); - this._val = ((this._val & 0x00ffffff) | (alpha << 24)) >>> 0; + set a (alpha: number) { + this._a = ~~clamp(alpha, 0, 255); } // compatibility with vector interfaces - get x (): number { return this.r * toFloat; } - set x (value) { this.r = value * 255; } - get y (): number { return this.g * toFloat; } - set y (value) { this.g = value * 255; } - get z (): number { return this.b * toFloat; } - set z (value) { this.b = value * 255; } - get w (): number { return this.a * toFloat; } - set w (value) { this.a = value * 255; } - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _val = 0; + get x (): number { return this._r * toFloat; } + set x (value: number) { this.r = value * 255; } + get y (): number { return this._g * toFloat; } + set y (value: number) { this.g = value * 255; } + get z (): number { return this._b * toFloat; } + set z (value: number) { this.b = value * 255; } + get w (): number { return this._a * toFloat; } + set w (value: number) { this.a = value * 255; } /** * @en Construct a same color from the given color * @zh 构造与指定颜色相等的颜色。 * @param other Specified color */ - constructor (other: Color); + constructor (other: Readonly); /** * @en Construct a color form the hex color string @@ -410,14 +410,14 @@ export class Color extends ValueType { */ constructor (r?: number, g?: number, b?: number, a?: number); - constructor (r?: number | Color | string, g?: number, b?: number, a?: number) { + constructor (r?: number | Readonly | string, g?: number, b?: number, a?: number) { super(); if (typeof r === 'string') { this.fromHEX(r); } else if (g !== undefined) { this.set(r as number, g, b, a); } else { - this.set(r as Color); + this.set(r as Readonly); } } @@ -427,7 +427,10 @@ export class Color extends ValueType { */ public clone (): Color { const ret = new Color(); - ret._val = this._val; + ret._r = this._r; + ret._g = this._g; + ret._b = this._b; + ret._a = this._a; return ret; } @@ -435,10 +438,14 @@ export class Color extends ValueType { * @en Check whether the current color is identical with the given color * @zh 判断当前颜色是否与指定颜色相等。 * @param other Specified color - * @returns Returns `true` when all channels of both colours are equal; otherwise returns `false`. + * @returns Returns `true` when all channels of both colors are equal; otherwise returns `false`. */ - public equals (other: Color): boolean { - return other && this._val === other._val; + public equals (other: Readonly): boolean { + const otherColor = other as Color; + return other && this._r === otherColor._r + && this._g === otherColor._g + && this._b === otherColor._b + && this._a === otherColor._a; } /** @@ -447,21 +454,13 @@ export class Color extends ValueType { * @param to Target color * @param ratio The interpolation coefficient.The range is [0,1]. */ - public lerp (to: Color, ratio: number): Color { - let r = this.r; - let g = this.g; - let b = this.b; - let a = this.a; - r += (to.r - r) * ratio; - g += (to.g - g) * ratio; - b += (to.b - b) * ratio; - a += (to.a - a) * ratio; - this._val = Math.floor(((a << 24) >>> 0) + (b << 16) + (g << 8) + r); + public lerp (to: Readonly, ratio: number): Color { + Color.lerp(this, this, to, ratio); return this; } /** - * @en Convert to string with color informations + * @en Convert to string with color information. * @zh 返回当前颜色的字符串表示。 * @returns A string representation of the current color. */ @@ -513,22 +512,21 @@ export class Color extends ValueType { if (hex.length === 6) { hex += 'FF'; } else if (hex.length === 3) { - hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + 'FF'; + hex = `${hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]}FF`; } else if (hex.length === 4) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3]; } - hexNumber = Number('0x' + hex); + hexNumber = Number(`0x${hex}`); } else { if (hex < 0x1000000) { hex = (hex << 8) + 0xff; } hexNumber = hex; } - const r = hexNumber >>> 24; - const g = (hexNumber & 0x00ff0000) >>> 16; - const b = (hexNumber & 0x0000ff00) >>> 8; - const a = hexNumber & 0x000000ff; - this._val = ((a << 24) >>> 0) + (b << 16) + (g << 8) + r; + this.r = hexNumber >>> 24; + this.g = (hexNumber & 0x00ff0000) >>> 16; + this.b = (hexNumber & 0x0000ff00) >>> 8; + this.a = hexNumber & 0x000000ff; return this; } @@ -537,7 +535,8 @@ export class Color extends ValueType { * @en convert Color to HEX color string. * @zh 转换当前颜色为十六进制颜色字符串。 * @param fmt "#rrggbb" or "#rrggbbaa". - * - `'#rrggbbaa'` obtains the hexadecimal value of the Red, Green, Blue, Alpha channels (**two**, high complement 0) and connects them sequentially. + * - `'#rrggbbaa'` obtains the hexadecimal value of the Red, Green, Blue, + * Alpha channels (**two**, high complement 0) and connects them sequentially. * - `'#rrggbb'` is similar to `'#rrggbbaa'` but does not include the Alpha channel. * @returns the Hex color string * @example @@ -552,9 +551,9 @@ export class Color extends ValueType { const prefix = '0'; // #rrggbb const hex = [ - (this.r < 16 ? prefix : '') + (this.r).toString(16), - (this.g < 16 ? prefix : '') + (this.g).toString(16), - (this.b < 16 ? prefix : '') + (this.b).toString(16), + (this._r < 16 ? prefix : '') + (this._r).toString(16), + (this._g < 16 ? prefix : '') + (this._g).toString(16), + (this._b < 16 ? prefix : '') + (this._b).toString(16), ]; const i = -1; if (fmt === '#rgb') { @@ -562,7 +561,7 @@ export class Color extends ValueType { hex[1] = hex[1][0]; hex[2] = hex[2][0]; } else if (fmt === '#rrggbbaa') { - hex.push((this.a < 16 ? prefix : '') + (this.a).toString(16)); + hex.push((this._a < 16 ? prefix : '') + (this._a).toString(16)); } return hex.join(''); } @@ -578,7 +577,7 @@ export class Color extends ValueType { * ``` */ public toRGBValue (): number { - return this._val & 0x00ffffff; + return (this._b << 16 | this._g << 8 | this._r); } /** @@ -651,10 +650,9 @@ export class Color extends ValueType { break; } } - r *= 255; - g *= 255; - b *= 255; - this._val = ((this.a << 24) >>> 0) + (b << 16) + (g << 8) + (r | 0); + this.r = r * 255; + this.g = g * 255; + this.b = b * 255; return this; } @@ -670,9 +668,9 @@ export class Color extends ValueType { * ``` */ public toHSV (): { h: number; s: number; v: number; } { - const r = this.r * toFloat; - const g = this.g * toFloat; - const b = this.b * toFloat; + const r = this._r * toFloat; + const g = this._g * toFloat; + const b = this._b * toFloat; const hsv = { h: 0, s: 0, v: 0 }; const max = Math.max(r, g, b); const min = Math.min(r, g, b); @@ -705,25 +703,20 @@ export class Color extends ValueType { * @param [a=255] alpha component of the color * @returns Current color. */ - public set(other: Color): Color; + public set(other: Readonly): Color; public set(r?: number, g?: number, b?: number, a?: number): Color; - public set (r?: number | Color, g?: number, b?: number, a?: number): Color { + public set (r?: number | Readonly, g?: number, b?: number, a?: number): Color { if (typeof r === 'object') { - if (r._val != null) { - this._val = r._val; - } else { - g = r.g || 0; - b = r.b || 0; - a = typeof r.a === 'number' ? r.a : 255; - r = r.r || 0; - this._val = ((a << 24) >>> 0) + (b << 16) + (g << 8) + (r | 0); - } + const other = r as Color; + this.r = other._r; + this.g = other._g; + this.b = other._b; + this.a = other._a; } else { - r = r || 0; - g = g || 0; - b = b || 0; - a = typeof a === 'number' ? a : 255; - this._val = ((a << 24) >>> 0) + (b << 16) + (g << 8) + (r | 0); + this.r = r ?? 0; + this.g = g ?? 0; + this.b = b ?? 0; + this.a = a ?? 255; } return this; } @@ -734,43 +727,7 @@ export class Color extends ValueType { * @param other The specified color. */ public multiply (other: Color): Color { - const r = ((this._val & 0x000000ff) * other.r) >> 8; - const g = ((this._val & 0x0000ff00) * other.g) >> 8; - const b = ((this._val & 0x00ff0000) * other.b) >> 8; - const a = ((this._val & 0xff000000) >>> 8) * other.a; - this._val = (a & 0xff000000) | (b & 0x00ff0000) | (g & 0x0000ff00) | (r & 0x000000ff); - return this; - } - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _set_r_unsafe (red: number): Color { - this._val = ((this._val & 0xffffff00) | red) >>> 0; - return this; - } - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _set_g_unsafe (green: number): Color { - this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; - return this; - } - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _set_b_unsafe (blue: number): Color { - this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; - return this; - } - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _set_a_unsafe (alpha: number): Color { - this._val = ((this._val & 0x00ffffff) | (alpha << 24)) >>> 0; + Color.multiply(this, this, other); return this; } } @@ -782,7 +739,7 @@ export function color (other: Color | string): Color; export function color (r?: number, g?: number, b?: number, a?: number): Color; export function color (r?: number | Color | string, g?: number, b?: number, a?: number): Color { - return new Color(r as any, g, b, a); + return new Color(r as number, g, b, a); } legacyCC.color = color; @@ -860,7 +817,7 @@ export function packRGBE (rgb: Vec3): Vec4 { e = clamp(e + 128.0, 0.0, 255.0); } // eslint-disable-next-line no-restricted-properties - const sc = 1.0 / Math.pow(1.1, e - 128.0); + const sc = 1.0 / 1.1 ** (e - 128.0); const encode = clampVec3(rgb.multiplyScalar(sc), new Vec3(0.0, 0.0, 0.0), new Vec3(1.0, 1.0, 1.0)); encode.multiplyScalar(255.0); const encode_rounded = floorVec3(encode).add(stepVec3(encode.subtract(floorVec3(encode)), new Vec3(0.5, 0.5, 0.5))); diff --git a/cocos/core/math/type-define.ts b/cocos/core/math/type-define.ts index e83e48775a..17642da6c1 100644 --- a/cocos/core/math/type-define.ts +++ b/cocos/core/math/type-define.ts @@ -1,25 +1,25 @@ /* - Copyright (c) 2020-2023 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2020-2024 Xiamen Yaji Software Co., Ltd. https://www.cocos.com/ - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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. */ export interface IColorLike { @@ -27,8 +27,6 @@ export interface IColorLike { g: number; b: number; a: number; - _val: number; - } export interface IMat3Like { diff --git a/cocos/dragon-bones/assembler/simple.ts b/cocos/dragon-bones/assembler/simple.ts index 5d579e472d..ba26668e97 100644 --- a/cocos/dragon-bones/assembler/simple.ts +++ b/cocos/dragon-bones/assembler/simple.ts @@ -429,7 +429,7 @@ function updateComponentRenderData (comp: ArmatureDisplay, batcher: Batcher2D): _nodeG = nodeColor.g / 255; _nodeB = nodeColor.b / 255; _nodeA = comp.node._uiProps.opacity; - if (nodeColor._val !== 0xffffffff) { + if (Color.toUint32(nodeColor) !== 0xffffffff) { _handleVal |= NEED_COLOR; } diff --git a/cocos/gfx/base/pipeline-state.editor.ts b/cocos/gfx/base/pipeline-state.editor.ts index 59c17d4265..9d9e4edd56 100644 --- a/cocos/gfx/base/pipeline-state.editor.ts +++ b/cocos/gfx/base/pipeline-state.editor.ts @@ -271,7 +271,7 @@ export class BlendStateEditor { @serializable @editable - public blendColor: Color = Color.WHITE; + public blendColor: Color = Color.WHITE.clone(); @type([BlendTargetEditor]) @serializable diff --git a/cocos/particle-2d/motion-streak-2d-assembler.ts b/cocos/particle-2d/motion-streak-2d-assembler.ts index 160eaaaec1..9879601ed7 100644 --- a/cocos/particle-2d/motion-streak-2d-assembler.ts +++ b/cocos/particle-2d/motion-streak-2d-assembler.ts @@ -36,7 +36,7 @@ const _normal = new Vec2(); const _vec2 = new Vec2(); let QUAD_INDICES; -function normal (out:Vec2, dir:Vec2): Vec2 { +function normal (out: Vec2, dir: Vec2): Vec2 { // get perpendicular out.x = -dir.y; out.y = dir.x; @@ -152,7 +152,6 @@ export const MotionStreakAssembler: IAssembler = { normal(_normal, dir); const da = progress * ca; - const c = ((da << 24) >>> 0) + (cb << 16) + (cg << 8) + cr; let offset = vertexCount; @@ -160,7 +159,7 @@ export const MotionStreakAssembler: IAssembler = { data[offset].y = point.y + _normal.y * stroke; data[offset].u = 1; data[offset].v = progress; - data[offset].color._val = c; + data[offset].color.set(cr, cg, cb, da); offset += 1; @@ -168,7 +167,7 @@ export const MotionStreakAssembler: IAssembler = { data[offset].y = point.y - _normal.y * stroke; data[offset].u = 0; data[offset].v = progress; - data[offset].color._val = c; + data[offset].color.set(cr, cg, cb, da); vertexCount += 2; } @@ -205,7 +204,7 @@ export const MotionStreakAssembler: IAssembler = { } }, - createQuadIndices (comp, indexCount): void { + createQuadIndices (comp: MotionStreak, indexCount: number): void { const renderData = comp.renderData!; const chunk = renderData.chunk; const vid = 0; @@ -251,6 +250,7 @@ export const MotionStreakAssembler: IAssembler = { }, updateColor (comp: MotionStreak): void { + // do nothing }, fillBuffers (comp: MotionStreak, renderer: IBatcher): void { diff --git a/cocos/particle-2d/particle-simulator-2d.ts b/cocos/particle-2d/particle-simulator-2d.ts index def8cb54fa..8436e3b882 100644 --- a/cocos/particle-2d/particle-simulator-2d.ts +++ b/cocos/particle-2d/particle-simulator-2d.ts @@ -79,7 +79,7 @@ class ParticlePool extends js.Pool { const pool = new ParticlePool((par: Particle): void => { par.pos.set(ZERO_VEC2); par.startPos.set(ZERO_VEC2); - par.color._val = 0xFF000000; + par.color.set(0, 0, 0, 255); par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0; par.deltaColor.a = 255; par.size = 0; diff --git a/cocos/particle/models/line-model.ts b/cocos/particle/models/line-model.ts index 4b35293766..00d66215b0 100644 --- a/cocos/particle/models/line-model.ts +++ b/cocos/particle/models/line-model.ts @@ -26,7 +26,7 @@ import { JSB } from 'internal:constants'; import { RenderingSubMesh } from '../../asset/assets/rendering-sub-mesh'; import { DRAW_INFO_SIZE, Buffer, Attribute, BufferInfo, DrawInfo, AttributeName, BufferUsageBit, Format, FormatInfos, MemoryUsageBit, PrimitiveMode } from '../../gfx'; -import { Vec3 } from '../../core'; +import { Color, Vec3 } from '../../core'; import { scene } from '../../render-scene'; import CurveRange from '../animator/curve-range'; import GradientRange from '../animator/gradient-range'; @@ -145,7 +145,7 @@ export class LineModel extends scene.Model { this._vdataF32![offset++] = _temp_v1.x; this._vdataF32![offset++] = _temp_v1.y; this._vdataF32![offset++] = _temp_v1.z; - this._vdataUint32![offset++] = color.evaluate(0, 1)._val; + this._vdataUint32![offset++] = Color.toUint32(color.evaluate(0, 1)); this._vdataF32![offset++] = positions[0].x; this._vdataF32![offset++] = positions[0].y; this._vdataF32![offset++] = positions[0].z; @@ -156,7 +156,7 @@ export class LineModel extends scene.Model { this._vdataF32![offset++] = _temp_v1.x; this._vdataF32![offset++] = _temp_v1.y; this._vdataF32![offset++] = _temp_v1.z; - this._vdataUint32![offset++] = color.evaluate(0, 1)._val; + this._vdataUint32![offset++] = Color.toUint32(color.evaluate(0, 1)); for (let i = 1; i < positions.length - 1; i++) { Vec3.subtract(_temp_v1, positions[i - 1], positions[i]); Vec3.subtract(_temp_v2, positions[i + 1], positions[i]); @@ -172,7 +172,7 @@ export class LineModel extends scene.Model { this._vdataF32![offset++] = _temp_v2.x; this._vdataF32![offset++] = _temp_v2.y; this._vdataF32![offset++] = _temp_v2.z; - this._vdataUint32![offset++] = color.evaluate(seg, 1)._val; + this._vdataUint32![offset++] = Color.toUint32(color.evaluate(seg, 1)); this._vdataF32![offset++] = positions[i].x; this._vdataF32![offset++] = positions[i].y; this._vdataF32![offset++] = positions[i].z; @@ -183,7 +183,7 @@ export class LineModel extends scene.Model { this._vdataF32![offset++] = _temp_v2.x; this._vdataF32![offset++] = _temp_v2.y; this._vdataF32![offset++] = _temp_v2.z; - this._vdataUint32![offset++] = color.evaluate(seg, 1)._val; + this._vdataUint32![offset++] = Color.toUint32(color.evaluate(seg, 1)); } Vec3.subtract(_temp_v1, positions[positions.length - 1], positions[positions.length - 2]); this._vdataF32![offset++] = positions[positions.length - 1].x; @@ -196,7 +196,7 @@ export class LineModel extends scene.Model { this._vdataF32![offset++] = _temp_v1.x; this._vdataF32![offset++] = _temp_v1.y; this._vdataF32![offset++] = _temp_v1.z; - this._vdataUint32![offset++] = color.evaluate(1, 1)._val; + this._vdataUint32![offset++] = Color.toUint32(color.evaluate(1, 1)); this._vdataF32![offset++] = positions[positions.length - 1].x; this._vdataF32![offset++] = positions[positions.length - 1].y; this._vdataF32![offset++] = positions[positions.length - 1].z; @@ -207,7 +207,7 @@ export class LineModel extends scene.Model { this._vdataF32![offset++] = _temp_v1.x; this._vdataF32![offset++] = _temp_v1.y; this._vdataF32![offset++] = _temp_v1.z; - this._vdataUint32![offset++] = color.evaluate(1, 1)._val; + this._vdataUint32![offset++] = Color.toUint32(color.evaluate(1, 1)); } this.updateIA(Math.max(0, positions.length - 1)); } diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index ec93e74857..ff5e67b23d 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -184,7 +184,7 @@ export default class ParticleBatchModel extends scene.Model { if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSize, vOffset as number)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { - vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color.WHITE._val; + vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color.toUint32(Color.WHITE); } } const vbFloatArray = new Float32Array(vBuffer); @@ -280,7 +280,7 @@ export default class ParticleBatchModel extends scene.Model { if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSizeStatic, vOffset as number)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { - vb[iVertex * this._vertStaticAttrsFloatCount + vOffset / 4] = Color.WHITE._val; + vb[iVertex * this._vertStaticAttrsFloatCount + vOffset / 4] = Color.toUint32(Color.WHITE); } } } else { diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 0f91aae63a..672fd524bc 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -26,13 +26,12 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants'; import { builtinResMgr } from '../../asset/asset-manager'; import { Material, Texture2D } from '../../asset/assets'; import { AttributeName, Format, Attribute, FormatInfos } from '../../gfx'; -import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat, EPSILON, approx, RecyclePool, warn } from '../../core'; +import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat, EPSILON, approx, RecyclePool, warn, Color } from '../../core'; import { MaterialInstance, IMaterialInstanceInfo } from '../../render-scene/core/material-instance'; import { MacroRecord } from '../../render-scene/core/pass-utils'; import { AlignmentSpace, RenderMode, Space } from '../enum'; import { Particle, IParticleModule, PARTICLE_MODULE_ORDER, PARTICLE_MODULE_NAME } from '../particle'; import { ParticleSystemRendererBase } from './particle-system-renderer-base'; -import { Component } from '../../scene-graph'; import { Camera } from '../../render-scene/scene/camera'; import { Pass } from '../../render-scene'; import { ParticleNoise } from '../noise'; @@ -540,7 +539,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); Vec3.copy(this._particleVertexData.size, p.size); Vec3.copy(this._particleVertexData.rotation, p.rotation); - this._particleVertexData.color = p.color._val; + this._particleVertexData.color = Color.toUint32(p.color); this._model!.addParticleVertexData(i, this._particleVertexData); } @@ -554,7 +553,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); Vec3.copy(this._particleVertexData.size, p.size); Vec3.copy(this._particleVertexData.rotation, p.rotation); - this._particleVertexData.color = p.color._val; + this._particleVertexData.color = Color.toUint32(p.color); this._particleVertexData.velocity = p.ultimateVelocity; this._model!.addParticleVertexData(idx++, this._particleVertexData); } @@ -570,7 +569,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); Vec3.copy(this._particleVertexData.size, p.size); Vec3.copy(this._particleVertexData.rotation, p.rotation); - this._particleVertexData.color = p.color._val; + this._particleVertexData.color = Color.toUint32(p.color); this._particleVertexData.velocity = p.ultimateVelocity; this._model!.addParticleVertexData(i, this._particleVertexData); } @@ -585,7 +584,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); Vec3.copy(this._particleVertexData.size, p.size); Vec3.copy(this._particleVertexData.rotation, p.rotation); - this._particleVertexData.color = p.color._val; + this._particleVertexData.color = Color.toUint32(p.color); this._model!.addParticleVertexData(idx++, this._particleVertexData); } } else { @@ -600,7 +599,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.copy(this._particleVertexData.texcoord, _tempAttribUV); Vec3.copy(this._particleVertexData.size, p.size); Vec3.copy(this._particleVertexData.rotation, p.rotation); - this._particleVertexData.color = p.color._val; + this._particleVertexData.color = Color.toUint32(p.color); this._model!.addParticleVertexData(i, this._particleVertexData); } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index 3dad5a3d74..f2f3bc11e5 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -562,8 +562,14 @@ export default class TrailModule { for (let i = trailSeg.start + 1; i < end; i++) { const segEle = trailSeg.trailElements[i % trailSeg.trailElements.length]; const j = i - trailSeg.start; - this._fillVertexBuffer(segEle, this.colorOverTrail.evaluate(1 - j / trailNum, 1), - indexOffset, 1 - j * textCoordSeg, j, PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX); + this._fillVertexBuffer( + segEle, + this.colorOverTrail.evaluate(1 - j / trailNum, 1), + indexOffset, + 1 - j * textCoordSeg, + j, + PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX, + ); } if (this._needTransform) { Vec3.transformMat4(_temp_trailEle.position, p.position, this._psTransform); @@ -602,8 +608,14 @@ export default class TrailModule { this.vbOffset -= this._vertSize / 4 * 2; this.ibOffset -= 6; // _bcIdx = (_bcIdx - 6 + 9) % 9; // - this._fillVertexBuffer(lastSecondTrail, this.colorOverTrail.evaluate(textCoordSeg, 1), indexOffset, - textCoordSeg, trailNum - 1, PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX); + this._fillVertexBuffer( + lastSecondTrail, + this.colorOverTrail.evaluate(textCoordSeg, 1), + indexOffset, + textCoordSeg, + trailNum - 1, + PRE_TRIANGLE_INDEX | NEXT_TRIANGLE_INDEX, + ); Vec3.subtract(_temp_trailEle.velocity, _temp_trailEle.position, lastSecondTrail.position); Vec3.normalize(_temp_trailEle.velocity, _temp_trailEle.velocity); this._checkDirectionReverse(_temp_trailEle, lastSecondTrail); @@ -702,8 +714,14 @@ export default class TrailModule { return trailEle.lifetime > module._trailLifetime; } - private _fillVertexBuffer (trailSeg: ITrailElement, colorModifer: Color, indexOffset: number, - xTexCoord: number, trailEleIdx: number, indexSet: number): void { + private _fillVertexBuffer ( + trailSeg: ITrailElement, + colorModifer: Color, + indexOffset: number, + xTexCoord: number, + trailEleIdx: number, + indexSet: number, + ): void { this._vbF32![this.vbOffset++] = trailSeg.position.x; this._vbF32![this.vbOffset++] = trailSeg.position.y; this._vbF32![this.vbOffset++] = trailSeg.position.z; @@ -720,7 +738,7 @@ export default class TrailModule { this._vbF32![this.vbOffset++] = trailSeg.velocity.z; _temp_color.set(trailSeg.color); _temp_color.multiply(colorModifer); - this._vbUint32![this.vbOffset++] = _temp_color._val; + this._vbUint32![this.vbOffset++] = Color.toUint32(_temp_color); this._vbF32![this.vbOffset++] = trailSeg.position.x; this._vbF32![this.vbOffset++] = trailSeg.position.y; this._vbF32![this.vbOffset++] = trailSeg.position.z; @@ -735,7 +753,7 @@ export default class TrailModule { this._vbF32![this.vbOffset++] = trailSeg.velocity.x; this._vbF32![this.vbOffset++] = trailSeg.velocity.y; this._vbF32![this.vbOffset++] = trailSeg.velocity.z; - this._vbUint32![this.vbOffset++] = _temp_color._val; + this._vbUint32![this.vbOffset++] = Color.toUint32(_temp_color); if (indexSet & PRE_TRIANGLE_INDEX) { this._iBuffer![this.ibOffset++] = indexOffset + 2 * trailEleIdx; this._iBuffer![this.ibOffset++] = indexOffset + 2 * trailEleIdx - 1; diff --git a/cocos/render-scene/scene/fog.ts b/cocos/render-scene/scene/fog.ts index 36a6f504ac..a0b95e7454 100644 --- a/cocos/render-scene/scene/fog.ts +++ b/cocos/render-scene/scene/fog.ts @@ -114,7 +114,7 @@ export class Fog { * @zh 全局雾颜色 * @en Global fog color */ - set fogColor (val: Color) { + set fogColor (val: Readonly) { this._fogColor.set(val); _v4.set(val.x, val.y, val.z, val.w); diff --git a/cocos/render-scene/scene/shadows.ts b/cocos/render-scene/scene/shadows.ts index 3ad6037c6c..a4dc798047 100644 --- a/cocos/render-scene/scene/shadows.ts +++ b/cocos/render-scene/scene/shadows.ts @@ -370,7 +370,7 @@ export class Shadows { this.normal = shadowsInfo.planeDirection; this.distance = shadowsInfo.planeHeight; this.planeBias = shadowsInfo.planeBias; - this.shadowColor = shadowsInfo.shadowColor; + this.shadowColor = shadowsInfo.shadowColor as Color; this.maxReceived = shadowsInfo.maxReceived; if (shadowsInfo.shadowMapSize !== this._size.x) { this.size.set(shadowsInfo.shadowMapSize, shadowsInfo.shadowMapSize); diff --git a/cocos/scene-graph/scene-globals.ts b/cocos/scene-graph/scene-globals.ts index 870e365763..08ef6ee848 100644 --- a/cocos/scene-graph/scene-globals.ts +++ b/cocos/scene-graph/scene-globals.ts @@ -894,7 +894,7 @@ export class ShadowsInfo { @visible(function (this: ShadowsInfo) { return this._type === ShadowType.Planar; }) set shadowColor (val: Readonly) { this._shadowColor.set(val); - if (this._resource) { this._resource.shadowColor = val; } + if (this._resource) { this._resource.shadowColor = val as Color; } } get shadowColor (): Readonly { return this._shadowColor; diff --git a/cocos/serialization/compiled/builtin-value-type.ts b/cocos/serialization/compiled/builtin-value-type.ts index c6b4afb7e7..32d3e38d47 100644 --- a/cocos/serialization/compiled/builtin-value-type.ts +++ b/cocos/serialization/compiled/builtin-value-type.ts @@ -55,7 +55,7 @@ const setterMap: SetterMap = [ vec4LikeSetter, // Vec4 vec4LikeSetter, // Quat (obj: Color, data: SetterInput): void => { - obj._val = data[1]; + Color.fromUint32(obj, data[1]); }, (obj: Size, data: SetterInput): void => { obj.width = data[1]; @@ -84,7 +84,7 @@ export function serializeBuiltinValueType (obj: ValueType): ValueTypeData | null case Quat: return [typeId, (obj as Vec4).x, (obj as Vec4).y, (obj as Vec4).z, (obj as Vec4).w]; case Color: - return [typeId, (obj as Color)._val]; + return [typeId, Color.toUint32((obj as Color))]; case Size: return [typeId, (obj as Size).width, (obj as Size).height]; case Rect: diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index 40cb2296df..1a6e99b059 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -279,7 +279,7 @@ function cacheTraverse (comp: Skeleton): void { vUint8Buf.set(model.vData as TypedArray); const nodeColor = comp.color; - if (nodeColor._val !== 0xffffffff || _premultipliedAlpha) { + if (Color.toUint32(nodeColor) !== 0xffffffff || _premultipliedAlpha) { _nodeR = nodeColor.r / 255; _nodeG = nodeColor.g / 255; _nodeB = nodeColor.b / 255; diff --git a/tests/animation/animation-clip.test.ts b/tests/animation/animation-clip.test.ts index 289de638fb..973b962882 100644 --- a/tests/animation/animation-clip.test.ts +++ b/tests/animation/animation-clip.test.ts @@ -1,6 +1,6 @@ -import { Color, js, lerp, Quat, Rect, Size, Vec2, Vec3, Vec4 } from '../../cocos/core'; +import { Color, js, lerp, Size, Vec2, Vec3, Vec4 } from '../../cocos/core'; import { AnimationClip, AnimationState, AnimationManager } from '../../cocos/animation'; -import { AnimationController, ColorTrack, ComponentPath, HierarchyPath, IValueProxyFactory, RealTrack, SizeTrack, Track, VectorTrack } from '../../cocos/animation/animation'; +import { ColorTrack, ComponentPath, HierarchyPath, IValueProxyFactory, RealTrack, SizeTrack, Track, VectorTrack } from '../../cocos/animation/animation'; import { ccclass } from 'cc.decorator'; import { captureErrorIDs, captureWarnIDs } from '../utils/log-capture'; import { Node,Component } from '../../cocos/scene-graph'; diff --git a/tests/core/math/color.test.ts b/tests/core/math/color.test.ts index 6dc1a5edb8..1d399fd30b 100644 --- a/tests/core/math/color.test.ts +++ b/tests/core/math/color.test.ts @@ -1,25 +1,32 @@ import { Vec4 } from '../../../cocos/core'; import { Color, linearToSrgb8Bit, srgb8BitToLinear, srgbToLinear } from '../../../cocos/core/math/color'; +function colorEqualTest(color1: Color, color2: Color): void { + expect(color1.r).toBe(color2.r); + expect(color1.g).toBe(color2.g); + expect(color1.b).toBe(color2.b); + expect(color1.a).toBe(color2.a); +} + // test Color describe('Test Color', () => { test('clone', () => { const color = new Color(128, 234, 0, 255); const color2 = color.clone(); - expect(color2._val).toBe(color._val); + colorEqualTest(color, color2); }); test('copy', () => { const color = new Color(128, 234, 0, 255); const color2 = new Color(); Color.copy(color2, color); - expect(color2._val).toBe(color._val); + colorEqualTest(color, color2); }); test('set', () => { const color = new Color(128, 234, 0, 255); const color2 = new Color(); Color.set(color2, color.r, color.g, color.b, color.a); - expect(color2._val).toBe(color._val); + colorEqualTest(color, color2); }); test('fromHex', () => { const hexColor = ['#ff000000', '#00ff0000', '#0000ff00', '#ffffff00', '#00000000', '#ff00ff00', '#00ffff00', '#ffff0000']; @@ -65,6 +72,7 @@ describe('Test Color', () => { expect(color3.a).toBe(0); }); test('multiply', () => { + // test static function const color = new Color(128, 234, 10, 255); const color2 = new Color(128, 234, 20, 255); const color3 = new Color(); @@ -73,6 +81,13 @@ describe('Test Color', () => { expect(color3.g).toBe(255); expect(color3.b).toBe(200); expect(color3.a).toBe(255); + + // test object function + color.multiply(color2); + expect(color.r).toBe(255); + expect(color.g).toBe(255); + expect(color.b).toBe(200); + expect(color.a).toBe(255); }); test('divide', () => { const color = new Color(128, 234, 10, 255); @@ -94,6 +109,7 @@ describe('Test Color', () => { expect(color2.a).toBe(255); }); test('lerp', () => { + // static function version const color = new Color(1, 235, 15, 255); const color2 = new Color(255, 255, 255, 255); const color3 = new Color(); @@ -102,6 +118,13 @@ describe('Test Color', () => { expect(color3.g).toBe(245); expect(color3.b).toBe(135); expect(color3.a).toBe(255); + + // object method version + color.lerp(color2, 0.5); + expect(color.r).toBe(128); + expect(color.g).toBe(245); + expect(color.b).toBe(135); + expect(color.a).toBe(255); }); test('toArray', () => { const color = new Color(1, 235, 15, 255); @@ -159,11 +182,11 @@ describe('Test Color', () => { const testHexRGBA = testColor.toHEX('#rrggbbaa'); const color1 = new Color(); color1.fromHEX(testHexRGBA); - expect(color1._val).toBe(testColor._val); + colorEqualTest(testColor, color1); const color2 = new Color(); Color.fromHEX(color2, testHexRGBA); - expect(color2._val).toBe(testColor._val); + colorEqualTest(testColor, color2); const testHexRGB = testColor.toHEX('#rrggbb'); const color3 = new Color(); @@ -172,7 +195,7 @@ describe('Test Color', () => { const color4 = new Color(); Color.fromHEX(color4, testHexRGB); - expect(color4._val).toBe(color3._val); + colorEqualTest(color3, color4); }); }); @@ -198,14 +221,13 @@ describe('Test Color', () => { expect(color.g).toBe(val >> 8 & 0xFF); expect(color.b).toBe(val >> 16 & 0xFF); expect(color.a).toBe(val >> 24 & 0xFF); - expect(color._val).toBe(val); } }); test('toUint32', () => { const color = new Color(); for (let i = 0; i != 100; i++) { - const val = (Math.random() * 0xFFFFFFFF) | 0; + const val = (Math.random() * 0xFFFFFFFF) >>> 0; Color.fromUint32(color, val); expect(Color.toUint32(color)).toBe(val); } diff --git a/tests/tween/tween.test.ts b/tests/tween/tween.test.ts index 9c968710da..d01e532304 100644 --- a/tests/tween/tween.test.ts +++ b/tests/tween/tween.test.ts @@ -1,4 +1,4 @@ -import { Vec3, System, size, Size, approx } from "../../cocos/core"; +import { Vec3, System, size, Size, approx, color, Color } from "../../cocos/core"; import { tween, Tween, TweenSystem } from "../../cocos/tween"; import { Node, Scene } from "../../cocos/scene-graph"; import { Component } from "../../cocos/scene-graph/component"; @@ -7,6 +7,7 @@ import { UITransform } from "../../cocos/2d/framework/ui-transform"; import { Canvas } from "../../cocos/2d/framework/canvas"; import { Batcher2D } from "../../cocos/2d/renderer/batcher-2d"; import { UIOpacity } from "../../cocos/2d"; +import { Sprite } from "../../cocos/2d"; function isSizeEqualTo(a: Size, b: Size) { return approx(a.width, b.width) && approx(a.height, b.height); @@ -976,7 +977,6 @@ test('sequence', function () { } // @ts-expect-error access private property const action = tweenact._actions[0] as TweenAction; - // @ts-expect-error access private property const props = action._props; for (const property in props) { const prop = props[property]; @@ -1022,5 +1022,50 @@ test('reverseTime', function () { expect(node.position.equals(new Vec3(0, 0, 0))).toBeTruthy(); expect(completed).toBeTruthy(); + director.unregisterSystem(sys); +}); + +test('tween color', function () { + const sys = new TweenSystem(); + (TweenSystem.instance as any) = sys; + director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM); + + const node = new Node(); + const sprite: Sprite = node.addComponent(Sprite); + sprite.color.set(255, 255, 255, 255); + + let isComplete = false; + const t = tween(node.getComponent(Sprite) as Sprite) + .to(1, { color: color(0, 0, 0, 0) }, { + onComplete (target?: object) { + isComplete = true; + }, + + }) + .start(); + + // Pass 1/3 time, 255 get 174 remain: 255 * (1 - 1/3 + 1/60) = 174.24 ≈ 174 + for (let i = 0; i < 20; ++i) { + game.step(); + } + expect(sprite.color.equals(color(174, 174, 174, 174))).toBeTruthy(); + + // Pass 2/3 time, 255 get 89 remain: 255 * (1 - 2/3 + 1/60) = 89.24 ≈ 89 + for (let i = 0; i < 20; ++i) { + game.step(); + } + expect(sprite.color.equals(color(89, 89, 89, 89))).toBeTruthy(); + + // Pass the whole time, 255 get 4 remain: 255 * (1 - 1 + 1/60) = 4.25 ≈ 4 + for (let i = 0; i < 20; ++i) { + game.step(); + } + expect(sprite.color.equals(color(4, 4, 4, 4))).toBeTruthy(); + + // Do the last step + game.step(); + expect(sprite.color.equals(color(0, 0, 0, 0))).toBeTruthy(); + expect(isComplete).toBeTruthy();; + director.unregisterSystem(sys); }); \ No newline at end of file diff --git a/tests/value-types/color.test.ts b/tests/value-types/color.test.ts index bc30b5e0f2..c37c9477f0 100644 --- a/tests/value-types/color.test.ts +++ b/tests/value-types/color.test.ts @@ -4,11 +4,11 @@ const white = Number.parseInt('ffffffff', 16); test('creation test', function () { let c0 = new Color(255, 255, 255, 255); - expect(c0._val).toBe(white); + expect(Color.toUint32(c0)).toBe(white); c0.r = 0; c0.b = 127.5; let c1 = new Color(c0); - expect(c1._val).toBe(Number.parseInt('ff7fff00', 16)); + expect(Color.toUint32(c1)).toBe(Number.parseInt('ff7fff00', 16)); let c2 = new Color('#ffff087f'); expect(c2.r).toBe(255); expect(c2.g).toBe(255); @@ -26,11 +26,11 @@ test('value test', function () { expect(c0.r).toBe(255); c0.g = 300; expect(c0.g).toBe(255); - expect(c0._val).toBe(Number.parseInt('ff00ffff', 16)); + expect(Color.toUint32(c0)).toBe(Number.parseInt('ff00ffff', 16)); c0.r = 16; c0.a = -1; expect(c0.a).toBe(0); - expect(c0._val).toBe(Number.parseInt('0000ff10', 16)); + expect(Color.toUint32(c0)).toBe(Number.parseInt('0000ff10', 16)); let c1 = new Color(16, 255, 0, 0); expect(c0).toEqual(c1); });