diff --git a/cocos/3d/assets/animation-clip.js b/cocos/3d/assets/animation-clip.js deleted file mode 100644 index 432d15bbe2..0000000000 --- a/cocos/3d/assets/animation-clip.js +++ /dev/null @@ -1,398 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -// @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import { Asset } from "../../assets/asset"; -import vec3 from "../../core/vmath/vec3"; -import quat from "../../core/vmath/quat"; -import { clamp } from "../../core/vmath/utils"; - -/** - * @typedef {import("../framework/skeleton-instance").SkeletonMask} SkeletonMask - * @typedef {import("../../scene-graph/node").default} Node - */ - -let tmpvec3 = vec3.create(0, 0, 0); -let tmpquat = quat.create(); - -function _binaryIndexOf(array, key) { - let lo = 0; - let hi = array.length - 1; - let mid; - - while (lo <= hi) { - mid = ((lo + hi) >> 1); - let val = array[mid]; - - if (val < key) { - lo = mid + 1; - } else if (val > key) { - hi = mid - 1; - } else { - return mid; - } - } - - return lo; -} - -@ccclass('cc.AnimationChannel') -export class AnimationChannel { - /** - * Target node's path into virtual hierarchy. - * @type {string} - */ - @property - target = ""; - - /** - * Target node's position animation curve. - * @type {cc.Vec3[]} - */ - @property - positionCurve = []; - - /** - * Target node's scale animation curve. - * @type {cc.Vec3[]} - */ - @property - scaleCurve = []; - - /** - * Target node's rotation animation curve. - * @type {cc.Quat[]} - */ - @property - rotationCurve = []; -} -cc.AnimationChannel = AnimationChannel; - -@ccclass('cc.AnimationFrame') -export class AnimationFrame { - @property - _name = ""; - - /** - * @type {AnimationChannel[]} - */ - @property - _channels = []; - - /** - * @type {number[]} - */ - @property - _times = []; - - get channels() { - return this._channels; - } - - get times() { - return this._times; - } -} -cc.AnimationFrame = AnimationFrame; - -@ccclass('cc.AnimationClip') -export default class AnimationClip extends Asset { - /** - * @type {AnimationFrame[]} - */ - @property - _frames = []; - - /** - * @type {number} - */ - @property - _length = 0.0; - - get frames() { - return this._frames; - } - - get length() { - return this._length; - } -} -cc.AnimationClip = AnimationClip; - -export class AnimationTarget { - constructor() { - /** - * @type {Node[]} - */ - this._nodes = []; - - /** - * @type {Map} - */ - this._pathMap = new Map(); - } - - add(path, node) { - if (this._pathMap.has(path)) { - return; - } - const index = this._nodes.length; - this._nodes.push(node); - this._pathMap.set(path, index); - } - - get(path) { - return this._pathMap.get(path); - } - - get nodes() { - return this._nodes; - } - - getDefaultPosition(nodeIndex) { - return this._nodes[nodeIndex].getPosition(); - //return this._defaultPositions[nodeIndex]; - } - - getDefaultScale(nodeIndex) { - return this._nodes[nodeIndex].getScale(); - //return this._defaultScales[nodeIndex]; - } - - getDefaultRotation(nodeIndex) { - return this._nodes[nodeIndex].getRotation(); - //return this._defaultRotations[nodeIndex]; - } - - // _saveDefaultTRS() { - // this._defaultPositions = new Array(this._nodes.length); - // this._defaultScales = new Array(this._nodes.length); - // this._defaultRotations = new Array(this._nodes.length); - // this._nodes.forEach((node, index) => { - // this._defaultPositions[index] = node.getPosition(); - // this._defaultScales[index] = node.getScale(); - // this._defaultRotations[index] = node.getRotation(); - // }); - // } -} - -/** - * The AnimationTarget class represents the progress of blended sampling. - */ -export class AnimationSampler { - /** - * - * @param {AnimationTarget} animationTarget - */ - constructor(animationTarget) { - /** - * @type {AnimationTarget} - */ - this._animationTarget = animationTarget; - - const targetNodes = this._animationTarget.nodes; - /** - * @type {NodeSamplingState[]} - */ - this._nodeSamplingStates = new Array(targetNodes.length); - this._animationTarget.nodes.forEach((targetNode, index) => { - this._nodeSamplingStates[index] = new NodeSamplingState( - targetNode, - this._animationTarget.getDefaultPosition(index), - this._animationTarget.getDefaultScale(index), - this._animationTarget.getDefaultRotation(index)); - }); - } - - /** - * Resets this state to get sampling start. - */ - reset() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.reset()); - } - - /** - * Updates the sampling result. - */ - apply() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.apply()); - } - - /** Sample data of this animation clip in a specific time and blend that data - * with a weight together with previous data(if exist, or blank if not exists) sampled before. - * - * @param {AnimationClip} clip - * @param {Number} t The time. - * @param {Number} weight The weight. - * @param {SkeletonMask} [mask] The skeleton mask. - */ - sample(clip, t, weight, mask) { - t = clamp(t, 0, clip.length); - - const getState = /** @param {AnimationChannel} [channel] */(channel) => { - return this._nodeSamplingStates[this._animationTarget.get(channel.target)]; - }; - - clip.frames.forEach((frame) => { - let idx = 0; - if (frame.times.length != 1) - idx = _binaryIndexOf(frame.times, t); - if (idx == 0) { - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - nodeSamlingState.blendPosition(channel.positionCurve[0], weight); - } - if (channel.rotationCurve.length != 0) { - nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); - } - if (channel.scaleCurve.length != 0) { - nodeSamlingState.blendScale(channel.scaleCurve[0], weight); - } - }); - } - else { - let loIdx = Math.max(idx - 1, 0); - let hiIdx = Math.min(idx, frame.times.length); - let ratio = (t - frame.times[loIdx]) / (frame.times[hiIdx] - frame.times[loIdx]); - - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - let a = channel.positionCurve[loIdx]; - let b = channel.positionCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendPosition(tmpvec3, weight); - } - if (channel.rotationCurve.length != 0) { - let a = channel.rotationCurve[loIdx]; - let b = channel.rotationCurve[hiIdx]; - quat.slerp(tmpquat, a, b, ratio); - nodeSamlingState.blendRotation(tmpquat, weight); - } - if (channel.scaleCurve.length != 0) { - let a = channel.scaleCurve[loIdx]; - let b = channel.scaleCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendScale(tmpvec3, weight); - } - }); - } - }); - } -} - -class NodeSamplingState { - /** - * - * @param {Node} target - * @param {cc.Vec3} defaultPosition - * @param {cc.Vec3} defaultScale - * @param {cc.Quat} defaultRotation - */ - constructor(target, defaultPosition, defaultScale, defaultRotation) { - /** - * @type {Node} - */ - this._target = target; - - /** - * @type {cc.Vec3} - */ - this._defaultPosition = defaultPosition; - - /** - * @type {cc.Vec3} - */ - this._defaultScale = defaultScale; - - /** - * @type {cc.Quat} - */ - this._defaultRotation = defaultRotation; - } - - reset() { - /** - * @type {Number} - */ - this._sumPosWeight = 0.0; - - /** - * @type {Number} - */ - this._sumScaleWeight = 0.0; - - /** - * @type {Number} - */ - this._sumRotWeight = 0.0; - this._target.setPosition(0, 0, 0); - this._target.setScale(0, 0, 0); - this._target.setRotation(0, 0, 0, 1); - } - - blendPosition(pos, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lpos, pos, weight); - this._target.setPosition(tmpvec3); - this._sumPosWeight += weight; - } - - blendScale(scale, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lscale, scale, weight); - this._target.setScale(tmpvec3); - this._sumScaleWeight += weight; - } - - /** - * Inspired by: - * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions - */ - blendRotation(rot, weight) { - let t = weight / (this._sumRotWeight + weight); - quat.slerp(tmpquat, this._target._lrot, rot, t); - this._target.setRotation(tmpquat); - this._sumRotWeight += weight; - } - - apply() { - if (this._sumPosWeight < 1.0) - this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); - if (this._sumScaleWeight < 1.0) - this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); - if (this._sumRotWeight < 1.0) - this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); - } -} diff --git a/cocos/3d/assets/animation-clip.ts b/cocos/3d/assets/animation-clip.ts new file mode 100644 index 0000000000..321ff63aaf --- /dev/null +++ b/cocos/3d/assets/animation-clip.ts @@ -0,0 +1,319 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +// @ts-check +import { _decorator } from '../../core/data/index'; +const { ccclass, property } = _decorator; +import { Asset } from '../../assets/asset'; +import { Quat, Vec3 } from '../../core/value-types'; +import quat from '../../core/vmath/quat'; +import { clamp } from '../../core/vmath/utils'; +import vec3 from '../../core/vmath/vec3'; +import { Node } from '../../scene-graph/node'; + +const tmpvec3 = new Vec3(); +const tmpquat = new Quat(); + +function _binaryIndexOf (array: number[], key: number) { + let lo = 0; + let hi = array.length - 1; + while (lo <= hi) { + const mid = ((lo + hi) >> 1); + const val = array[mid]; + if (val < key) { + lo = mid + 1; + } else if (val > key) { + hi = mid - 1; + } else { + return mid; + } + } + return lo; +} + +export interface IAnimationChannel { + /** + * Target node's path in scene graph. + */ + target: string; + + /** + * Target node's position animation curve. + */ + positionCurve: Vec3[]; + + /** + * Target node's scale animation curve. + */ + scaleCurve: Vec3[]; + + /** + * Target node's rotation animation curve. + */ + rotationCurve: Quat[]; +} + +@ccclass('cc.AnimationClip') +export default class AnimationClip extends Asset { + @property + private _channels: IAnimationChannel[] = []; + + @property + private _times: number[] = []; + + @property + private _length: number = 0.0; + + get times () { + return this._times; + } + + get channels () { + return this._channels; + } + + get length () { + return this._length; + } +} +cc.AnimationClip = AnimationClip; + +export class AnimationTarget { + private _nodes: Node[] = []; + private _pathMap: Map = new Map(); + + public add (path: string, node: Node) { + if (this._pathMap.has(path)) { + return; + } + const index = this._nodes.length; + this._nodes.push(node); + this._pathMap.set(path, index); + } + + public get (path: string) { + return this._pathMap.get(path); + } + + get nodes () { + return this._nodes; + } + + public getDefaultPosition (nodeIndex: number) { + return this._nodes[nodeIndex].getPosition(); + // return this._defaultPositions[nodeIndex]; + } + + public getDefaultScale (nodeIndex: number) { + return this._nodes[nodeIndex].getScale(); + // return this._defaultScales[nodeIndex]; + } + + public getDefaultRotation (nodeIndex: number) { + return this._nodes[nodeIndex].getRotation(); + // return this._defaultRotations[nodeIndex]; + } + + // _saveDefaultTRS() { + // this._defaultPositions = new Array(this._nodes.length); + // this._defaultScales = new Array(this._nodes.length); + // this._defaultRotations = new Array(this._nodes.length); + // this._nodes.forEach((node, index) => { + // this._defaultPositions[index] = node.getPosition(); + // this._defaultScales[index] = node.getScale(); + // this._defaultRotations[index] = node.getRotation(); + // }); + // } +} + +/** + * The AnimationTarget class represents the progress of blended sampling. + */ +export class AnimationSampler { + private _animationTarget: AnimationTarget; + private _nodeSamplingStates: NodeSamplingState[]; + + constructor (animationTarget: AnimationTarget) { + this._animationTarget = animationTarget; + + const targetNodes = this._animationTarget.nodes; + this._nodeSamplingStates = new Array(targetNodes.length); + this._animationTarget.nodes.forEach((targetNode, index) => { + this._nodeSamplingStates[index] = new NodeSamplingState( + targetNode, + this._animationTarget.getDefaultPosition(index), + this._animationTarget.getDefaultScale(index), + this._animationTarget.getDefaultRotation(index)); + }); + } + + /** + * Resets this state to get sampling start. + */ + public reset () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.reset()); + } + + /** + * Updates the sampling result. + */ + public apply () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.apply()); + } + + /** Sample data of this animation clip in a specific time and blend that data + * with a weight together with previous data(if exist, or blank if not exists) sampled before. + * + * @param clip + * @param t The time. + * @param weight The weight. + * @param [mask] The skeleton mask. + */ + public sample (clip: AnimationClip, t: number, weight: number, mask?: any) { + t = clamp(t, 0, clip.length); + + const getState = (channel: IAnimationChannel) => { + const iNode = this._animationTarget.get(channel.target); + if (!iNode) { + return null; + } + return this._nodeSamplingStates[iNode]; + }; + + let idx = 0; + if (clip.times.length !== 1) { + idx = _binaryIndexOf(clip.times, t); + } + if (idx === 0) { + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + nodeSamlingState.blendPosition(channel.positionCurve[0], weight); + } + if (channel.rotationCurve.length !== 0) { + nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); + } + if (channel.scaleCurve.length !== 0) { + nodeSamlingState.blendScale(channel.scaleCurve[0], weight); + } + }); + } else { + const loIdx = Math.max(idx - 1, 0); + const hiIdx = Math.min(idx, clip.times.length); + const ratio = (t - clip.times[loIdx]) / (clip.times[hiIdx] - clip.times[loIdx]); + + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + const a = channel.positionCurve[loIdx]; + const b = channel.positionCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendPosition(tmpvec3, weight); + } + if (channel.rotationCurve.length !== 0) { + const a = channel.rotationCurve[loIdx]; + const b = channel.rotationCurve[hiIdx]; + quat.slerp(tmpquat, a, b, ratio); + nodeSamlingState.blendRotation(tmpquat, weight); + } + if (channel.scaleCurve.length !== 0) { + const a = channel.scaleCurve[loIdx]; + const b = channel.scaleCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendScale(tmpvec3, weight); + } + }); + } + } +} + +class NodeSamplingState { + private _target: Node; + private _defaultPosition: Vec3; + private _defaultScale: Vec3; + private _defaultRotation: Quat; + private _sumPosWeight = 0; + private _sumScaleWeight = 0; + private _sumRotWeight = 0; + + constructor (target: Node, defaultPosition: Vec3, defaultScale: Vec3, defaultRotation: Quat) { + this._target = target; + this._defaultPosition = defaultPosition; + this._defaultScale = defaultScale; + this._defaultRotation = defaultRotation; + } + + public reset () { + this._sumPosWeight = 0.0; + this._sumScaleWeight = 0.0; + this._sumRotWeight = 0.0; + this._target.setPosition(0, 0, 0); + this._target.setScale(0, 0, 0); + this._target.setRotation(0, 0, 0, 1); + } + + public blendPosition (position: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getPosition(), position, weight); + this._target.setPosition(tmpvec3); + this._sumPosWeight += weight; + } + + public blendScale (scale: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getScale(), scale, weight); + this._target.setScale(tmpvec3); + this._sumScaleWeight += weight; + } + + /** + * Inspired by: + * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions + */ + public blendRotation (rotation: Quat, weight: number) { + const t = weight / (this._sumRotWeight + weight); + quat.slerp(tmpquat, this._target.getRotation(), rotation, t); + this._target.setRotation(tmpquat); + this._sumRotWeight += weight; + } + + public apply () { + if (this._sumPosWeight < 1.0) { + this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); + } + if (this._sumScaleWeight < 1.0) { + this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); + } + if (this._sumRotWeight < 1.0) { + this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); + } + } +} diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 89b4e73776..07d0cf0621 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,5 +1,77 @@ // absolute essential effects export default [ + { + "name": "builtin-effect-pbr", + "techniques": [{"passes":[{"program":"builtin-effect-pbr|pbr-vs:vert|pbr-fs:frag", "properties":{"albedo":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "albedo_texture":{"type":29, "value":"grey"}, "metallic":{"type":13, "value":[0.5]}, "metallic_texture":{"type":29, "value":"grey"}, "roughness":{"type":13, "value":[0.7]}, "roughness_texture":{"type":29, "value":"grey"}, "ao":{"type":13, "value":[0.2]}, "ao_texture":{"type":29, "value":"grey"}, "mra_texture":{"type":29, "value":"grey"}, "emissive":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "normal_texture":{"type":29, "value":"normal"}, "diffuseEnvTexture":{"type":32, "value":"white-cube"}, "specularEnvTexture":{"type":32, "value":"white-cube"}, "brdfLUT":{"type":29, "value":"grey"}, "maxReflectionLod":{"type":13, "value":[9]}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-pbr|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], + "shaders": [ + { + "name": "builtin-effect-pbr|pbr-vs:vert|pbr-fs:frag", + "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\nvarying vec3 pos_w;\nvarying vec3 normal_w;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_MRA_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_MRA_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#if USE_TEX_LOD\n#extension GL_EXT_shader_texture_lod: enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\n}\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 pos_w;\nvarying vec3 normal_w;\n#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\n#if USE_IBL\n uniform samplerCube diffuseEnvTexture;\n uniform samplerCube specularEnvTexture;\n uniform sampler2D brdfLUT;\n#endif\n uniform vec4 albedo;\n uniform float metallic;\n uniform float roughness;\n uniform float ao;\n uniform float maxReflectionLod;\n uniform vec4 emissive;\n uniform float alphaTestThreshold;\n#if USE_ALBEDO_TEXTURE\n uniform sampler2D albedo_texture;\n#endif\n#if USE_MRA_TEXTURE\n uniform sampler2D mra_texture;\n#endif\n#if USE_METALLIC_TEXTURE\n uniform sampler2D metallic_texture;\n#endif\n#if USE_ROUGHNESS_TEXTURE\n uniform sampler2D roughness_texture;\n#endif\n#if USE_AO_TEXTURE\n uniform sampler2D ao_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n \n vec3 getNormalFromTexture() {\n vec3 tangentNormal = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n vec3 q1 = dFdx(pos_w);\n vec3 q2 = dFdy(pos_w);\n vec2 st1 = dFdx(uv0);\n vec2 st2 = dFdy(uv0);\n vec3 N = normalize(normal_w);\n vec3 T = normalize(q1*st2.t - q2*st1.t);\n vec3 B = -normalize(cross(N, T));\n mat3 TBN = mat3(T, B, N);\n return normalize(TBN * tangentNormal);\n }\n#endif\nfloat distributionGGX(vec3 N, vec3 H, float roughness) {\n float a = roughness * roughness;\n float a2 = a * a;\n float NdotH = max(dot(N, H), 0.0);\n float NdotH2 = NdotH * NdotH;\n float nom = a2;\n float denom = (NdotH2 * (a2 - 1.0) + 1.0);\n denom = 3.14159265359 * denom * denom;\n return nom / denom;\n}\nfloat geometrySchlickGGX(float NdotV, float roughness) {\n float r = (roughness + 1.0);\n float k = (r * r) / 8.0;\n float nom = NdotV;\n float denom = NdotV * (1.0 - k) + k;\n return nom / denom;\n}\nfloat geometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {\n float NdotV = max(dot(N, V), 0.0);\n float NdotL = max(dot(N, L), 0.0);\n float ggx2 = geometrySchlickGGX(NdotV, roughness);\n float ggx1 = geometrySchlickGGX(NdotL, roughness);\n return ggx1 * ggx2;\n}\nvec3 fresnelSchlick(float cosTheta, vec3 F0) {\n float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta);\n return F0 + (1.0 - F0) * fresnel;\n}\nvec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) {\n float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta);\n return F0 + (max(vec3(1.0 - roughness), F0) - F0) * fresnel;\n}\nvec3 brdf(LightInfo lightInfo, vec3 N, vec3 V, vec3 F0, vec3 albedo, float metallic, float roughness) {\n vec3 H = normalize(V + lightInfo.lightDir);\n float NDF = distributionGGX(N, H, roughness);\n float G = geometrySmith(N, V, lightInfo.lightDir, roughness);\n vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0);\n vec3 nominator = NDF * G * F;\n float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, lightInfo.lightDir), 0.0) + 0.001; \n vec3 specular = nominator / denominator;\n \n vec3 kS = F;\n \n \n \n vec3 kD = vec3(1.0) - kS;\n \n \n \n kD *= 1.0 - metallic;\n float NdotL = max(dot(N, lightInfo.lightDir), 0.0);\n return (kD * albedo / 3.14159265359 + specular) * lightInfo.radiance * NdotL;\n}\nvec4 frag() {\n float opacity = 1.0;\n #if USE_ALBEDO_TEXTURE\n vec4 baseColor = albedo * gammaToLinearSpaceRGBA(texture2D(albedo_texture, uv0));\n vec3 albedo = baseColor.rgb;\n opacity = baseColor.a;\n #else\n opacity = albedo.a;\n vec3 albedo = albedo.rgb;\n #endif\n #if USE_ALPHA_TEST\n if(opacity < alphaTestThreshold) discard;\n #endif\n #if USE_MRA_TEXTURE\n vec3 metalRoughness = texture2D(mra_texture, uv0).rgb;\n float metallic = metalRoughness.r;\n float roughness = metalRoughness.g;\n float ao = metalRoughness.b;\n #else\n #if USE_METALLIC_TEXTURE\n float metallic = texture2D(metallic_texture, uv0).r;\n #endif\n #if USE_ROUGHNESS_TEXTURE\n float roughness = texture2D(roughness_texture, uv0).r;\n #endif\n #if USE_AO_TEXTURE\n float ao = texture2D(ao_texture, uv0).r;\n #endif\n #endif\n vec3 N = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n N = getNormalFromTexture();\n #endif\n vec3 V = normalize(cc_cameraPos.xyz - pos_w);\n \n \n vec3 F0 = vec3(0.04);\n F0 = mix(F0, albedo, metallic);\n \n vec3 Lo = vec3(0.0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n LightInfo info = computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n LightInfo info = computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n LightInfo info = computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if USE_EMISSIVE\n vec3 emissiveColor = emissive.rgb;\n #if USE_EMISSIVE_TEXTURE\n emissiveColor *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n Lo += emissiveColor;\n #endif\n \n vec3 ambient = vec3(0.03) * albedo * ao;\n #if USE_IBL\n \n vec3 F = fresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);\n vec3 kS = F;\n vec3 kD = vec3(1.0) - kS;\n kD *= 1.0 - metallic;\n #if USE_RGBE_IBL_DIFFUSE\n vec3 diffuseEnv = unpackRGBE(textureCube(diffuseEnvTexture, N));\n #else\n vec3 diffuseEnv = textureCube(diffuseEnvTexture, N).rgb;\n #endif\n vec3 diffuse = diffuseEnv * albedo;\n \n vec3 R = reflect(-V, N);\n #if USE_TEX_LOD\n #if USE_RGBE_IBL_SPECULAR\n vec3 specularEnv = unpackRGBE(textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod));\n #else\n vec3 specularEnv = textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod).rgb;\n #endif\n #else\n #if USE_RGBE_IBL_SPECULAR\n vec3 specularEnv = unpackRGBE(textureCube(specularEnvTexture, R));\n #else\n vec3 specularEnv = textureCube(specularEnvTexture, R).rgb;\n #endif\n #endif\n vec2 brdf = texture2D(brdfLUT, vec2(max(dot(N, V), 0.0), 1.0 - roughness)).rg;\n vec3 specular = specularEnv * (F * brdf.x + brdf.y);\n ambient = (kD * diffuse + specular) * ao;\n #endif\n vec3 color = ambient + Lo;\n #if CC_USE_SHADOW_MAP\n color *= computeShadow();\n #endif\n \n color = color / (color + vec3(1.0));\n \n vec4 finalColor = vec4(color, opacity);\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"USE_ALBEDO_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, + {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_TEX_LOD", "type":"boolean", "defines":[]}, + {"name":"USE_IBL", "type":"boolean", "defines":[]}, + {"name":"USE_MRA_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_METALLIC_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_ROUGHNESS_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_AO_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, + {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, + {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, + {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, + {"name":"USE_RGBE_IBL_DIFFUSE", "type":"boolean", "defines":["USE_IBL"]}, + {"name":"USE_RGBE_IBL_SPECULAR", "type":"boolean", "defines":["USE_IBL"]} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8} + ]}, + {"name": "Constants", "size": 52, "defines": [], "binding": 1, "members": [ + {"name":"albedo", "type":16, "count":1, "size":16}, + {"name":"metallic", "type":13, "count":1, "size":4}, + {"name":"roughness", "type":13, "count":1, "size":4}, + {"name":"ao", "type":13, "count":1, "size":4}, + {"name":"maxReflectionLod", "type":13, "count":1, "size":4}, + {"name":"emissive", "type":16, "count":1, "size":16}, + {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} + ]} + ], + "samplers": [ + {"name":"diffuseEnvTexture", "type":32, "count":1, "defines":["USE_IBL"], "binding":2}, + {"name":"specularEnvTexture", "type":32, "count":1, "defines":["USE_IBL"], "binding":3}, + {"name":"brdfLUT", "type":29, "count":1, "defines":["USE_IBL"], "binding":4}, + {"name":"albedo_texture", "type":29, "count":1, "defines":["USE_ALBEDO_TEXTURE"], "binding":5}, + {"name":"mra_texture", "type":29, "count":1, "defines":["USE_MRA_TEXTURE"], "binding":6}, + {"name":"metallic_texture", "type":29, "count":1, "defines":["USE_METALLIC_TEXTURE"], "binding":7}, + {"name":"roughness_texture", "type":29, "count":1, "defines":["USE_ROUGHNESS_TEXTURE"], "binding":8}, + {"name":"ao_texture", "type":29, "count":1, "defines":["USE_AO_TEXTURE"], "binding":9}, + {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":10}, + {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":11} + ], + "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives", "USE_TEX_LOD":"EXT_shader_texture_lod"} + }, + { + "name": "builtin-effect-pbr|shadow-depth-vs:vert|shadow-depth-fs:frag", + "vert": "\nattribute vec3 a_position;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying float vDepth;\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert() {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} + ], + "blocks": [], + "samplers": [], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-phong", "techniques": [{"passes":[{"program":"builtin-effect-phong|phong-vs:vert|phong-fs:frag", "properties":{"diffuseColor":{"type":17, "value":[0.3, 0.3, 0.3, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "diffuse_texture":{"type":29, "value":"grey"}, "specularColor":{"type":17, "value":[0, 0, 0, 0]}, "specular_texture":{"type":29, "value":"grey"}, "emissiveColor":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "glossiness":{"type":13, "value":[10]}, "normal_texture":{"type":29, "value":"normal"}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js deleted file mode 100644 index 0e9d1c8e4b..0000000000 --- a/cocos/3d/framework/animation-component.js +++ /dev/null @@ -1,495 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - 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. - ****************************************************************************/ -// @ts-check -import { Component } from '../../components/component'; -import { ccclass, property, executionOrder, menu, executeInEditMode } from '../../core/data/class-decorator'; -import Enum from '../../core/value-types/enum'; -import AnimationClip, { AnimationTarget, AnimationSampler } from '../assets/animation-clip'; - -/** - * !#en Animation State Class - * - * !#ch 动画状态类 - * @class AnimationState - */ -class AnimationState { - constructor(clip) { - /** - * !#en An animation clip that is played through this state - * - * !#ch 通过此状态播放的动画剪辑 - * @property clip - * @type {AnimationClip} - */ - this.clip = clip; - - /** - * !#en Blend mode - * - * !#ch 混合模式 - * @property blendMode - * @type {String} - */ - this.blendMode = AnimationState.BlendMode.Blend; - - /** - * !#en Wrapping mode - * - * !#ch 循环模式 - * @property wrapMode - * @type {String} - */ - this.wrapMode = AnimationState.WrapMode.Loop; - - /** - * !#en The playback speed - * - * !#ch 播放速度 - * @property speed - * @type {Number} - */ - this.speed = 1.0; - - /** - * !#en The current time of the animation. - * - * !#ch 当前动画播放时间 - * @property time - * @type {Number} - */ - this.time = 0.0; - - /** - * !#en The weight of animation. - * - * !#ch 动画权重 - * @property weight - * @type {Number} - */ - this.weight = 1.0; - } - - /** - * !#en The blend mode of animation state - * - * !#ch 动画状态的混合模式 - * @static - * @enum AnimationState.BlendMode - */ - static BlendMode = Enum({ - /** - * !#en Animations will be blended. - * - * !#ch 动画将被混合 - * @property Blend - * @readonly - * @type {String} - */ - Blend: 'blend', - /** - * !#en Animations will be added. - * - * !#ch 动画将被附加 - * @property Additive - * @readonly - * @type {String} - */ - Additive: 'additive' - }); - - /** - * !#en Wrapping mode of the animation. - * - * !#ch 动画状态的循环模式 - * @static - * @enum AnimationState.WrapMode - */ - static WrapMode = Enum({ - /** - * !#en Only once - * - * !#ch 只播放一次 - * @property Once - * @readonly - * @type {String} - */ - Once: 'once', - /** - * !#en Loop - * - * !#ch 循环播放 - * @property Additive - * @readonly - * @type {String} - */ - Loop: 'loop', - /** - * !#en Ping Pong - * - * !#ch 乒乓模式播放 - * @property PinpPong - * @readonly - * @type {String} - */ - PinpPong: 'ping-pong', - /** - * !#en Plays back the animation. The last frame is played until the end. - * - * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 - * @property Clamp - * @readonly - * @type {String} - */ - Clamp: 'clamp' - }); -} - -/** - * !#en Animation Controller - * - * !#ch 动画控制器 - * @class AnimationCtrl - */ -class AnimationCtrl { - constructor() { - /** - * @type {AnimationTarget} - */ - this._animationTarget = null; - - /** - * @type {AnimationSampler} - */ - this._animationSampler = null; - - this._current = null; - - this._next = null; - - this._blendTime = 0.0; - - this._blendDuration = 0.3; - } - - /** - * !#en Set up the animation target - * - * !#ch 设置动画目标 - * @param {AnimationTarget} animationTarget - */ - setAnimationTarget(animationTarget) { - this._animationTarget = animationTarget; - if (this._animationTarget) { - this._animationSampler = new AnimationSampler(this._animationTarget); - } - this._nodeIndexers = new Map(); - } - - /** - * !#en Animation fades in and out - * - * !#ch 动画的淡入淡出功能 - * @param {AnimationState} to - * @param {Number} duration - */ - crossFade(to, duration) { - if (this._current && duration > 0.0) { - this._next = to; - this._blendTime = 0.0; - this._blendDuration = duration; - } else { - this._current = to; - this._next = null; - } - } - - tick(dt) { - if (!this._animationSampler) { - return; - } - - this._animationSampler.reset(); - - // handle blend - if (this._current && this._next) { - let t0 = this._getTime(this._current); - let t1 = this._getTime(this._next); - - let alpha = this._blendTime / this._blendDuration; - - this._current.time += dt; - this._next.time += dt; - this._blendTime += dt; - - if (alpha > 1.0) { - this._current = this._next; - this._next = null; - this._animationSampler.sample(this._current.clip, t1, 1.0); - } else { - this._animationSampler.sample(this._current.clip, t0, alpha); - this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); - } - } - - // handle playing - if (this._current) { - let t0 = this._getTime(this._current); - this._animationSampler.sample(this._current.clip, t0, 1.0); - this._current.time += dt; - } - - this._animationSampler.apply(); - } - - /** - * !#en Get the play time of an animation clip in current animation state - * - * !#ch 返回当前动画状态下的动画剪辑播放时间 - * @param {AnimationState} state - Specify animation status - */ - _getTime(state) { - let t = state.time; - let length = state.clip.length; - t *= state.speed; - - if (state.wrapMode === 'once') { - if (t > length) { - t = 0.0; - } - } else if (state.wrapMode === 'loop') { - t %= length; - } else if (state.wrapMode === 'ping-pong') { - let order = Math.floor(t / length); - if (order % 2 === 1) { - t = length - t % length; - } - } - - return t; - } -} - -/** - * !#en - * Basic animation component for playing animation - * - * !#ch - * 基础动画组件用于动画播放 - * @class AnimationComponent - * @extends Component - */ -@ccclass('cc.AnimationComponent') -@executionOrder(99) -@executeInEditMode -@menu('Components/AnimationComponent') -export default class AnimationComponent extends Component { - /** - * @type {AnimationClip[]} - */ - @property({ type: [AnimationClip] }) - _clips = []; - - /** - * !#en Current clip - * - * !#ch 当前动画剪辑 - * @property currentClip - * @type {AnimationClip} - */ - @property({ type:AnimationClip }) - currentClip = null; - - /** - * !#en Whether to start the animation automatically - * - * !#ch 是否启动时自动播放动画 - * @property playAutomatically - * @type {Boolean} - */ - @property - playAutomatically = false; - - _preview = false; - - @property({ type: Boolean }) - get preview() { - return this._preview; - } - - set preview(value) { - this._preview = value; - if (value) { - if (this.currentClip) { - cc.engine.animatingInEditMode = true; - this.play(this.currentClip.name); - } - } else { - cc.engine.animatingInEditMode = false; - this._animCtrl.crossFade(null, 0); - } - } - - /** - * !#en Animation state - * - * !#ch 动画状态列表 - * @type {Object} - */ - _name2states = {}; - - constructor() { - super(); - - /** - * @type {AnimationTarget} - */ - this._target = null; - - /** - * !#en Animation controller - * - * !#ch 动画控制器 - * @type {AnimationCtrl} - */ - this._animCtrl = new AnimationCtrl(); - } - - /** - * !#en Clip required for animation playback - * - * !#ch 动画剪辑列表 - * @property clips - * @type {AnimationClip[]} - */ - @property({ type: [AnimationClip] }) - get clips() { - return this._clips; - } - - set clips(val) { - this._clips = val; - } - - onLoad() { - this._clips.forEach(clip => { - this._name2states[clip.name] = new AnimationState(clip); - }); - - this._resetTarget(); - - if (this.playAutomatically != undefined && - this.playAutomatically && - this.currentClip != undefined && - this.currentClip) { - this.play(this.currentClip.name); - } - } - - update(dt) { - this._animCtrl.tick(dt); - } - - onDestroy() { - } - - onEnable() { - } - - onDisable() { - this._target = null; - this._animCtrl.setAnimationTarget(null); - } - - /** - * !#en Add an animation clip to the animation status list - * - * !#ch 添加动画剪辑到动画状态列表 - * @param {String} name - The name of animation clip - * @param {AnimationClip} animClip - Animation clip - */ - addClip(name, animClip) { - if (this._name2states[name]) { - console.warn(`Failed to add clip ${name}, the name already exsits.`); - return; - } - - this._clips.push(animClip); - this._name2states[name] = new AnimationState(animClip); - } - - /** - * !#en Get the animation state through the animation clip name - * - * !#ch 返回动画剪辑相对应的动画状态 - * @param {String} name - The name of animation clip - */ - getState(name) { - return this._name2states[name]; - } - - /** - * !#en Play the name of the animation clip - * - * !#ch 播放相对应名字的动画剪辑 - * @param {String} name - The name of animation clip - * @param {Number} fadeDuration - Fade duration - */ - play(name, fadeDuration = 0.3) { - if (!this._target) { - return; - } - - if (!this._name2states[name]) { - console.warn(`Failed to play animation ${name}, not found.`); - return; - } - - let animState = this._name2states[name]; - animState.time = 0.0; - - this._animCtrl.crossFade(animState, fadeDuration); - } - - _resetTarget() { - this._target = new AnimationTarget(); - this._clips.forEach(clip => { - clip.frames.forEach(frame => { - frame.channels.forEach(channel => { - const targetPath = channel.target; - if (this._target.get(targetPath)) { - return; - } - const targetNode = this.node.getChildByPath(targetPath); - if (!targetNode) { - console.warn(`Animation target ${targetPath} not found in scene graph.`); - return; - } - this._target.add(targetPath, targetNode); - }); - }); - }); - this._animCtrl.setAnimationTarget(this._target); - } -} diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts new file mode 100644 index 0000000000..c308fb1f82 --- /dev/null +++ b/cocos/3d/framework/animation-component.ts @@ -0,0 +1,426 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + 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. + ****************************************************************************/ +// @ts-check +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { ccenum } from '../../core/value-types/enum'; +import AnimationClip, { AnimationSampler, AnimationTarget } from '../assets/animation-clip'; + +enum BlendMode { + /** + * !#en Animations will be blended. + * + * !#ch 动画将被混合 + */ + Blend = 'blend', + /** + * !#en Animations will be added. + * + * !#ch 动画将被附加 + */ + Additive = 'additive', +} + +ccenum(BlendMode); + +enum WrapMode { + /** + * !#en Only once + * + * !#ch 只播放一次 + */ + Once = 'once', + + /** + * !#en Loop + * + * !#ch 循环播放 + */ + Loop = 'loop', + + /** + * !#en Ping Pong + * + * !#ch 乒乓模式播放 + */ + PinpPong = 'ping-pong', + + /** + * !#en Plays back the animation. The last frame is played until the end. + * + * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 + */ + Clamp = 'clamp', +} + +ccenum(WrapMode); + +/** + * !#en Animation State Class + * + * !#ch 动画状态类 + */ +class AnimationState { + /** + * !#en The blend mode of animation state. + * + * !#ch 动画状态的混合模式 + */ + public static BlendMode = BlendMode; + + /** + * !#en Wrapping mode of the animation. + * + * !#ch 动画状态的循环模式 + */ + public static WrapMode = WrapMode; + + /** + * !#en An animation clip that is played through this state + * + * !#ch 通过此状态播放的动画剪辑 + */ + public clip: AnimationClip; + + /** + * !#en Blend mode + * + * !#ch 混合模式 + */ + public blendMode: BlendMode = BlendMode.Blend; + + /** + * !#en Wrapping mode + * + * !#ch 循环模式 + */ + public wrapMode: WrapMode = WrapMode.Loop; + + /** + * !#en The playback speed + * + * !#ch 播放速度 + */ + public speed = 1.0; + + /** + * !#en The current time of the animation. + * + * !#ch 当前动画播放时间 + */ + public time: number = 0.0; + + /** + * !#en The weight of animation. + * + * !#ch 动画权重 + */ + public weight: number = 1.0; + + constructor (clip: AnimationClip) { + this.clip = clip; + } +} + +/** + * !#en Animation Controller + * + * !#ch 动画控制器 + */ +class AnimationCtrl { + private _animationTarget: AnimationTarget | null = null; + private _animationSampler: AnimationSampler | null = null; + private _current: AnimationState | null = null; + private _next: AnimationState | null = null; + private _blendTime = 0.0; + private _blendDuration = 0.3; + + /** + * !#en Set up the animation target + * + * !#ch 设置动画目标 + */ + public setAnimationTarget (animationTarget: AnimationTarget | null) { + this._animationTarget = animationTarget; + if (this._animationTarget) { + this._animationSampler = new AnimationSampler(this._animationTarget); + } + } + + /** + * !#en Animation fades in and out + * + * !#ch 动画的淡入淡出功能 + * @param to + * @param duration + */ + public crossFade (to: AnimationState | null, duration: number) { + if (this._current && duration > 0.0) { + this._next = to; + this._blendTime = 0.0; + this._blendDuration = duration; + } else { + this._current = to; + this._next = null; + } + } + + public tick (deltaTime: number) { + if (!this._animationSampler) { + return; + } + + this._animationSampler.reset(); + + // handle blend + if (this._current && this._next) { + const t0 = this._getTime(this._current); + const t1 = this._getTime(this._next); + + const alpha = this._blendTime / this._blendDuration; + + this._current.time += deltaTime; + this._next.time += deltaTime; + this._blendTime += deltaTime; + + if (alpha > 1.0) { + this._current = this._next; + this._next = null; + this._animationSampler.sample(this._current.clip, t1, 1.0); + } else { + this._animationSampler.sample(this._current.clip, t0, alpha); + this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); + } + } + + // handle playing + if (this._current) { + const t0 = this._getTime(this._current); + this._animationSampler.sample(this._current.clip, t0, 1.0); + this._current.time += deltaTime; + } + + this._animationSampler.apply(); + } + + /** + * !#en Get the play time of an animation clip in current animation state + * + * !#ch 返回当前动画状态下的动画剪辑播放时间 + * @param state - Specify animation status + */ + private _getTime (state: AnimationState) { + let t = state.time; + const length = state.clip.length; + t *= state.speed; + + if (state.wrapMode === 'once') { + if (t > length) { + t = 0.0; + } + } else if (state.wrapMode === 'loop') { + t %= length; + } else if (state.wrapMode === 'ping-pong') { + const order = Math.floor(t / length); + if (order % 2 === 1) { + t = length - t % length; + } + } + + return t; + } +} + +/** + * !#en + * Basic animation component for playing animation + * + * !#ch + * 基础动画组件用于动画播放 + */ +@ccclass('cc.AnimationComponent') +@executionOrder(99) +@executeInEditMode +@menu('Components/AnimationComponent') +export default class AnimationComponent extends Component { + @property({ type: [AnimationClip] }) + public _clips: AnimationClip[] = []; + + /** + * !#en Current clip + * + * !#ch 当前动画剪辑 + */ + @property({ type: AnimationClip }) + public currentClip: AnimationClip | null = null; + + /** + * !#en Whether to start the animation automatically + * + * !#ch 是否启动时自动播放动画 + */ + @property + public playAutomatically: boolean = false; + + private _preview = false; + + private _animationController: AnimationCtrl = new AnimationCtrl(); + + private _name2states: { [x: string]: AnimationState | undefined; } = {}; + + private _animationTarget: AnimationTarget | null = null; + + @property({ type: Boolean }) + get preview () { + return this._preview; + } + + set preview (value) { + this._preview = value; + if (value) { + if (this.currentClip) { + cc.engine.animatingInEditMode = true; + this.play(this.currentClip.name); + } + } else { + cc.engine.animatingInEditMode = false; + this._animationController.crossFade(null, 0); + } + } + + constructor () { + super(); + } + + /** + * !#en Clip required for animation playback + * + * !#ch 动画剪辑列表 + */ + @property({ type: [AnimationClip] }) + get clips () { + return this._clips; + } + + set clips (val) { + this._clips = val; + } + + public onLoad () { + this._clips.forEach((clip) => { + this._name2states[clip.name] = new AnimationState(clip); + }); + + this._resetTarget(); + + if (!CC_EDITOR && this.playAutomatically && this.currentClip) { + this.play(this.currentClip.name); + } + } + + public update (deltaTime: number) { + this._animationController.tick(deltaTime); + } + + public onDestroy () { + } + + public onEnable () { + } + + public onDisable () { + this._animationTarget = null; + this._animationController.setAnimationTarget(null); + } + + /** + * !#en Add an animation clip to the animation status list + * + * !#ch 添加动画剪辑到动画状态列表 + * @param name - The name of animation clip + * @param animationClip - Animation clip + */ + public addClip (name: string, animationClip: AnimationClip) { + if (this._name2states[name]) { + console.warn(`Failed to add clip ${name}, the name already exsits.`); + return; + } + + this._clips.push(animationClip); + this._name2states[name] = new AnimationState(animationClip); + } + + /** + * !#en Get the animation state through the animation clip name + * + * !#ch 返回动画剪辑相对应的动画状态 + * @param name - The name of animation clip + */ + public getState (name: string) { + return this._name2states[name]; + } + + /** + * !#en Play the name of the animation clip + * + * !#ch 播放相对应名字的动画剪辑 + * @param name - The name of animation clip + * @param fadeDuration - Fade duration + */ + public play (name: string, fadeDuration = 0.3) { + if (!this._animationTarget) { + return; + } + + const state = this._name2states[name]; + if (!state) { + console.warn(`Failed to play animation ${name}, not found.`); + return; + } + + state.time = 0.0; + this._animationController.crossFade(state, fadeDuration); + } + + public _resetTarget () { + const animationTarget = new AnimationTarget(); + this._clips.forEach((clip) => { + clip.channels.forEach((channel) => { + const targetPath = channel.target; + if (animationTarget.get(targetPath)) { + return; + } + const targetNode = this.node.getChildByPath(targetPath); + if (!targetNode) { + console.warn(`Animation target ${targetPath} not found in scene graph.`); + return; + } + animationTarget.add(targetPath, targetNode); + }); + }); + this._animationTarget = animationTarget; + this._animationController.setAnimationTarget(this._animationTarget); + } +} diff --git a/cocos/3d/framework/animation-system.js b/cocos/3d/framework/animation-system.js deleted file mode 100644 index c68d3b8165..0000000000 --- a/cocos/3d/framework/animation-system.js +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - 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. - ****************************************************************************/ -// @ts-check -import System from '../ecs/system'; -import { FixedArray } from '../memop'; -/** - * @typedef {import('./animation-component').default} AnimationComponent - */ - -export default class AnimationSystem extends System { - constructor() { - super(); - - this._anims = new FixedArray(200); - } - - add(comp) { - this._anims.push(comp); - } - - remove(comp) { - this._anims.fastRemove(this._anims.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._anims.length; ++i) { -// let anim = this._anims.data[i]; -// if (!anim.enabled) { -// continue; -// } -// if (!anim.skeleton) { -// // console.error(`Animation component depends on skinning model component.`); -// let skeleton = findSkeleton(anim._entity); -// anim.skeleton = skeleton; -// } -// if (anim.skeleton) { -// anim._animCtrl.tick(this._app.deltaTime); -// } -// } -// } -} diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts index a15be397b5..361d058cf6 100644 --- a/cocos/3d/framework/light-component.ts +++ b/cocos/3d/framework/light-component.ts @@ -183,9 +183,10 @@ export default class LightComponent extends Component { set color (val) { this._color = val; - this._colorData[0] = val.r * this._intensity; - this._colorData[1] = val.g * this._intensity; - this._colorData[2] = val.b * this._intensity; + const scale = this._intensity / 255; + this._colorData[0] = val.r * scale; + this._colorData[1] = val.g * scale; + this._colorData[2] = val.b * scale; if (this._light) { this._light.color = this._colorData; } @@ -204,9 +205,10 @@ export default class LightComponent extends Component { set intensity (val) { this._intensity = val; - this._colorData[0] = this._color.r * val; - this._colorData[1] = this._color.g * val; - this._colorData[2] = this._color.b * val; + const scale = val / 255; + this._colorData[0] = this._color.r * scale; + this._colorData[1] = this._color.g * scale; + this._colorData[2] = this._color.b * scale; if (this._light) { this._light.color = this._colorData; } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 2389fe921a..bbf38ac38c 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -13,6 +13,10 @@ export class RenderableComponent extends Component { super(); } + public onLoad () { + this.sharedMaterials = this._materials.concat(); + } + @property({ type: [Material], displayName: 'Materials', diff --git a/cocos/3d/framework/skeleton-instance.js b/cocos/3d/framework/skeleton-instance.js deleted file mode 100644 index 92ac204819..0000000000 --- a/cocos/3d/framework/skeleton-instance.js +++ /dev/null @@ -1,176 +0,0 @@ -// @ts-check -import { vec3, quat, mat4 } from '../../core/vmath'; -import { Node } from '../../scene-graph'; - -let _v3_tmp = vec3.create(); -let _qt_tmp = quat.create(); - -/** - * - * @param {cc.Node} node - * @param {(node: cc.Node)=>void} fx - */ -function _walk(node, fx) { - fx(node); - for (let i = 0; i < node.childrenCount; ++i) { - _walk(node.children[i], fx); - } -} - -export default class SkeletonInstance { - /** - * - * @param {import("../assets/skeleton").default} skeleton - */ - constructor(skeleton) { - this._skeleton = skeleton; - - /** - * @type {cc.Node[]} - */ - this._nodes = this._copyNodesForest(skeleton._nodes); - - /** - * @type {mat4[]} - */ - this._matrices = new Array(this._nodes.length); - for (let i = 0; i < this._nodes.length; ++i) { - this._matrices[i] = mat4.create(); - } - - this.updateMatrices(); - } - - /** - * - * @param {cc.Node[]} nodes - */ - _copyNodesForest(nodes) { - /** @type {cc.Node[]} */ - const newNodes = new Array(nodes.length); - nodes.forEach((node, index) => { - newNodes[index] = this._copyNode(node); - }); - nodes.forEach((node, index) => { - const newNode = newNodes[index]; - node.children.forEach(childNode => { - const childIndex = nodes.indexOf(childNode); - newNode.addChild(newNodes[childIndex]); - }); - }); - return newNodes; - } - - /** - * - * @param {cc.Node} node - */ - _copyNode(node) { - const newNode = new Node(node.name); - newNode.setPosition(node.getPosition()); - newNode.setScale(node.getScale()); - newNode.setRotation(node.getRotation()); - return newNode; - } - - blend(fromSkel, toSkel, alpha) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - let jointFrom = fromSkel._nodes[i]; - let jointTo = toSkel._nodes[i]; - - vec3.lerp(_v3_tmp, jointFrom._lpos, jointTo._lpos, alpha); - joint.setPosition(_v3_tmp); - - vec3.lerp(_v3_tmp, jointFrom._lscale, jointTo._lscale, alpha); - joint.setScale(_v3_tmp); - - quat.lerp(_qt_tmp, jointFrom._lrot, jointTo._lrot, alpha); - joint.setRotation(_qt_tmp); - } - } - - updateMatrices() { - for (let i = 0; i < this._nodes.length; ++i) { - this._nodes[i].getWorldMatrix(this._matrices[i]); - } - } - - /** - * - * @param {number} i Index of the node. - */ - getWorldMatrix(i) { - return this._matrices[i]; - } - - getJointIndex(jointName) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - if (joint.name == jointName) { - return i; - } - } - return -1; - } - - getJointIndexFromOrignalNodeIndex(index) { - return index; - } - - clone() { - return new SkeletonInstance(this._skeleton); - } - - createMask() { - return new SkeletonMask(this); - } -} - -export class SkeletonMask { - /** - * - * @param {SkeletonInstance} skeleton - */ - constructor(skeleton) { - /** - * @type {SkeletonInstance} - * */ - this._skeleton = skeleton; - - this._isMaskedArray = new Array(skeleton._nodes.length); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - this._isMaskedArray[i] = false; - } - } - - setMasked(jointIndex, masked = true) { - this._isMaskedArray[jointIndex] = masked; - } - - setMaskedRecursive(jointIndex, masked = true) { - if (jointIndex < 0 || jointIndex >= this._skeleton._nodes.length) { - return; - } - - this._isMaskedArray[jointIndex] = masked; - _walk(this._skeleton._nodes[0], joint => { - let idx = this._skeleton._nodes.indexOf(joint); - if (idx >= 0) { - this._isMaskedArray[idx] = masked; - } - }); - } - - isMasked(jointIndex) { - return this._isMaskedArray[jointIndex]; - } - - complement() { - let ret = new SkeletonMask(this._skeleton); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - ret._isMaskedArray[i] = !this._isMaskedArray[i]; - } - return ret; - } -} \ No newline at end of file diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts index 1f80f29aeb..ee0737bb9c 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/3d/framework/skinning-model-component.ts @@ -24,37 +24,18 @@ ****************************************************************************/ // @ts-check -import { Texture2D } from '../../assets/texture-2d'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { mat4 } from '../../core/vmath'; import { GFXDevice, GFXFeature } from '../../gfx/device'; import { SkinningModel } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; +import { Material } from '../assets/material'; import Skeleton from '../assets/skeleton'; -import * as utils from '../misc/utils'; import { ModelComponent } from './model-component'; const _m4_tmp = mat4.create(); -interface IJointTextureStorage { - nativeData: Float32Array; - texture: Texture2D; -} - -interface IJointUniformsStorage { - nativeData: Float32Array; -} - -type JointStorage = IJointTextureStorage | IJointUniformsStorage; - -interface ISkinningState { - skinningTarget: Map; - storage: JointStorage; -} - -function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { - return (storage as any).texture !== undefined; -} +type SkinningTarget = Map; /** * !#en The Skinning Model Component @@ -65,17 +46,6 @@ function isTextureStorage (storage: JointStorage): storage is IJointTextureStora @executeInEditMode @menu('Components/SkinningModelComponent') export default class SkinningModelComponent extends ModelComponent { - @property(Skeleton) - private _skeleton: Skeleton | null = null; - - @property(Node) - private _skinningRoot: Node | null = null; - - private _skinningState: ISkinningState | null = null; - - constructor () { - super(); - } /** * !#en The bone nodes @@ -89,7 +59,8 @@ export default class SkinningModelComponent extends ModelComponent { set skeleton (val) { this._skeleton = val; - this._resetSkinningState(); + this._resetSkinningTarget(); + this._bindSkeleton(); } @property({type: Node}) @@ -99,11 +70,23 @@ export default class SkinningModelComponent extends ModelComponent { set skinningRoot (value) { this._skinningRoot = value; - this._resetSkinningState(); + this._resetSkinningTarget(); + } + @property(Skeleton) + private _skeleton: Skeleton | null = null; + + @property(Node) + private _skinningRoot: Node | null = null; + + private _skinningTarget: SkinningTarget | null = null; + + constructor () { + super(); } public onLoad () { - this._resetSkinningState(); + super.onLoad(); + this._resetSkinningTarget(); } public update (dt) { @@ -114,19 +97,19 @@ export default class SkinningModelComponent extends ModelComponent { } public _tryUpdateMatrices () { - if (!this._skeleton || !this._skinningState) { + if (!this._skeleton || !this._skinningTarget || !this._model) { return; } - const skinningState = this._skinningState!; - const skeleton = this._skeleton!; + const skinningModel = this._model as SkinningModel; + const skeleton = this._skeleton; + const skinningTarget = this._skinningTarget; const cancelThisNodeTransform = this.node.getWorldMatrix(); mat4.invert(cancelThisNodeTransform, cancelThisNodeTransform); - this._skeleton.joints.forEach((joint, index) => { // If target joint doesn't exists in scene graph, skip it. - const targetNode = skinningState.skinningTarget.get(joint); + const targetNode = skinningTarget.get(joint); if (!targetNode) { return; } @@ -137,13 +120,10 @@ export default class SkinningModelComponent extends ModelComponent { const jointMatrix = _m4_tmp; mat4.multiply(jointMatrix, cancelThisNodeTransform, targetNode.getWorldMatrix()); mat4.multiply(jointMatrix, jointMatrix, bindpose); - _setJointMatrix(skinningState.storage.nativeData, index, jointMatrix); + skinningModel.updateJointMatrix(index, jointMatrix); }); - const storage = skinningState.storage; - if (isTextureStorage(storage)) { - storage.texture.directUpdate(storage.nativeData.buffer); - } + skinningModel.commitJointMatrices(); } public _createModel () { @@ -152,53 +132,33 @@ export default class SkinningModelComponent extends ModelComponent { public _updateModelParams () { super._updateModelParams(); - // Upload joint matrices. - if (this._skinningState !== null) { - const skinningState = this._skinningState; - const skinningModel = this._model as SkinningModel; - if (isTextureStorage(skinningState.storage)) { - const texture = skinningState.storage.texture; - skinningModel.setJointTexture(texture); - } else { - skinningModel.setJointMatrices(skinningState.storage.nativeData); - } + this._bindSkeleton(); + } + + protected _onMaterialModified (index: number, material: Material) { + super._onMaterialModified(index, material); + + const device = _getGlobalDevice(); + const useJointTexture = device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false; + this.getMaterial(0, CC_EDITOR)!.setDefines({ + CC_USE_SKINNING: true, + CC_USE_JOINTS_TEXTURE: useJointTexture, + }); + } + + private _bindSkeleton () { + if (this._model && this._skeleton) { + (this._model as SkinningModel).bindSkeleton(this._skeleton); } } - private _resetSkinningState () { - if (this._skinningState) { - if (isTextureStorage(this._skinningState.storage)) { - this._skinningState.storage.texture.destroy(); - } - this._skinningState = null; - } - + private _resetSkinningTarget () { if (!this._skeleton || !this._skinningRoot) { return; } - let storage: JointStorage; - - // Allocate joint matrices storage. - const device = _getGlobalDevice(); - if (device && device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { - const jointsTexture = utils.createJointsTexture(this._skeleton); - storage = { - texture: jointsTexture, - nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), - } as IJointTextureStorage; - } else { - storage = { - nativeData: new Float32Array(this._skeleton.joints.length * 16), - } as IJointUniformsStorage; - } - - const skinningState: ISkinningState = { - skinningTarget: new Map(), - storage, - }; - // Collect target to skin. + this._skinningTarget = new Map(); const rootNode = this._skinningRoot; this._skeleton.joints.forEach((joint) => { const targetNode = rootNode.getChildByPath(joint); @@ -206,10 +166,8 @@ export default class SkinningModelComponent extends ModelComponent { console.warn(`Skinning target ${joint} not found in scene graph.`); return; } - skinningState.skinningTarget.set(joint, targetNode); + this._skinningTarget!.set(joint, targetNode); }); - - this._skinningState = skinningState; } } @@ -217,22 +175,3 @@ function _getGlobalDevice (): GFXDevice | null { // @ts-ignore return cc.director.root.device; } - -function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { - out[16 * iMatrix + 0] = matrix.m00; - out[16 * iMatrix + 1] = matrix.m01; - out[16 * iMatrix + 2] = matrix.m02; - out[16 * iMatrix + 3] = matrix.m03; - out[16 * iMatrix + 4] = matrix.m04; - out[16 * iMatrix + 5] = matrix.m05; - out[16 * iMatrix + 6] = matrix.m06; - out[16 * iMatrix + 7] = matrix.m07; - out[16 * iMatrix + 8] = matrix.m08; - out[16 * iMatrix + 9] = matrix.m09; - out[16 * iMatrix + 10] = matrix.m10; - out[16 * iMatrix + 11] = matrix.m11; - out[16 * iMatrix + 12] = matrix.m12; - out[16 * iMatrix + 13] = matrix.m13; - out[16 * iMatrix + 14] = matrix.m14; - out[16 * iMatrix + 15] = matrix.m15; -} diff --git a/cocos/3d/framework/skinning-model-system.js b/cocos/3d/framework/skinning-model-system.js deleted file mode 100644 index 25d4542bf1..0000000000 --- a/cocos/3d/framework/skinning-model-system.js +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - 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. - ****************************************************************************/ -// @ts-check -import { System } from '../ecs'; -import { FixedArray } from '../memop'; -import { _decorator } from '../../core/data/index'; -const { ccclass, property } = _decorator; - -/** - * !#en Skinning Model Component Management System - * - * !#ch 皮肤模型管理系统 - * @class SkinningModelSystem - * @extends System - */ -@ccclass('cc.SkinningModelSystem') -export default class SkinningModelSystem extends System { - constructor() { - super(); - - this._comps = new FixedArray(200); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - add(comp) { - this._comps.push(comp); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - remove(comp) { - this._comps.fastRemove(this._comps.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._comps.length; ++i) { -// let comp = this._comps.data[i]; -// if (comp.enabled === false) { -// continue; -// } - -// comp._updateMatrices(); -// } -// } -} diff --git a/cocos/core/director.js b/cocos/core/director.js index eb6e6e56d1..d701c45a1c 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -33,7 +33,6 @@ import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; import ComponentScheduler from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; -// import AnimationSystem from '../3d/framework/animation-system'; // import SkinningModelSystem from '../3d/framework/skinning-model-system'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; diff --git a/cocos/core/game.js b/cocos/core/game.js index b1cb8a09e1..df7594afa4 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -771,6 +771,7 @@ var game = { this._gfxDevice = new cc.WebGLGFXDevice; this._gfxDevice.initialize({ canvasElm : localCanvas, + debug: true, }); //let device = this._renderContext = new gfx.Device(localCanvas, {}); diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index e9d17c6ba7..b4d36fc1c3 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -25,6 +25,7 @@ export interface IGFXDeviceInfo { canvasElm: HTMLElement; isAntialias?: boolean; isPremultipliedAlpha?: boolean; + debug?: boolean; } // tslint:disable: max-line-length diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 07d0e3df5b..ae5a1230c4 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,3 +1,4 @@ +import * as WebGLDeveloperTools from 'webgl-debug'; import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -253,6 +254,9 @@ export class WebGLGFXDevice extends GFXDevice { }; this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); + if (this._webGLRC && info.debug) { + this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); + } } catch (err) { console.error(err); return false; @@ -1076,4 +1080,8 @@ export class WebGLGFXDevice extends GFXDevice { gl.colorMask(true, true, true, true); gl.blendColor(0.0, 0.0, 0.0, 0.0); } + + private _onWebGLError (error: GLenum, functionName: string, ...args: any[]) { + throw new Error(`${WebGLDeveloperTools.glEnumToString(error)} was caused by call to ${functionName}`); + } } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 3b5e0c3bec..9de364d044 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -155,12 +155,8 @@ export class Pass { stride: 1, // N/A for blocks usage: GFXBufferUsageBit.UNIFORM, }); - if (buffer) { - this._buffers[u.binding] = buffer; - } else { - console.error('create buffer failed.'); - return; - } + if (buffer) { this._buffers[u.binding] = buffer; } + else { console.error('create buffer failed.'); return; } // buffer data processing system const block: IBlock = this._blocks[u.binding] = { buffer: buffer.buffer as ArrayBuffer, @@ -188,13 +184,12 @@ export class Pass { const inf = info.properties && info.properties[u.name]; const samplerInfo = Object.assign({ name: u.name }, inf && inf.sampler); const sampler = device.createSampler(samplerInfo); - if (sampler) { - this._samplers[u.binding] = sampler; - } else { - console.error('create sampler failed.'); - } + if (sampler) { this._samplers[u.binding] = sampler; } + else { console.error('create sampler failed.'); } const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; - this._textureViews[u.binding] = builtinResMgr.get(texName).getGFXTextureView()!; + const texture = builtinResMgr.get(texName); + if (texture) { this._textureViews[u.binding] = texture.getGFXTextureView()!; } + else { console.warn(`illegal texture default value ${texName}`); } } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 2bfc0a874f..7945b1bf94 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -125,6 +125,7 @@ class ProgramLib { if (program !== undefined) { return program; } + defines.CC_NUM_DIR_LIGHTS = 1; // get template const tmpl = this._templates[name]; diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index 95a7a179d2..e734f8f7d6 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -1,8 +1,12 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import Skeleton from '../../3d/assets/skeleton'; +import { createJointsTexture } from '../../3d/misc/utils'; import { Texture2D } from '../../assets/texture-2d'; +import { mat4 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXFeature } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Node } from '../../scene-graph/node'; import { Model } from '../scene/model'; @@ -11,9 +15,28 @@ import { SkinningUBO } from './model-uniforms'; const textureSizeBuffer = new Float32Array(4); +interface IJointTextureStorage { + nativeData: Float32Array; + texture: Texture2D; +} + +interface IJointUniformsStorage { + nativeData: Float32Array; +} + +type JointStorage = IJointTextureStorage | IJointUniformsStorage; + +function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { + return 'texture' in storage; +} + +function isUniformStorage (storage: JointStorage): storage is IJointUniformsStorage { + return !('texture' in storage); +} + export class SkinningModel extends Model { + private _jointStorage: JointStorage | null = null; private _skinningUBO: GFXBuffer; - private _jointTexture: Texture2D | null = null; constructor (scene: RenderScene, node: Node) { super(scene, node); @@ -26,27 +49,83 @@ export class SkinningModel extends Model { }); } - public setJointTexture (texture: Texture2D) { - this._jointTexture = texture; - textureSizeBuffer[0] = texture.width; - this._skinningUBO.update( + public bindSkeleton (skeleton: Skeleton) { + this._destroyJointStorage(); + + if (this._device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false) { + const jointsTexture = createJointsTexture(skeleton); + textureSizeBuffer[0] = jointsTexture.width; + this._skinningUBO.update( textureSizeBuffer, SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET, textureSizeBuffer.byteLength); + this._jointStorage = { + texture: jointsTexture, + nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), + } as IJointTextureStorage; + } else { + this._jointStorage = { + nativeData: new Float32Array(skeleton.joints.length * 16), + } as IJointUniformsStorage; + } } - public setJointMatrices (data: Float32Array) { - this._skinningUBO.update(data, SkinningUBO.MAT_JOINT_OFFSET); + public updateJointMatrix (iMatrix: number, matrix: mat4) { + if (!this._jointStorage) { + return; + } + _setJointMatrix(this._jointStorage.nativeData, iMatrix, matrix); + } + + public commitJointMatrices () { + if (!this._jointStorage) { + return; + } + if (isUniformStorage(this._jointStorage)) { + this._skinningUBO.update(this._jointStorage.nativeData, SkinningUBO.MAT_JOINT_OFFSET); + } else if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.directUpdate(this._jointStorage.nativeData.buffer); + } } protected _onCreatePSO (pso: GFXPipelineState) { super._onCreatePSO(pso); pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); - if (this._jointTexture) { - const view = this._jointTexture.getGFXTextureView(); - const sampler = this._jointTexture.getGFXSampler(); + if (this._jointStorage && isTextureStorage(this._jointStorage)) { + const jointTexture = this._jointStorage.texture; + const view = jointTexture.getGFXTextureView(); + const sampler = jointTexture.getGFXSampler(); if (view && sampler) { pso.pipelineLayout.layouts[0].bindTextureView(SkinningUBO.JOINT_TEXTURE.binding, view); pso.pipelineLayout.layouts[0].bindSampler(SkinningUBO.JOINT_TEXTURE.binding, sampler); } } } + + private _destroyJointStorage () { + if (!this._jointStorage) { + return; + } + if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.destroy(); + } + this._jointStorage = null; + } +} + +function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { + out[16 * iMatrix + 0] = matrix.m00; + out[16 * iMatrix + 1] = matrix.m01; + out[16 * iMatrix + 2] = matrix.m02; + out[16 * iMatrix + 3] = matrix.m03; + out[16 * iMatrix + 4] = matrix.m04; + out[16 * iMatrix + 5] = matrix.m05; + out[16 * iMatrix + 6] = matrix.m06; + out[16 * iMatrix + 7] = matrix.m07; + out[16 * iMatrix + 8] = matrix.m08; + out[16 * iMatrix + 9] = matrix.m09; + out[16 * iMatrix + 10] = matrix.m10; + out[16 * iMatrix + 11] = matrix.m11; + out[16 * iMatrix + 12] = matrix.m12; + out[16 * iMatrix + 13] = matrix.m13; + out[16 * iMatrix + 14] = matrix.m14; + out[16 * iMatrix + 15] = matrix.m15; } diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/renderer/scene/directional-light.ts index cde70935a4..c58f678aba 100644 --- a/cocos/renderer/scene/directional-light.ts +++ b/cocos/renderer/scene/directional-light.ts @@ -4,7 +4,7 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; export class DirectionalLight extends Light { - protected _direction = new Float32Array(4); + protected _direction = Float32Array.from([0, 0, 1, 0]); set direction (val: Vec3) { vec3.array(this._direction, val); diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts index 45379330e2..526b708991 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/renderer/scene/light.ts @@ -8,7 +8,7 @@ export enum LightType { } export class Light { - protected _color = new Float32Array(4); + protected _color = Float32Array.from([1, 1, 1, 1]); protected _enabled = false; set enabled (val) { diff --git a/cocos/renderer/scene/point-light.ts b/cocos/renderer/scene/point-light.ts index 68af391dc0..bfd677c175 100644 --- a/cocos/renderer/scene/point-light.ts +++ b/cocos/renderer/scene/point-light.ts @@ -4,7 +4,7 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; export class PointLight extends Light { - protected _positionAndRange = new Float32Array(4); + protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); set position (val: Vec3) { vec3.array(this._positionAndRange, val); diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts index 30ce89a366..dd56fd8c1f 100644 --- a/cocos/renderer/scene/spot-light.ts +++ b/cocos/renderer/scene/spot-light.ts @@ -4,8 +4,8 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; export class SpotLight extends Light { - protected _direction = new Float32Array(4); - protected _positionAndRange = new Float32Array(4); + protected _direction = Float32Array.from([0, 0, 1, 0]); + protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); set position (val: Vec3) { vec3.array(this._positionAndRange, val); diff --git a/globals.d.ts b/globals.d.ts index 163998848c..8c476a4668 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -45,4 +45,13 @@ type RecursivePartial = { [P in keyof T]?: T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; -}; \ No newline at end of file +}; + +declare module "webgl-debug" { + export function makeDebugContext( + webGLRenderingContext: WebGLRenderingContext, + throwOnGLError: (err: GLenum, funcName: string, ...args: any[]) => void + ): WebGLRenderingContext; + + export function glEnumToString(glEnum: GLenum): string; +} \ No newline at end of file diff --git a/package.json b/package.json index a4635ad24b..665a556c2d 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0", + "webgl-debug": "^2.0.1", "yargs": "^12.0.5" } } diff --git a/playground/simple.html b/playground/simple.html index aef133da14..b02fcdb872 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -68,7 +68,7 @@ const material = new cc.Material(); material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js - material.effectName = 'builtin-effect-phong'; + material.effectName = 'builtin-effect-pbr'; const len = 50; const models = [], passes = []; @@ -84,7 +84,7 @@ // material instance initialized here passes.push(modelCom.material.passes[0]); } - const handle = passes[0].getHandle('diffuseColor'); + const handle = passes[0].getHandle('albedo'); { const material = new cc.Material();