diff --git a/.gitignore b/.gitignore index 32e6862f36..a3c739bd6c 100644 --- a/.gitignore +++ b/.gitignore @@ -12,5 +12,3 @@ node_modules /.project npm-debug.log DebugInfos.json - -cocos/3d/builtin/effects/index.json diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js index f7762cd982..2ca8bbd685 100644 --- a/cocos/3d/assets/material.js +++ b/cocos/3d/assets/material.js @@ -63,7 +63,7 @@ class Material extends Asset { if (this.effectName !== val) this._setEffect(val); } get effectName() { - return this._effectAsset.name; + return this._effectAsset ? this._effectAsset.name : ''; } /** @@ -83,14 +83,7 @@ class Material extends Asset { * @param {Material} mat */ copy(mat) { - this.effectAsset = mat.effectAsset; - - for (let name in mat._defines) { - this.define(name, mat._defines[name]); - } - for (let name in mat._props) { - this.setProperty(name, mat._props[name]); - } + this._setEffect(mat.effectAsset); } /** @@ -101,11 +94,8 @@ class Material extends Asset { setProperty(name, val) { this._props[name] = val; if (this._effect) { - if (val instanceof Texture) { - this._effect.setProperty(name, val._texture); - } else { - this._effect.setProperty(name, val); - } + if (val instanceof Texture) this._effect.setProperty(name, val._texture); + else this._effect.setProperty(name, val); } } @@ -116,18 +106,11 @@ class Material extends Asset { */ define(name, val) { this._defines[name] = val; - if (this._effect) { - this._effect.define(name, val); - } + if (this._effect) this._effect.define(name, val); } onLoaded() { this._setEffect(this.effectAsset); - if (!this._effect) return; - for (let def in this._defines) - this._effect.define(def, this._defines[def]); - for (let prop in this._props) - this.setProperty(prop, this._props[prop]); } _setEffect(val) { @@ -137,7 +120,12 @@ class Material extends Asset { return; } this._effectAsset = effectAsset; - this._effect = effectAsset ? Effect.parseEffect(effectAsset) : null; + if (!effectAsset) return; + this._effect = Effect.parseEffect(effectAsset); + for (let def in this._defines) + this._effect.define(def, this._defines[def]); + for (let prop in this._props) + this.setProperty(prop, this._props[prop]); } static getInstantiatedMaterial(mat, rndCom) { diff --git a/cocos/3d/builtin/effects/font.effect b/cocos/3d/builtin/effects/font.effect deleted file mode 100644 index 8a88d716e8..0000000000 --- a/cocos/3d/builtin/effects/font.effect +++ /dev/null @@ -1,31 +0,0 @@ -%{ - "techniques": [ - { - "queue": "overlay", - "lod": 0, - "passes": [ - { - "vert": "sprite-vs:vert", - "frag": "sprite-fs:frag", - "stage": "default", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "one", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - } - } -%} diff --git a/cocos/3d/builtin/effects/gizmo.effect b/cocos/3d/builtin/effects/gizmo.effect deleted file mode 100644 index 60f03d3e0d..0000000000 --- a/cocos/3d/builtin/effects/gizmo.effect +++ /dev/null @@ -1,143 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 0, - "passes": [ - { - "vert": "gizmo-vs", - "frag": "gizmo-fs", - "stage": "default", - "cullMode": "none", - "depthTest": false, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "color": { - "type": "color4", - "value": [1, 1, 1, 1] - } - } -%} - -%% gizmo-vs { - attribute vec3 a_position; - attribute vec3 a_normal; - - uniform mat4 model; - uniform mat4 viewProj; - uniform mat3 normalMatrix; - - varying vec3 normal_w; - varying vec3 pos_w; - varying vec3 pos_l; - - void main () { - vec4 pos = vec4(a_position, 1); - - pos_l = a_position; - pos_w = (model * pos).xyz; - normal_w = normalMatrix * a_normal; - - gl_Position = viewProj * model * pos; - } -} - -%% gizmo-fs { - #include - #include - - uniform vec3 eye; - uniform vec4 color; - - varying vec3 normal_w; - varying vec3 pos_w; - varying vec3 pos_l; - - #if PLANE_CONTROLLER - #include - uniform float width; - uniform float height; - uniform float rotx; - uniform float roty; - uniform vec3 center; - vec3 rotation_x(vec3 v, float a) { - vec3 r; - r.x = v.x; - r.y = v.y*cos(a) - v.z*sin(a); - r.z = v.y*sin(a) + v.z*cos(a); - return r; - } - vec3 rotation_y(vec3 v, float a) { - vec3 r; - r.x = v.x*cos(a) + v.z*sin(a); - r.y = v.y; - r.z = -v.x*sin(a) + v.z*cos(a); - return r; - } - vec3 rotation_xy(vec3 v, float ax, float ay) { - return rotation_y(rotation_x(v, ax), ay); - } - struct Rect { - vec3 center; - vec3 dirx; - vec3 diry; - float halfx; - float halfy; - }; - void InitRect(out Rect rect) - { - rect.center = center; - rect.dirx = rotation_xy(vec3(1, 0, 0), rotx * PI2, roty * PI2); - rect.diry = rotation_xy(vec3(0, 1, 0), rotx * PI2, roty * PI2); - rect.halfx = 0.5 * width; - rect.halfy = 0.5 * height; - } - void InitRectPoints(Rect rect, out vec3 points[4]) - { - vec3 ex = rect.halfx * rect.dirx; - vec3 ey = rect.halfy * rect.diry; - - points[0] = rect.center - ex - ey; - points[1] = rect.center + ex - ey; - points[2] = rect.center + ex + ey; - points[3] = rect.center - ex + ey; - } - #endif - - void main () { - vec3 N = normalize(normal_w); - vec3 V = normalize(eye - pos_w); - - // vec3 L = normalize(vec3(1, 2, 3)); - // vec3 diffuse = color.rgb * (0.2 + max(0.0, dot(N, L)) * 0.8); - - vec3 points[4]; - #if PLANE_CONTROLLER - Rect rect; - InitRect(rect); - InitRectPoints(rect, points); - #else - // { center: (30, 40, 50), width: 40, height: 40, rotx: -0.125, roty: 0.125 } - points[0] = vec3(25.86, 25.86, 74.14); - points[1] = vec3(54.14, 25.86, 45.86); - points[2] = vec3(34.14, 54.14, 25.86); - points[3] = vec3(5.86, 54.14, 54.14); - #endif - - vec3 diffuse = color.rgb * (0.2 + LTC_Evaluate(N, V, pos_l, mat3(1), points) * 0.8); - - gl_FragColor = linearToGammaSpaceRGBA(vec4(diffuse, color.a)); - } -} diff --git a/cocos/3d/builtin/effects/grid.effect b/cocos/3d/builtin/effects/grid.effect deleted file mode 100644 index c6493372b7..0000000000 --- a/cocos/3d/builtin/effects/grid.effect +++ /dev/null @@ -1,178 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 100, - "passes": [ - { - "vert": "grid-vs", - "frag": "grid-fs", - "stage": "default" - } - ] - } - ], - - "properties": { - "tiling": { - "type": "vec2", - "value": [1, 1] - }, - "baseColorWhite": { - "type": "color3", - "value": [1, 1, 1] - }, - "baseColorBlack": { - "type": "color3", - "value": [0, 0, 0] - }, - "basePattern": { - "type": "sampler2D", - "value": null - }, - "basePatternTiling": { - "type": "vec2", - "value": [1, 1] - }, - "basePatternOffset": { - "type": "vec2", - "value": [0, 0] - }, - "subPatternColor": { - "type": "color4", - "value": [1, 1, 1, 1] - }, - "subPattern": { - "type": "sampler2D", - "value": null - }, - "subPatternTiling": { - "type": "vec2", - "value": [1, 1] - }, - "subPatternOffset": { - "type": "vec2", - "value": [0, 0] - }, - "subPatternColor2": { - "type": "color4", - "value": [1, 1, 1, 1] - }, - "subPattern2": { - "type": "sampler2D", - "value": null - }, - "subPattern2Tiling": { - "type": "vec2", - "value": [1, 1] - }, - "subPattern2Offset": { - "type": "vec2", - "value": [0, 0] - } - } -%} - - -%% grid-vs { - attribute vec2 a_uv0; - attribute vec3 a_position; - attribute vec3 a_normal; - - uniform mat4 model; - uniform mat4 viewProj; - - varying vec2 uv0; - varying vec4 pos_w; - - #if USE_WORLD_POS - uniform mat3 normalMatrix; - varying vec3 normal_w; - #endif - - void main () { - uv0 = a_uv0; - pos_w = model * vec4(a_position, 1); - - #if USE_WORLD_POS - normal_w = normalMatrix * a_normal; - #endif - - gl_Position = viewProj * pos_w; - } -} - -%% grid-fs { - varying vec2 uv0; - varying vec4 pos_w; - - #if USE_WORLD_POS - varying vec3 normal_w; - #endif - - uniform vec2 tiling; - - uniform vec3 baseColorWhite; - uniform vec3 baseColorBlack; - uniform sampler2D basePattern; - uniform vec2 basePatternTiling; - uniform vec2 basePatternOffset; - - uniform vec4 subPatternColor; - uniform sampler2D subPattern; - uniform vec2 subPatternTiling; - uniform vec2 subPatternOffset; - - uniform vec4 subPatternColor2; - uniform sampler2D subPattern2; - uniform vec2 subPattern2Tiling; - uniform vec2 subPattern2Offset; - - void main () { - vec2 uv = uv0 * tiling; - vec2 uvBase = uv * basePatternTiling + basePatternOffset; - vec2 uvSub = uv * subPatternTiling + subPatternOffset; - vec2 uvSub2 = uv * subPattern2Tiling + subPattern2Offset; - - #if USE_WORLD_POS - vec3 dnormal_w = normalize(normal_w); - - if (abs(dnormal_w.x)>0.5) { // side - uvBase = (pos_w.zy * tiling * basePatternTiling) + basePatternOffset; - uvSub = (pos_w.zy * tiling * subPatternTiling) + subPatternOffset; - uvSub2 = (pos_w.zy * tiling * subPattern2Tiling) + subPattern2Offset; - } else if (abs(dnormal_w.z)>0.5) { // front - uvBase = (pos_w.xy * tiling * basePatternTiling) + basePatternOffset; - uvSub = (pos_w.xy * tiling * subPatternTiling) + subPatternOffset; - uvSub2 = (pos_w.xy * tiling * subPattern2Tiling) + subPattern2Offset; - } else { // top - uvBase = (pos_w.xz * tiling * basePatternTiling) + basePatternOffset; - uvSub = (pos_w.xz * tiling * subPatternTiling) + subPatternOffset; - uvSub2 = (pos_w.xz * tiling * subPattern2Tiling) + subPattern2Offset; - } - #endif - - vec4 texColBase = texture2D(basePattern, uvBase); - vec4 texColSub = texture2D(subPattern, uvSub); - vec4 texColSub2 = texture2D(subPattern2, uvSub2); - - // texColBase.rgb = gammaToLinearSpace(texColBase.rgb); - // texColSub.rgb = gammaToLinearSpace(texColSub.rgb); - // texColSub2.rgb = gammaToLinearSpace(texColSub2.rgb); - - vec4 color = vec4(baseColorWhite,1) * texColBase + vec4(baseColorBlack,1) * (1.0-texColBase); - color = - color * (1.0 - texColSub) + - (subPatternColor * subPatternColor.a + color * (1.0-subPatternColor.a)) * texColSub - ; - color = - color * (1.0 - texColSub2) + - (subPatternColor2 * subPatternColor2.a + color * (1.0-subPatternColor2.a)) * texColSub2 - ; - - // gamma correction. - // color.rgb = linearToGammaSpace(color.rgb); - - gl_FragColor = color; - } -} diff --git a/cocos/3d/builtin/effects/line.effect b/cocos/3d/builtin/effects/line.effect deleted file mode 100644 index 5aeef3bbd8..0000000000 --- a/cocos/3d/builtin/effects/line.effect +++ /dev/null @@ -1,61 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 100, - "passes": [ - { - "vert": "line-vs", - "frag": "line-fs", - "stage": "default", - "depthTest": true - } - ] - } - ], - "properties": {} -%} - -%% line-vs { - attribute vec3 a_position; - attribute vec3 a_color; - - uniform mat4 model; - uniform mat4 viewProj; - - varying vec3 color; - - void main () { - vec4 pos = viewProj * model * vec4(a_position, 1); - - // // halp-pixel offset solution 1 - // vec4 pos = viewProj * model * vec4( - // floor(a_position.x) + 0.5, - // floor(a_position.y) + 0.5, - // a_position.z, - // 1 - // ); - - // halp-pixel offset solution 2 - // vec2 hpc = vec2(screen.x * 0.5, screen.y * 0.5); - // vec4 pos = viewProj * model * vec4(a_position, 1); - // pos = vec4( - // 2.0 * ((floor((pos.x + 1.0) * 0.5 * screen.x) + 0.5) / screen.x - 0.5), - // 2.0 * ((floor((pos.y + 1.0) * 0.5 * screen.y) - 0.5) / screen.y - 0.5), - // pos.z, - // pos.w - // ); - - color = a_color; - - gl_Position = pos; - } -} - -%% line-fs { - varying vec3 color; - - void main () { - gl_FragColor = vec4(color, 1.0); - } -} diff --git a/cocos/3d/builtin/effects/matcap.effect b/cocos/3d/builtin/effects/matcap.effect deleted file mode 100644 index e3fd1f2bb7..0000000000 --- a/cocos/3d/builtin/effects/matcap.effect +++ /dev/null @@ -1,98 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 100, - "passes": [ - { - "vert": "matcap-vs", - "frag": "matcap-fs", - "stage": "default", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "mainTex": { - "type": "sampler2D", - "value": null - }, - "matcapTex": { - "type": "sampler2D", - "value": null - }, - "colorFactor": { - "type": "float", - "value": 0.5 - }, - "color": { - "type": "color4", - "value": [1, 1, 1, 1] - } - } -%} - -%% matcap-vs { - attribute vec3 a_position; - attribute vec3 a_normal; - uniform mat4 model; - uniform mat4 viewProj; - uniform mat3 normalMatrix; - varying vec2 matcapUV; - - #if USE_MAIN_TEX - attribute vec2 a_uv0; - varying vec2 uv0; - #endif - - #if USE_SKINNING - #include - #endif - - void main(void){ - #if USE_MAIN_TEX - uv0 = a_uv0; - #endif - - vec4 pos = vec4(a_position, 1); - #if USE_SKINNING - mat4 skinMat = skinMatrix(); - pos = skinMat * pos; - #endif - pos = viewProj * model * pos; - gl_Position = pos; - - vec4 normal = vec4(a_normal, 0); - #if USE_SKINNING - normal = skinMat * normal; - #endif - normal = vec4(normalize(normalMatrix * normal.xyz), 0); - matcapUV = normal.xy; - matcapUV = matcapUV * 0.5 + 0.5; - } -} - -%% matcap-fs { - uniform sampler2D matcapTex; - uniform float colorFactor; - uniform vec4 color; - varying vec2 matcapUV; - - #if USE_MAIN_TEX - varying vec2 uv0; - uniform sampler2D mainTex; - #endif - - void main(void){ - vec4 col = vec4(1, 1, 1, 1); - col *= color; - #if USE_MAIN_TEX - col *= texture2D(mainTex, uv0); - #endif - vec4 matcapColor = texture2D(matcapTex, matcapUV); - gl_FragColor = col * colorFactor + matcapColor * (1.0 - colorFactor); - } -} diff --git a/cocos/3d/builtin/effects/particle-add-gpu.effect b/cocos/3d/builtin/effects/particle-add-gpu.effect deleted file mode 100644 index 026712f6f0..0000000000 --- a/cocos/3d/builtin/effects/particle-add-gpu.effect +++ /dev/null @@ -1,68 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 300, - "passes": [ - { - "vert": "particle-vs-gpu:gpvs_main", - "frag": "particle-add-gpu-fs", - "stage": "default", - "cullMode": "none", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "one", - "blendAlphaEq": "add", - "blendSrcAlpha": "srcAlpha", - "blendDstAlpha": "one" - } - ] - } - ], - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "tintColor": { - "type": "color4", - "value": [0.5, 0.5, 0.5, 0.5] - }, - "frameTile": { - "type": "vec2", - "value": [1, 1] - }, - "velocityScale": { - "type": "float", - "value": 0 - }, - "lengthScale": { - "type": "float", - "value": 0 - } - } -%} - -%% particle-add-gpu-fs { - uniform sampler2D mainTexture; - uniform vec4 tintColor; - - varying vec2 uv; - varying vec4 color; - - void main () { - // TODO: soft particle - gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv); - } -} diff --git a/cocos/3d/builtin/effects/particle-add-multiply.effect b/cocos/3d/builtin/effects/particle-add-multiply.effect deleted file mode 100644 index 3966245e3a..0000000000 --- a/cocos/3d/builtin/effects/particle-add-multiply.effect +++ /dev/null @@ -1,73 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 200, - "passes": [ - { - "vert": "particle-vs-legacy:lpvs_main", - "frag": "particle-add-multiply-fs", - "stage": "default", - "cullMode": "none", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "one", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "tintColor": { - "type": "color4", - "value": [0.5, 0.5, 0.5, 0.5] - }, - "frameTile": { - "type": "vec2", - "value": [1,1] - }, - "velocityScale": { - "type": "float", - "value": 0 - }, - "lengthScale": { - "type": "float", - "value": 0 - } - } -%} - -%% particle-add-multiply-fs { - uniform sampler2D mainTexture; - uniform vec4 tintColor; - - varying vec2 uv; - varying vec4 color; - - void main () { - // TODO: soft particle - vec4 col; - vec4 texColor = texture2D(mainTexture, uv); - col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0); - col.a = (1.0 - texColor.a) * (tintColor.a * color.a * 2.0); - gl_FragColor = col; - } -} diff --git a/cocos/3d/builtin/effects/particle-add-smooth.effect b/cocos/3d/builtin/effects/particle-add-smooth.effect deleted file mode 100644 index 36530a5b4a..0000000000 --- a/cocos/3d/builtin/effects/particle-add-smooth.effect +++ /dev/null @@ -1,65 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "passes": [ - { - "vert": "particle-vs-legacy:lpvs_main", - "frag": "particle-add-smooth-fs", - "stage": "default", - "cullMode": "none", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "one", - "blendDst": "oneMinusSrcColor", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcColor" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "frameTile": { - "type": "vec2", - "value": [1,1] - }, - "velocityScale": { - "type": "float", - "value": 0 - }, - "lengthScale": { - "type": "float", - "value": 0 - } - } -%} - -%% particle-add-smooth-fs { - uniform sampler2D mainTexture; - - varying vec2 uv; - varying vec4 color; - - void main () { - // TODO: soft particle - vec4 col = color * texture2D(mainTexture, uv); - col.rgb *= col.a; - gl_FragColor = col; - } -} diff --git a/cocos/3d/builtin/effects/particle-add.effect b/cocos/3d/builtin/effects/particle-add.effect deleted file mode 100644 index 65ec159a72..0000000000 --- a/cocos/3d/builtin/effects/particle-add.effect +++ /dev/null @@ -1,69 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 200, - "passes": [ - { - "vert": "particle-vs-legacy:lpvs_main", - "frag": "particle-add-fs", - "stage": "default", - "cullMode": "none", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "one", - "blendAlphaEq": "add", - "blendSrcAlpha": "srcAlpha", - "blendDstAlpha": "one" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "tintColor": { - "type": "color4", - "value": [0.5, 0.5, 0.5, 0.5] - }, - "frameTile": { - "type": "vec2", - "value": [1,1] - }, - "velocityScale": { - "type": "float", - "value": 0 - }, - "lengthScale": { - "type": "float", - "value": 0 - } - } -%} - -%% particle-add-fs { - uniform sampler2D mainTexture; - uniform vec4 tintColor; - - varying vec2 uv; - varying vec4 color; - - void main () { - // TODO: soft particle - gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv); - } -} diff --git a/cocos/3d/builtin/effects/particle-alpha-blend.effect b/cocos/3d/builtin/effects/particle-alpha-blend.effect deleted file mode 100644 index 51e773edb6..0000000000 --- a/cocos/3d/builtin/effects/particle-alpha-blend.effect +++ /dev/null @@ -1,69 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 200, - "passes": [ - { - "vert": "particle-vs-legacy:lpvs_main", - "frag": "particle-alpha-blend-fs", - "stage": "default", - "cullMode": "none", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "srcAlpha", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "tintColor": { - "type": "color4", - "value": [0.5, 0.5, 0.5, 0.5] - }, - "frameTile": { - "type": "vec2", - "value": [1,1] - }, - "velocityScale": { - "type": "float", - "value": 0 - }, - "lengthScale": { - "type": "float", - "value": 0 - } - } -%} - -%% particle-alpha-blend-fs { - uniform sampler2D mainTexture; - uniform vec4 tintColor; - - varying vec2 uv; - varying vec4 color; - - void main () { - // TODO: soft particle - gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv); - } -} diff --git a/cocos/3d/builtin/effects/particle-premultiply-blend.effect b/cocos/3d/builtin/effects/particle-premultiply-blend.effect deleted file mode 100644 index 2e072eff04..0000000000 --- a/cocos/3d/builtin/effects/particle-premultiply-blend.effect +++ /dev/null @@ -1,62 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "passes": [ - { - "vert": "particle-vs-legacy:lpvs_main", - "frag": "particle-premultiply-blend-fs", - "stage": "default", - "cullMode": "none", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "one", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "frameTile": { - "type": "vec2", - "value": [1,1] - }, - "velocityScale": { - "type": "float", - "value": 0 - }, - "lengthScale": { - "type": "float", - "value": 0 - } - } -%} - -%% particle-premultiply-blend-fs { - uniform sampler2D mainTexture; - varying vec2 uv; - varying vec4 color; - - void main () { - // TODO: soft particle - gl_FragColor = color * texture2D(mainTexture, uv) * color.a; - } -} diff --git a/cocos/3d/builtin/effects/pbr-transparent.effect b/cocos/3d/builtin/effects/pbr-transparent.effect deleted file mode 100644 index 7fc1d54e8b..0000000000 --- a/cocos/3d/builtin/effects/pbr-transparent.effect +++ /dev/null @@ -1,113 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 500, - "passes": [ - { - "vert": "pbr-vs:vert", - "frag": "pbr-fs:frag", - "stage": "forward", - "cullMode": "back", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - }, - { - "vert": "shadow-depth-vs:vert", - "frag": "shadow-depth-fs:frag", - "stage": "shadowcast", - "cullMode": "back", - "blendMode": "none", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "albedo": { - "type": "color4", - "value": [1, 1, 1, 1] - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "albedo_texture": { - "type": "sampler2D", - "value": null - }, - "metallic": { - "type": "float", - "value": 1 - }, - "metallic_texture": { - "type": "sampler2D", - "value": null - }, - "roughness": { - "type": "float", - "value": 0.5 - }, - "roughness_texture": { - "type": "sampler2D", - "value": null - }, - "ao": { - "type": "float", - "value": 0.2 - }, - "ao_texture": { - "type": "sampler2D", - "value": null - }, - "mra_texture": { - "type": "sampler2D", - "value": null - }, - "emissive": { - "type": "color3", - "value": [0, 0, 0] - }, - "emissive_texture": { - "type": "sampler2D", - "value": null - }, - "normal_texture": { - "type": "sampler2D", - "value": null - }, - "diffuseEnvTexture": { - "type": "samplerCube", - "value": null - }, - "specularEnvTexture": { - "type": "samplerCube", - "value": null - }, - "brdfLUT": { - "type": "sampler2D", - "value": null - }, - "maxReflectionLod": { - "type": "float", - "value": 9 - }, - "alphaTestThreshold": { - "type": "float", - "value": 0 - } - } -%} diff --git a/cocos/3d/builtin/effects/pbr.effect b/cocos/3d/builtin/effects/pbr.effect deleted file mode 100644 index 7cc6fb1b34..0000000000 --- a/cocos/3d/builtin/effects/pbr.effect +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 500, - "passes": [ - { - "vert": "pbr-vs:vert", - "frag": "pbr-fs:frag", - "stage": "forward", - "cullMode": "back", - "depthTest": true, - "depthWrite": true - }, - { - "vert": "shadow-depth-vs:vert", - "frag": "shadow-depth-fs:frag", - "stage": "shadowcast", - "cullMode": "back", - "blendMode": "none", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "albedo": { - "type": "color4", - "value": [1, 1, 1, 1] - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "albedo_texture": { - "type": "sampler2D", - "value": null - }, - "metallic": { - "type": "float", - "value": 1 - }, - "metallic_texture": { - "type": "sampler2D", - "value": null - }, - "roughness": { - "type": "float", - "value": 0.5 - }, - "roughness_texture": { - "type": "sampler2D", - "value": null - }, - "ao": { - "type": "float", - "value": 0.2 - }, - "ao_texture": { - "type": "sampler2D", - "value": null - }, - "mra_texture": { - "type": "sampler2D", - "value": null - }, - "emissive": { - "type": "color3", - "value": [0, 0, 0] - }, - "emissive_texture": { - "type": "sampler2D", - "value": null - }, - "normal_texture": { - "type": "sampler2D", - "value": null - }, - "diffuseEnvTexture": { - "type": "samplerCube", - "value": null - }, - "specularEnvTexture": { - "type": "samplerCube", - "value": null - }, - "brdfLUT": { - "type": "sampler2D", - "value": null - }, - "maxReflectionLod": { - "type": "float", - "value": 9 - } - } -%} diff --git a/cocos/3d/builtin/effects/phong-transparent.effect b/cocos/3d/builtin/effects/phong-transparent.effect deleted file mode 100644 index 39430e7cf4..0000000000 --- a/cocos/3d/builtin/effects/phong-transparent.effect +++ /dev/null @@ -1,80 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "lod": 200, - "passes": [ - { - "vert": "phong-vs:vert", - "frag": "phong-fs:frag", - "stage": "forward", - "cullMode": "back", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - }, - { - "vert": "shadow-depth-vs:vert", - "frag": "shadow-depth-fs:frag", - "stage": "shadowcast", - "cullMode": "back", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "diffuseColor": { - "type": "color4", - "value": [0.8, 0.8, 0.8, 1] - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "diffuse_texture": { - "type": "sampler2D", - "value": null - }, - "specularColor": { - "type": "color3", - "value": [0, 0, 0] - }, - "specular_texture": { - "type": "sampler2D", - "value": null - }, - "emissiveColor": { - "type": "color3", - "value": [0, 0, 0] - }, - "emissive_texture": { - "type": "sampler2D", - "value": null - }, - "glossiness": { - "type": "float", - "value": 10 - }, - "normal_texture": { - "type": "sampler2D", - "value": null - }, - "alphaTestThreshold": { - "type": "float", - "value": 0 - } - } -%} diff --git a/cocos/3d/builtin/effects/phong.effect b/cocos/3d/builtin/effects/phong.effect deleted file mode 100644 index 3af3a4341c..0000000000 --- a/cocos/3d/builtin/effects/phong.effect +++ /dev/null @@ -1,73 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 200, - "passes": [ - { - "vert": "phong-vs:vert", - "frag": "phong-fs:frag", - "stage": "forward", - "cullMode": "back", - "depthTest": true, - "depthWrite": true - }, - { - "vert": "shadow-depth-vs:vert", - "frag": "shadow-depth-fs:frag", - "stage": "shadowcast", - "cullMode": "back", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "diffuseColor": { - "type": "color4", - "value": [0.8, 0.8, 0.8, 1] - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "diffuse_texture": { - "type": "sampler2D", - "value": null - }, - "specularColor": { - "type": "color3", - "value": [0, 0, 0] - }, - "specular_texture": { - "type": "sampler2D", - "value": null - }, - "emissiveColor": { - "type": "color3", - "value": [0, 0, 0] - }, - "emissive_texture": { - "type": "sampler2D", - "value": null - }, - "glossiness": { - "type": "float", - "value": 10 - }, - "normal_texture": { - "type": "sampler2D", - "value": null - }, - "alphaTestThreshold": { - "type": "float", - "value": 0 - } - } -%} diff --git a/cocos/3d/builtin/effects/simple.effect b/cocos/3d/builtin/effects/simple.effect deleted file mode 100644 index a4d0592900..0000000000 --- a/cocos/3d/builtin/effects/simple.effect +++ /dev/null @@ -1,74 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "passes": [ - { - "vert": "sp-vs", - "frag": "sp-fs", - "stage": "default", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "color": { - "type": "color4", - "value": [0.4, 0.4, 0.4, 1] - } - } -%} - -%% sp-vs { - attribute vec3 a_position; - - uniform mat4 model; - uniform mat4 viewProj; - - #if USE_TEXTURE - attribute vec2 a_uv0; - varying vec2 uv0; - #endif - - void main () { - vec4 pos = viewProj * model * vec4(a_position, 1); - - #if USE_TEXTURE - uv0 = a_uv0; - #endif - - gl_Position = pos; - } -} - -%% sp-fs { - #if USE_TEXTURE - uniform sampler2D texture; - varying vec2 uv0; - #endif - - #if USE_COLOR - uniform vec4 color; - #endif - - void main () { - vec4 o = vec4(1, 1, 1, 1); - - #if USE_TEXTURE - o *= texture2D(texture, uv0); - #endif - - #if USE_COLOR - o *= color; - #endif - - if (!gl_FrontFacing) { - o.rgb *= 0.5; - } - - gl_FragColor = o; - } -} diff --git a/cocos/3d/builtin/effects/skybox.effect b/cocos/3d/builtin/effects/skybox.effect deleted file mode 100644 index 2da0f92bb8..0000000000 --- a/cocos/3d/builtin/effects/skybox.effect +++ /dev/null @@ -1,59 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "priority" : -1000, - "lod": 200, - "passes": [ - { - "vert": "sky-vs", - "frag": "sky-fs", - "stage": "default", - "cullMode": "none" - } - ] - } - ], - - "properties": { - "cubeMap": { - "type": "samplerCube", - "value": null - } - } -%} - -%% sky-vs { - attribute vec3 a_position; - - uniform mat4 view; - uniform mat4 proj; - - varying vec3 viewDir; - - void main() { - mat4 rotView = mat4(mat3(view)); - vec4 clipPos = proj * rotView * vec4(a_position, 1.0); - - gl_Position = clipPos.xyww; - viewDir = a_position; - } -} - -%% sky-fs { - varying vec3 viewDir; - - uniform samplerCube cubeMap; - #include - #include - - void main() { - #if USE_RGBE_CUBEMAP - vec3 c = unpackRGBE(textureCube(cubeMap, viewDir)); - c = linearToGammaSpaceRGB(c / (1.0 + c)); - gl_FragColor = vec4(c, 1.0); - #else - gl_FragColor = textureCube(cubeMap, viewDir); - #endif - } -} diff --git a/cocos/3d/builtin/effects/sprite.effect b/cocos/3d/builtin/effects/sprite.effect deleted file mode 100644 index ffcf041fb4..0000000000 --- a/cocos/3d/builtin/effects/sprite.effect +++ /dev/null @@ -1,30 +0,0 @@ -%{ - "techniques": [ - { - "queue": "overlay", - "passes": [ - { - "vert": "sprite-vs:vert", - "frag": "sprite-fs:frag", - "stage": "default", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "mainTexture": { - "type": "sampler2D", - "value": null - } - } -%} diff --git a/cocos/3d/builtin/effects/unlit-transparent.effect b/cocos/3d/builtin/effects/unlit-transparent.effect deleted file mode 100644 index 14901ac7ce..0000000000 --- a/cocos/3d/builtin/effects/unlit-transparent.effect +++ /dev/null @@ -1,43 +0,0 @@ -%{ - "techniques": [ - { - "queue": "transparent", - "passes": [ - { - "vert": "unlit-vs:vert", - "frag": "unlit-fs:frag", - "stage": "default", - "cullMode": "back", - "depthTest": true, - "depthWrite": false, - "blend": true, - "blendEq": "add", - "blendSrc": "srcAlpha", - "blendDst": "oneMinusSrcAlpha", - "blendAlphaEq": "add", - "blendSrcAlpha": "one", - "blendDstAlpha": "oneMinusSrcAlpha" - } - ] - } - ], - - "properties": { - "color": { - "type": "color4", - "value": [1, 1, 1, 1] - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "mainTexture": { - "type": "sampler2D", - "value": null - } - } -%} diff --git a/cocos/3d/builtin/effects/unlit.effect b/cocos/3d/builtin/effects/unlit.effect deleted file mode 100644 index 505f78ed84..0000000000 --- a/cocos/3d/builtin/effects/unlit.effect +++ /dev/null @@ -1,37 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 100, - "passes": [ - { - "vert": "unlit-vs:vert", - "frag": "unlit-fs:frag", - "stage": "default", - "cullMode": "back", - "depthTest": true, - "depthWrite": true - } - ] - } - ], - - "properties": { - "color": { - "type": "color4", - "value": [1, 1, 1, 1] - }, - "mainTiling": { - "type": "vec2", - "value": [1, 1] - }, - "mainOffset": { - "type": "vec2", - "value": [0, 0] - }, - "mainTexture": { - "type": "sampler2D", - "value": null - } - } -%} diff --git a/cocos/3d/builtin/effects/wireframe.effect b/cocos/3d/builtin/effects/wireframe.effect deleted file mode 100644 index 7574cce171..0000000000 --- a/cocos/3d/builtin/effects/wireframe.effect +++ /dev/null @@ -1,60 +0,0 @@ -%{ - "techniques": [ - { - "queue": "opaque", - "lod": 100, - "passes": [ - { - "vert": "wire-vs", - "frag": "wire-fs", - "stage": "default", - "depthTest": true - } - ] - } - ], - "properties": { - "color": { - "type": "color3", - "value": [1, 1, 1] - } - } -%} - -%% wire-vs { - attribute vec3 a_position; - attribute vec3 a_normal; - - uniform mat4 model, viewProj; - uniform mat3 normalMatrix; - - varying vec3 position_w; - varying vec3 normal_w; - - void main () { - vec4 pos = vec4(a_position, 1); - - position_w = (model * pos).xyz; - pos = viewProj * model * pos; - normal_w = normalMatrix * a_normal.xyz; - - gl_Position = pos; - } -} - -%% wire-fs { - uniform vec3 eye; - uniform vec3 color; - - varying vec3 position_w; - varying vec3 normal_w; - - void main () { - gl_FragColor = vec4(color, 1.0); - - vec3 V = normalize(eye - position_w); - if (dot (normal_w, V) <= 0.0) { - gl_FragColor.rgb *= 0.6; - } - } -} diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index 2bfd07217f..61dcd0d76e 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -1,10 +1,13 @@ import Texture2D from '../../assets/CCTexture2D'; import TextureCube from '../assets/texture-cube'; import ImageAsset from '../../assets/image-asset'; +import Material from '../assets/material'; +import EffectAsset from '../assets/effect-asset'; let builtinResMgr = { // this should be called after renderer initialized - initBuiltinRes: function(device, effectUUIDs, OnComplete) { + initBuiltinRes: function(device) { + builtinResMgr.device = device; let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); @@ -69,28 +72,45 @@ let builtinResMgr = { whiteTexture._uuid = 'white-texture'; defaultTexture.image = canvasImage; + // classic ugly pink indicating missing material + let pinkEffect = new EffectAsset(); + pinkEffect.name = 'default'; + pinkEffect.techniques.push({ passes: [{ program: 'default' }] }); + pinkEffect.shaders.push({ + name: 'default', + vert: `attribute vec3 a_position; \n uniform mat4 _model; \n uniform mat4 _viewProj; \n void main() { gl_Position = _viewProj * _model * vec4(a_position, 1); }`, + frag: `void main() { gl_FragColor = vec4(1, 0, 1, 1); }`, + uniforms: [], defines: [], attributes: [], extensions: [] + }); + pinkEffect.onLoaded(); + let defaultMtl = new Material(); + defaultMtl._uuid = 'default-material'; + defaultMtl.effectAsset = pinkEffect; + let builtins = { [defaultTexture._uuid]: defaultTexture, [defaultTextureCube._uuid]: defaultTextureCube, [blackTexture._uuid]: blackTexture, [whiteTexture._uuid]: whiteTexture, + [defaultMtl._uuid]: defaultMtl }; - + return Object.assign(builtinResMgr, builtins); + }, + initEffects(effectUUIDs, OnComplete) { // ============================ // async builtin effects // ============================ - let remainingJobs = effectUUIDs.length; for (let i = 0; i < effectUUIDs.length; ++i) { let uuid = effectUUIDs[i]; cc.AssetLibrary.loadAsset(uuid, (err, asset) => { if (err) { console.error(err); return; } cc.EffectAsset.register(asset); - if (!--remainingJobs) OnComplete(builtins); + if (!--remainingJobs) OnComplete(builtinResMgr); }); } - }, + } }; -cc._builtinResMgr = builtinResMgr; +cc.BuiltinResMgr = builtinResMgr; export default builtinResMgr; diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index a3d63cf76c..e5a5e0ab73 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -71,7 +71,7 @@ let CameraProjection = Enum({ @ccclass('cc.CameraComponent') @menu('Components/CameraComponent') export default class CameraComponent extends RenderSystemActor{ - @property + @property(CameraProjection) _projection = CameraProjection.Perspective; @property diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index e29e17835a..eec836ed2a 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -275,13 +275,6 @@ export default class ModelComponent extends RenderableComponent { _getBuiltinMaterial() { // classic ugly pink indicating missing material - if (ModelComponent._builtinMaterial === null) { - const builtinMaterial = new cc.Material(); - builtinMaterial.effectName = 'builtin-effect-unlit'; - builtinMaterial.define("USE_COLOR", true); - builtinMaterial.setProperty("color", new cc.Color(255, 0, 255, 255)); - ModelComponent._builtinMaterial = builtinMaterial; - } - return ModelComponent._builtinMaterial; + return cc.BuiltinResMgr['default-material']; } } diff --git a/cocos/3d/misc/offline-mappings.js b/cocos/3d/misc/offline-mappings.js deleted file mode 100644 index ae71cc5960..0000000000 --- a/cocos/3d/misc/offline-mappings.js +++ /dev/null @@ -1,77 +0,0 @@ -// this file is used for offline effect building. - -import { enums } from '../../renderer/gfx/enums'; -import rendererEnums from '../../renderer/enums'; -import { RenderQueue, PassStage } from '../../renderer/core/constants'; - -const typeParams = { - INT: rendererEnums.PARAM_INT, - IVEC2: rendererEnums.PARAM_INT2, - IVEC3: rendererEnums.PARAM_INT3, - IVEC4: rendererEnums.PARAM_INT4, - FLOAT: rendererEnums.PARAM_FLOAT, - VEC2: rendererEnums.PARAM_FLOAT2, - VEC3: rendererEnums.PARAM_FLOAT3, - VEC4: rendererEnums.PARAM_FLOAT4, - COLOR3: rendererEnums.PARAM_COLOR3, - COLOR4: rendererEnums.PARAM_COLOR4, - MAT2: rendererEnums.PARAM_MAT2, - MAT3: rendererEnums.PARAM_MAT3, - MAT4: rendererEnums.PARAM_MAT4, - SAMPLER2D: rendererEnums.PARAM_TEXTURE_2D, - SAMPLERCUBE: rendererEnums.PARAM_TEXTURE_CUBE, - [rendererEnums.PARAM_FLOAT3]: rendererEnums.PARAM_COLOR3, - [rendererEnums.PARAM_FLOAT4]: rendererEnums.PARAM_COLOR4 -}; - -const passParams = { - BACK: enums.CULL_BACK, - FRONT: enums.CULL_FRONT, - NONE: enums.CULL_NONE, - - ADD: enums.BLEND_FUNC_ADD, - SUBTRACT: enums.BLEND_FUNC_SUBTRACT, - REVERSESUBTRACT: enums.BLEND_FUNC_REVERSE_SUBTRACT, - ZERO: enums.BLEND_ZERO, - ONE: enums.BLEND_ONE, - SRCCOLOR: enums.BLEND_SRC_COLOR, - ONEMINUSSRCCOLOR: enums.BLEND_ONE_MINUS_SRC_COLOR, - DSTCOLOR: enums.BLEND_DST_COLOR, - ONEMINUSDSTCOLOR: enums.BLEND_ONE_MINUS_DST_COLOR, - SRCALPHA: enums.BLEND_SRC_ALPHA, - ONEMINUSSRCALPHA: enums.BLEND_ONE_MINUS_SRC_ALPHA, - DSTALPHA: enums.BLEND_DST_ALPHA, - ONEMINUSDSTALPHA: enums.BLEND_ONE_MINUS_DST_ALPHA, - CONSTCOLOR: enums.BLEND_CONSTANT_COLOR, - ONEMINUSCONSTCOLOR: enums.BLEND_ONE_MINUS_CONSTANT_COLOR, - CONSTALPHA: enums.BLEND_CONSTANT_ALPHA, - ONEMINUSCONSTALPHA: enums.BLEND_ONE_MINUS_CONSTANT_ALPHA, - SRCALPHASATURATE: enums.BLEND_SRC_ALPHA_SATURATE, - - NEVER: enums.DS_FUNC_NEVER, - LESS: enums.DS_FUNC_LESS, - EQUAL: enums.DS_FUNC_EQUAL, - LEQUAL: enums.DS_FUNC_LEQUAL, - GREATER: enums.DS_FUNC_GREATER, - NOTEQUAL: enums.DS_FUNC_NOTEQUAL, - GEQUAL: enums.DS_FUNC_GEQUAL, - ALWAYS: enums.DS_FUNC_ALWAYS, - - KEEP: enums.STENCIL_OP_KEEP, - REPLACE: enums.STENCIL_OP_REPLACE, - INCR: enums.STENCIL_OP_INCR, - INCR_WRAP: enums.STENCIL_OP_INCR_WRAP, - DECR: enums.STENCIL_OP_DECR, - DECR_WRAP: enums.STENCIL_OP_DECR_WRAP, - INVERT: enums.STENCIL_OP_INVERT -}; - -Object.assign(passParams, PassStage); - -let mappings = { - typeParams, - passParams, - RenderQueue -}; - -export default mappings; diff --git a/cocos/3d/primitive/capsule.js b/cocos/3d/primitive/capsule.js index 6755f095c1..cf481a05a7 100644 --- a/cocos/3d/primitive/capsule.js +++ b/cocos/3d/primitive/capsule.js @@ -17,8 +17,8 @@ let temp2 = vec3.create(0, 0, 0); */ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts = {}) { let torsoHeight = height - radiusTop - radiusBottom; - let sides = opts.sides || 16; - let heightSegments = opts.heightSegments || 10; + let sides = opts.sides || 32; + let heightSegments = opts.heightSegments || 32; let bottomProp = radiusBottom / height; let torProp = torsoHeight / height; let topProp = radiusTop / height; diff --git a/cocos/3d/primitive/cylinder.js b/cocos/3d/primitive/cylinder.js index 7d2ff36119..60ed0a8b6c 100644 --- a/cocos/3d/primitive/cylinder.js +++ b/cocos/3d/primitive/cylinder.js @@ -17,7 +17,7 @@ let temp2 = vec3.create(0, 0, 0); */ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts = {}) { let halfHeight = height * 0.5; - let radialSegments = opts.radialSegments || 8; + let radialSegments = opts.radialSegments || 32; let heightSegments = opts.heightSegments || 1; let capped = opts.capped !== undefined ? opts.capped : true; let arc = opts.arc || 2.0 * Math.PI; diff --git a/cocos/3d/primitive/plane.js b/cocos/3d/primitive/plane.js index 3146619908..d20e25ec7f 100644 --- a/cocos/3d/primitive/plane.js +++ b/cocos/3d/primitive/plane.js @@ -17,9 +17,9 @@ let c01 = vec3.create(0, 0, 0); * @param {Number} opts.widthSegments * @param {Number} opts.lengthSegments */ -export default function (width, length, opts = {}) { - let uSegments = opts.widthSegments !== undefined ? opts.widthSegments : 5; - let vSegments = opts.lengthSegments !== undefined ? opts.lengthSegments : 5; +export default function (width = 10, length = 10, opts = {}) { + let uSegments = opts.widthSegments !== undefined ? opts.widthSegments : 10; + let vSegments = opts.lengthSegments !== undefined ? opts.lengthSegments : 10; let hw = width * 0.5; let hl = length * 0.5; diff --git a/cocos/3d/primitive/sphere.js b/cocos/3d/primitive/sphere.js index 8747f1feea..f7e1037801 100644 --- a/cocos/3d/primitive/sphere.js +++ b/cocos/3d/primitive/sphere.js @@ -8,7 +8,7 @@ import { vec3 } from '../../core/vmath'; * @param {Number} opts.segments */ export default function (radius = 0.5, opts = {}) { - let segments = opts.segments !== undefined ? opts.segments : 16; + let segments = opts.segments !== undefined ? opts.segments : 32; // lat === latitude // lon === longitude @@ -64,4 +64,4 @@ export default function (radius = 0.5, opts = {}) { maxPos, boundingRadius }; -} \ No newline at end of file +} diff --git a/cocos/3d/primitive/torus.js b/cocos/3d/primitive/torus.js index 4fbad98c6a..30967c2f50 100644 --- a/cocos/3d/primitive/torus.js +++ b/cocos/3d/primitive/torus.js @@ -9,9 +9,9 @@ import { vec3 } from '../../core/vmath'; * @param {Number} opts.tubularSegments * @param {Number} opts.arc */ -export default function (radius = 0.5, tube = 0.2, opts = {}) { - let radialSegments = opts.radialSegments || 30; - let tubularSegments = opts.tubularSegments || 20; +export default function (radius = 0.4, tube = 0.1, opts = {}) { + let radialSegments = opts.radialSegments || 32; + let tubularSegments = opts.tubularSegments || 32; let arc = opts.arc || 2.0 * Math.PI; let positions = []; @@ -66,4 +66,4 @@ export default function (radius = 0.5, tube = 0.2, opts = {}) { maxPos, boundingRadius }; -} \ No newline at end of file +} diff --git a/cocos/3d/primitive/utils.js b/cocos/3d/primitive/utils.js index e0bb24bc09..2af0fc3e5e 100644 --- a/cocos/3d/primitive/utils.js +++ b/cocos/3d/primitive/utils.js @@ -23,6 +23,34 @@ export function wireframe(indices) { return lines; } +/** + * @param {Array} indices + */ +export function invWinding(indices) { + let newIB = []; + for (let i = 0; i < indices.length; i += 3) + newIB.push(indices[i], indices[i + 2], indices[i + 1]); + return newIB; +} + +/** + * @param {Array} indices + */ +export function toWavefrontOBJ(primitive) { + let v = primitive.positions, t = primitive.uvs, n = primitive.normals, IB = primitive.indices; + let V = i => `${IB[i]+1}/${IB[i]+1}/${IB[i]+1}`; + let content = ''; + for (let i = 0; i < v.length; i += 3) + content += `v ${v[i]} ${v[i+1]} ${v[i+2]}\n`; + for (let i = 0; i < t.length; i += 2) + content += `vt ${t[i]} ${t[i+1]}\n`; + for (let i = 0; i < n.length; i += 3) + content += `vn ${n[i]} ${n[i+1]} ${n[i+2]}\n`; + for (let i = 0; i < IB.length; i += 3) + content += `f ${V(i)} ${V(i+1)} ${V(i+2)}\n`; + return content; +} + /** * @param {Array} positions * @param {Array} normals diff --git a/cocos/core/CCGame.js b/cocos/core/CCGame.js index 4d863d7e11..201a0dbe0e 100644 --- a/cocos/core/CCGame.js +++ b/cocos/core/CCGame.js @@ -364,17 +364,17 @@ var game = { // Init engine this._initEngine(); - this._initBuiltins(this.config.effects, () => { - // Log engine version - console.log('Cocos3D v' + cc.ENGINE_VERSION); + this._initBuiltins(); - this._setAnimFrame(); - this._runMainLoop(); + // Log engine version + console.log('Cocos3D v' + cc.ENGINE_VERSION); - this.emit(this.EVENT_GAME_INITED); + this._setAnimFrame(); + this._runMainLoop(); - if (cb) cb(); - }); + this.emit(this.EVENT_GAME_INITED); + + if (cb) cb(); }, eventTargetOn: EventTarget.prototype.on, @@ -795,13 +795,11 @@ var game = { this._rendererInitialized = true; }, - _initBuiltins: function(effectUUIDs, cb) { - builtinResMgr.initBuiltinRes(this._renderContext, effectUUIDs, (builtins) => { - this._renderer.setBuiltins({ - defaultTexture: builtins['default-texture']._texture, - defaultTextureCube: builtins['default-texture-cube']._texture, - }); - if (cb) cb(); + _initBuiltins: function() { + let builtins = builtinResMgr.initBuiltinRes(this._renderContext); + this._renderer.setBuiltins({ + defaultTexture: builtins['default-texture']._texture, + defaultTextureCube: builtins['default-texture-cube']._texture, }); }, diff --git a/cocos/core/vmath/quat.js b/cocos/core/vmath/quat.js index 0af1250a8e..ef6fc7bd51 100644 --- a/cocos/core/vmath/quat.js +++ b/cocos/core/vmath/quat.js @@ -744,12 +744,12 @@ class quat { let x = q.x, y = q.y, z = q.z, w = q.w; let heading, attitude, bank; let test = x * y + z * w; - if (test > 0.499) { // singularity at north pole + if (test > 0.499999) { // singularity at north pole heading = 2 * Math.atan2(x,w); attitude = Math.PI/2; bank = 0; } - if (test < -0.499) { // singularity at south pole + if (test < -0.499999) { // singularity at south pole heading = -2 * Math.atan2(x,w); attitude = - Math.PI/2; bank = 0; diff --git a/cocos/renderer/bin/chunks/common.inc b/cocos/renderer/bin/chunks/common.inc deleted file mode 100644 index d1865226c8..0000000000 --- a/cocos/renderer/bin/chunks/common.inc +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -// common module - -// constant value -#define PI 3.14159265359 -#define PI2 6.28318530718 -#define EPSILON 1e-6 -#define LOG2 1.442695 - -// common function -#define saturate(a) clamp( a, 0.0, 1.0 ) \ No newline at end of file diff --git a/cocos/renderer/bin/chunks/gamma-correction.inc b/cocos/renderer/bin/chunks/gamma-correction.inc deleted file mode 100644 index a824b2b122..0000000000 --- a/cocos/renderer/bin/chunks/gamma-correction.inc +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -// sRGB-linear transform approximation -// http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html -vec3 gammaToLinearSpaceRGB(vec3 sRGB) { // TODO: use half maybe better. - return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878); -} - -vec3 linearToGammaSpaceRGB(vec3 RGB) { // TODO: use half maybe better. - vec3 S1 = sqrt(RGB); - vec3 S2 = sqrt(S1); - vec3 S3 = sqrt(S2); - return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3; -} - -vec4 gammaToLinearSpaceRGBA(vec4 sRGBA) { - return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a); -} - -vec4 linearToGammaSpaceRGBA(vec4 RGBA) { - return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a); -} - -// exact version -float gammaToLinearSpaceExact(float val) { - if (val <= 0.04045) { - return val / 12.92; - } else if (val < 1.0) { - return pow((val + 0.055) / 1.055, 2.4); - } else { - return pow(val, 2.2); - } -} - -float linearToGammaSpaceExact(float val) { - if (val <= 0.0) { - return 0.0; - } else if (val <= 0.0031308) { - return 12.92 * val; - } else if (val < 1.0) { - return 1.055 * pow(val, 0.4166667) - 0.055; - } else { - return pow(val, 0.45454545); - } -} \ No newline at end of file diff --git a/cocos/renderer/bin/chunks/packing.inc b/cocos/renderer/bin/chunks/packing.inc deleted file mode 100644 index 5b1518d33b..0000000000 --- a/cocos/renderer/bin/chunks/packing.inc +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -vec4 packDepthToRGBA(float depth) { - vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth; - ret = fract(ret); - ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); - return ret; -} - -float unpackRGBAToDepth(vec4 color) { - return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)); -} \ No newline at end of file diff --git a/cocos/renderer/bin/chunks/particle-common.inc b/cocos/renderer/bin/chunks/particle-common.inc deleted file mode 100644 index f454db1bb8..0000000000 --- a/cocos/renderer/bin/chunks/particle-common.inc +++ /dev/null @@ -1,65 +0,0 @@ - -uniform vec2 frameTile; -uniform vec2 mainTiling; -uniform vec2 mainOffset; -uniform mat4 model; -uniform mat4 viewProj; -uniform mat4 view; - -#if USE_STRETCHED_BILLBOARD - uniform vec3 eye; - uniform float velocityScale; - uniform float lengthScale; -#endif - -varying vec2 uv; -varying vec4 color; - -void computeVertPos(inout vec4 pos, vec2 vertOffset -#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD - , mat4 view -#endif -#if USE_STRETCHED_BILLBOARD - , vec3 eye - , vec4 velocity - , float velocityScale - , float lengthScale - , float size - , float xIndex -#endif -) { -#if USE_BILLBOARD - vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0])); - vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1])); - pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y); -#elif USE_STRETCHED_BILLBOARD - vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)); - vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size; - pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex; -#elif USE_HORIZONTAL_BILLBOARD - vec3 camRight = vec3(1, 0, 0); - vec3 camUp = vec3(0, 0, -1); - pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y); -#elif USE_VERTICAL_BILLBOARD - vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0])); - vec3 camUp = vec3(0, 1, 0); - pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y); -#else - pos.x += vertOffset.x; - pos.y += vertOffset.y; -#endif -} - -vec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) { - vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y)); - aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x); - aniUV.y = frameTile.y - aniUV.y - 1.0; - return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y); -} - -void rotateCorner(inout vec2 corner, float angle) { - float xOS = cos(angle) * corner.x - sin(angle) * corner.y; - float yOS = sin(angle) * corner.x + cos(angle) * corner.y; - corner.x = xOS; - corner.y = yOS; -} diff --git a/cocos/renderer/bin/chunks/particle-vs-gpu.inc b/cocos/renderer/bin/chunks/particle-vs-gpu.inc deleted file mode 100644 index 766e4b4abc..0000000000 --- a/cocos/renderer/bin/chunks/particle-vs-gpu.inc +++ /dev/null @@ -1,377 +0,0 @@ - -#include -#define MAX_KEY_NUM 8 -#define CURVE_MODE_CONSTANT 0 -#define CURVE_MODE_RANDOM_CONSTANT 1 -#define CURVE_MODE_CURVE 2 -#define CURVE_MODE_RANDOM_CURVE 3 - -#define GRADIENT_MODE_FIX 0 -#define GRADIENT_MODE_BLEND 1 - -#define GRADIENT_RANGE_MODE_COLOR 0 -#define GRADIENT_RANGE_MODE_TWO_COLOR 1 -#define GRADIENT_RANGE_MODE_RANDOM_COLOR 2 -#define GRADIENT_RANGE_MODE_GRADIENT 3 -#define GRADIENT_RANGE_MODE_TWO_GRADIENT 4 - -#define SIMULATE_SPACE_LOCAL 0 -#define SIMULATE_SPACE_WORLD 1 - -#define ANIMATION_MODE_WHOLE_SHEET 0 -#define ANIMATION_MODE_SINGLE_ROW 1 - -#define COLOR_OVERTIME_RAND_OFFSET 91041. -#define FORCE_OVERTIME_RAND_OFFSET 212165. -#define ROTATION_OVERTIME_RAND_OFFSET 125292. -#define SIZE_OVERTIME_RAND_OFFSET 39825. -#define TEXTURE_ANIMATION_RAND_OFFSET 90794. -#define VELOCITY_OVERTIME_RAND_OFFSET 197866. - -#define DECL_CURVE_STRUCT(name) \ - uniform int u_##name##_curveMode; \ - uniform float u_##name##_minConstant; \ - uniform float u_##name##_maxConstant; \ - uniform vec4 u_##name##_minKeyCoef[MAX_KEY_NUM]; \ - uniform float u_##name##_minKeyTime[MAX_KEY_NUM]; \ - uniform vec4 u_##name##_maxKeyCoef[MAX_KEY_NUM]; \ - uniform float u_##name##_maxKeyTime[MAX_KEY_NUM]; - -#define DECL_CURVE_STRUCT_INT(name) \ - DECL_CURVE_STRUCT(name) \ - uniform float u_##name##_minIntegral[MAX_KEY_NUM - 1]; \ - uniform float u_##name##_maxIntegral[MAX_KEY_NUM - 1]; - -#define DECL_GRADIENT_STRUCT(name) \ - uniform int u_##name##_rangeMode; \ - uniform vec4 u_##name##_minColor; \ - uniform vec4 u_##name##_maxColor; \ - uniform int u_##name##_minGradMode; \ - uniform vec3 u_##name##_minColorKeyValue[MAX_KEY_NUM]; \ - uniform float u_##name##_minColorKeyTime[MAX_KEY_NUM]; \ - uniform float u_##name##_minAlphaKeyValue[MAX_KEY_NUM]; \ - uniform float u_##name##_minAlphaKeyTime[MAX_KEY_NUM]; \ - uniform int u_##name##_maxGradMode; \ - uniform vec3 u_##name##_maxColorKeyValue[MAX_KEY_NUM]; \ - uniform float u_##name##_maxColorKeyTime[MAX_KEY_NUM]; \ - uniform float u_##name##_maxAlphaKeyValue[MAX_KEY_NUM]; \ - uniform float u_##name##_maxAlphaKeyTime[MAX_KEY_NUM]; - -#define EVAL_CURVE_RANGE(name, t, rnd) \ - evaluateCurveRange(u_##name##_curveMode, u_##name##_minConstant, u_##name##_maxConstant, u_##name##_minKeyTime, u_##name##_minKeyCoef, u_##name##_maxKeyTime, u_##name##_maxKeyCoef, t, rnd) - -#define EVAL_CURVE_INTEGRAL(name, t, ts, rnd) \ - evaluateCurveRangeIntegral(u_##name##_curveMode, u_##name##_minConstant, u_##name##_maxConstant, u_##name##_minKeyTime, u_##name##_minKeyCoef, u_##name##_minIntegral, u_##name##_maxKeyTime, u_##name##_maxKeyCoef, u_##name##_maxIntegral, t, ts, rnd) - -#define EVAL_CURVE_INTEGRAL_TWICE(name, t, ts, rnd) \ - evaluateCurveRangeIntegralTwice(u_##name##_curveMode, u_##name##_minConstant, u_##name##_maxConstant, u_##name##_minKeyTime, u_##name##_minKeyCoef, u_##name##_minIntegral, u_##name##_maxKeyTime, u_##name##_maxKeyCoef, u_##name##_maxIntegral, t, ts, rnd) - -#define EVAL_GRADIENT_RANGE(name, t, rnd) \ - evaluateGradientRange(u_##name##_rangeMode, u_##name##_minColor, u_##name##_maxColor, \ - u_##name##_minGradMode, u_##name##_minColorKeyValue, u_##name##_minColorKeyTime, u_##name##_minAlphaKeyValue, u_##name##_minAlphaKeyTime, \ - u_##name##_maxGradMode, u_##name##_maxColorKeyValue, u_##name##_maxColorKeyTime, u_##name##_maxAlphaKeyValue, u_##name##_maxAlphaKeyTime, t, rnd); - -attribute vec4 a_position_starttime; // center position,particle start time -attribute vec4 a_vertIdx_size_angle; // xy:vertex index,z:size,w:angle -attribute vec4 a_color; -attribute vec4 a_dir_life; // xyz:particle start velocity,w:particle lifetime -attribute float a_rndSeed; - -uniform float u_psTime; -uniform vec4 u_worldRot; - -#if VELOCITY_OVERTIME_MODULE_ENABLE -uniform int u_velocity_space; -uniform float u_speedModifier; -DECL_CURVE_STRUCT_INT(velocity_pos_x) -DECL_CURVE_STRUCT_INT(velocity_pos_y) -DECL_CURVE_STRUCT_INT(velocity_pos_z) - #if USE_STRETCHED_BILLBOARD - DECL_CURVE_STRUCT(velocity_x) - DECL_CURVE_STRUCT(velocity_y) - DECL_CURVE_STRUCT(velocity_z) - #endif -#endif - -#if FORCE_OVERTIME_MODULE_ENABLE -uniform int u_force_space; -DECL_CURVE_STRUCT_INT(force_pos_x) -DECL_CURVE_STRUCT_INT(force_pos_y) -DECL_CURVE_STRUCT_INT(force_pos_z) - #if USE_STRETCHED_BILLBOARD - DECL_CURVE_STRUCT_INT(force_vel_x) - DECL_CURVE_STRUCT_INT(force_vel_y) - DECL_CURVE_STRUCT_INT(force_vel_z) - #endif -#endif - -#if SIZE_OVERTIME_MODULE_ENABLE -DECL_CURVE_STRUCT(size) -#endif - -#if COLOR_OVERTIME_MODULE_ENABLE -DECL_GRADIENT_STRUCT(color) -#endif - -#if TEXTURE_ANIMATION_ENABLE -DECL_CURVE_STRUCT(frameOverTime) -uniform float u_cycles; -uniform int u_animation_mode; -uniform bool u_random_row; -uniform int u_row_index; -#endif - -#if ROTATE_OVERTIME_MODULE_ENABLE -DECL_CURVE_STRUCT_INT(rotate) -#endif - -float repeat(float t, float length) { - return t - floor(t / length) * length; -} - -vec4 rotateQuat(vec4 p, vec4 q) { - vec3 iv = cross(q.xyz, p.xyz) + q.w * p.xyz; - vec3 res = p.xyz + 2.0 * cross(q.xyz, iv); - return vec4(res.xyz, p.w); -} - -float random(float seed) { - seed = mod(seed, 233280.); - float q = (seed * 9301. + 49297.) / 233280.; - return fract(q); -} - -float calcCurveValue(vec4 coef, float t) { - return t * (t * (t * coef.x + coef.y) + coef.z) + coef.w; -} - -float evaluateCurve(float keyTime[MAX_KEY_NUM], vec4 keyCoef[MAX_KEY_NUM], float normalizedTime) { - for (int i = 0; i < MAX_KEY_NUM; i++) { - if (keyTime[i] > normalizedTime) { - return calcCurveValue(keyCoef[i], normalizedTime - (i == 0 ? 0. : keyTime[i - 1])); - } - } -} - -float evaluateIntegral(float keyTime[MAX_KEY_NUM], vec4 keyCoef[MAX_KEY_NUM], float integral[MAX_KEY_NUM - 1], float normalizedTime, float ts) { - for (int i = 0; i < MAX_KEY_NUM; i++) { - if (keyTime[i] > normalizedTime) { - float t = normalizedTime - (i == 0 ? 0. : keyTime[i - 1]); - return ts * ((i - 1 < 0 ? 0. : integral[i - 1]) + t * calcCurveValue(keyCoef[i], t)); - } - } -} - -float evaluateIntegralTwice(float keyTime[MAX_KEY_NUM], vec4 keyCoef[MAX_KEY_NUM], float integral[MAX_KEY_NUM - 1], float normalizedTime, float ts) { - for (int i = 0; i < MAX_KEY_NUM; i++) { - if (keyTime[i] > normalizedTime) { - float t = normalizedTime - (i == 0 ? 0. : keyTime[i - 1]); - return ts * ts * ((i - 1 < 0 ? 0. : integral[i - 1]) + t * t * calcCurveValue(keyCoef[i], t)); - } - } -} - -float evaluateCurveRange(int mode, float minConstant, float maxConstant - , float minKeyTime[MAX_KEY_NUM], vec4 minKeyCoef[MAX_KEY_NUM] - , float maxKeyTime[MAX_KEY_NUM], vec4 maxKeyCoef[MAX_KEY_NUM] - , float t, float rnd) { - if (mode == CURVE_MODE_CONSTANT) { - return minConstant; - } else if (mode == CURVE_MODE_RANDOM_CONSTANT) { - return mix(minConstant, maxConstant, random(rnd)); - } else if (mode == CURVE_MODE_CURVE) { - return evaluateCurve(minKeyTime, minKeyCoef, t); - } else if (mode == CURVE_MODE_RANDOM_CURVE) { - return mix(evaluateCurve(minKeyTime, minKeyCoef, t), evaluateCurve(maxKeyTime, maxKeyCoef, t), random(rnd)); - } -} - -float evaluateCurveRangeIntegral(int mode, float minConstant, float maxConstant - , float minKeyTime[MAX_KEY_NUM], vec4 minKeyCoef[MAX_KEY_NUM], float minIntegral[MAX_KEY_NUM - 1] - , float maxKeyTime[MAX_KEY_NUM], vec4 maxKeyCoef[MAX_KEY_NUM], float maxIntegral[MAX_KEY_NUM - 1] - , float t, float ts, float rnd) { - if (mode == CURVE_MODE_CONSTANT) { - return minConstant * t * ts; - } else if (mode == CURVE_MODE_RANDOM_CONSTANT) { - return mix(minConstant, maxConstant, random(rnd)) * t * ts; - } else if (mode == CURVE_MODE_CURVE) { - return evaluateIntegral(minKeyTime, minKeyCoef, minIntegral, t, ts); - } else if (mode == CURVE_MODE_RANDOM_CURVE) { - return mix(evaluateIntegral(minKeyTime, minKeyCoef, minIntegral, t, ts), evaluateIntegral(maxKeyTime, maxKeyCoef, maxIntegral, t, ts), random(rnd)); - } -} - -float evaluateCurveRangeIntegralTwice(int mode, float minConstant, float maxConstant - , float minKeyTime[MAX_KEY_NUM], vec4 minKeyCoef[MAX_KEY_NUM], float minIntegral[MAX_KEY_NUM - 1] - , float maxKeyTime[MAX_KEY_NUM], vec4 maxKeyCoef[MAX_KEY_NUM], float maxIntegral[MAX_KEY_NUM - 1] - , float t, float ts, float rnd) { - if (mode == CURVE_MODE_CONSTANT) { - return minConstant * t * t * ts * ts / 2.; - } else if (mode == CURVE_MODE_RANDOM_CONSTANT) { - return mix(minConstant, maxConstant, random(rnd)) * t * t * ts * ts / 2.; - } else if (mode == CURVE_MODE_CURVE) { - return evaluateIntegralTwice(minKeyTime, minKeyCoef, minIntegral, t, ts); - } else if (mode == CURVE_MODE_RANDOM_CURVE) { - return mix(evaluateIntegralTwice(minKeyTime, minKeyCoef, minIntegral, t, ts), evaluateIntegralTwice(maxKeyTime, maxKeyCoef, maxIntegral, t, ts), random(rnd)); - } -} - -vec4 evaluateGradient(int mode, float colorKeyTime[MAX_KEY_NUM], vec3 colorKeyValue[MAX_KEY_NUM] - , float alphaKeyTime[MAX_KEY_NUM], float alphaKeyValue[MAX_KEY_NUM] - , float t){ - vec4 ret; - for (int i = 0; i < MAX_KEY_NUM; i++) { - if (t < colorKeyTime[i]) { - if (mode == GRADIENT_MODE_FIX) { - ret.xyz = colorKeyValue[i]; - } else if (mode == GRADIENT_MODE_BLEND) { - ret.xyz = mix(colorKeyValue[i - 1], colorKeyValue[i], (t - colorKeyTime[i - 1]) / (colorKeyTime[i] - colorKeyTime[i - 1])); - } - break; - } - } - for (int i = 0; i < MAX_KEY_NUM; i++) { - if (t < alphaKeyTime[i]) { - if (mode == GRADIENT_MODE_FIX) { - ret.w = alphaKeyValue[i]; - } else if (mode == GRADIENT_MODE_BLEND) { - ret.w = mix(alphaKeyValue[i - 1], alphaKeyValue[i], (t - alphaKeyTime[i - 1]) / (alphaKeyTime[i] - alphaKeyTime[i - 1])); - } - break; - } - } - return ret; -} - -vec4 evaluateGradientRange(int rangeMode, vec4 minColor, vec4 maxColor, - int minGradMode, vec3 minColorKeyValue[MAX_KEY_NUM], float minColorKeyTime[MAX_KEY_NUM], float minAlphaKeyValue[MAX_KEY_NUM], float minAlphaKeyTime[MAX_KEY_NUM], - int maxGradMode, vec3 maxColorKeyValue[MAX_KEY_NUM], float maxColorKeyTime[MAX_KEY_NUM], float maxAlphaKeyValue[MAX_KEY_NUM], float maxAlphaKeyTime[MAX_KEY_NUM], - float t, float rnd){ - if (rangeMode == GRADIENT_RANGE_MODE_COLOR) { - return minColor; - } else if (rangeMode == GRADIENT_RANGE_MODE_TWO_COLOR) { - return mix(minColor, maxColor, rnd); - } else if (rangeMode == GRADIENT_RANGE_MODE_GRADIENT) { - return evaluateGradient(minGradMode, minColorKeyTime, minColorKeyValue, minAlphaKeyTime, minAlphaKeyValue, t); - } else if (rangeMode == GRADIENT_RANGE_MODE_TWO_GRADIENT) { - return mix(evaluateGradient(minGradMode, minColorKeyTime, minColorKeyValue, minAlphaKeyTime, minAlphaKeyValue, t), - evaluateGradient(maxGradMode, maxColorKeyTime, maxColorKeyValue, maxAlphaKeyTime, maxAlphaKeyValue, t), rnd); - } -} - -void gpvs_main() { - vec4 pos = vec4(a_position_starttime.xyz, 1.); - float activeTime = u_psTime - a_position_starttime.w; - float normalizedTime = activeTime / a_dir_life.w; -#if VELOCITY_OVERTIME_MODULE_ENABLE - float speedModifier = u_speedModifier; -#else - float speedModifier = 1.; -#endif - pos.xyz += a_dir_life.xyz * activeTime * speedModifier; - -#if USE_STRETCHED_BILLBOARD - vec4 velocity = vec4(a_dir_life.xyz, 0.); - velocity *= speedModifier; -#endif -#if !USE_WORLD_SPACE - pos = model * pos; - #if USE_STRETCHED_BILLBOARD - velocity = rotateQuat(velocity, u_worldRot); - #endif -#endif -#if VELOCITY_OVERTIME_MODULE_ENABLE - vec4 velocityTrack = vec4(EVAL_CURVE_INTEGRAL(velocity_pos_x, normalizedTime, a_dir_life.w, a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET), EVAL_CURVE_INTEGRAL(velocity_pos_y, normalizedTime, a_dir_life.w, a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET), EVAL_CURVE_INTEGRAL(velocity_pos_z, normalizedTime, a_dir_life.w, a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET), 0); - velocityTrack = velocityTrack * speedModifier; - if (u_velocity_space == SIMULATE_SPACE_LOCAL) { - velocityTrack = rotateQuat(velocityTrack, u_worldRot); - } - pos += velocityTrack; - #if USE_STRETCHED_BILLBOARD - vec4 velocityVel = vec4(EVAL_CURVE_RANGE(velocity_x, normalizedTime, a_dir_life.w, a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET), EVAL_CURVE_RANGE(velocity_y, normalizedTime, a_dir_life.w, a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET), EVAL_CURVE_RANGE(velocity_z, normalizedTime, a_dir_life.w, a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET), 0); - if (u_velocity_space == SIMULATE_SPACE_LOCAL) { - velocityVel = rotateQuat(velocityVel, u_worldRot); - } - velocityVel *= speedModifier; - velocity += velocityVel; - #endif -#endif - -#if FORCE_OVERTIME_MODULE_ENABLE - vec4 forceTrack = vec4(EVAL_CURVE_INTEGRAL_TWICE(force_pos_x, normalizedTime, a_dir_life.w, a_rndSeed + FORCE_OVERTIME_RAND_OFFSET), EVAL_CURVE_INTEGRAL_TWICE(force_pos_y, normalizedTime, a_dir_life.w, a_rndSeed + FORCE_OVERTIME_RAND_OFFSET), EVAL_CURVE_INTEGRAL_TWICE(force_pos_z, normalizedTime, a_dir_life.w, a_rndSeed + FORCE_OVERTIME_RAND_OFFSET), 0); - forceTrack = forceTrack * speedModifier; - if (u_force_space == SIMULATE_SPACE_LOCAL) { - forceTrack = rotateQuat(forceTrack, u_worldRot); - } - pos += forceTrack; - #if USE_STRETCHED_BILLBOARD - vec4 forceVel = vec4(EVAL_CURVE_INTEGRAL(force_vel_x, normalizedTime, a_dir_life.w, a_rndSeed + FORCE_OVERTIME_RAND_OFFSET), EVAL_CURVE_INTEGRAL(force_vel_y, normalizedTime, a_dir_life.w, a_rndSeed + FORCE_OVERTIME_RAND_OFFSET), EVAL_CURVE_INTEGRAL(force_vel_z, normalizedTime, a_dir_life.w, a_rndSeed + FORCE_OVERTIME_RAND_OFFSET), 0); - if (u_force_space == SIMULATE_SPACE_LOCAL) { - forceVel = rotateQuat(forceVel, u_worldRot); - } - forceVel *= speedModifier; - velocity += forceVel; - #endif -#endif - - float size = a_vertIdx_size_angle.z; -#if SIZE_OVERTIME_MODULE_ENABLE - float sizeModifier = EVAL_CURVE_RANGE(size, normalizedTime, a_rndSeed + SIZE_OVERTIME_RAND_OFFSET); - size *= sizeModifier; -#endif - - vec2 cornerOffset = vec2((a_vertIdx_size_angle.xy - 0.5) * size); -#if !USE_STRETCHED_BILLBOARD - float angle = a_vertIdx_size_angle.w; - #if ROTATE_OVERTIME_MODULE_ENABLE - angle += EVAL_CURVE_INTEGRAL(rotate, normalizedTime, a_dir_life.w, a_rndSeed + ROTATION_OVERTIME_RAND_OFFSET); - #endif - rotateCorner(cornerOffset, angle); -#endif - - computeVertPos(pos, cornerOffset - #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD - , view - #endif - #if USE_STRETCHED_BILLBOARD - , eye - , velocity - , velocityScale - , lengthScale - , size - , a_vertIdx_size_angle.x - #endif - ); - - pos = viewProj * pos; - - float frameIndex = 0.; -#if TEXTURE_ANIMATION_ENABLE - if (u_animation_mode == ANIMATION_MODE_WHOLE_SHEET) { - frameIndex = repeat(u_cycles * EVAL_CURVE_RANGE(frameOverTime, normalizedTime, a_rndSeed + TEXTURE_ANIMATION_RAND_OFFSET), 1.); - } else if (u_animation_mode == ANIMATION_MODE_SINGLE_ROW) { - float rowLength = 1. / frameTile.y; - if (u_random_row) { - float f = repeat(u_cycles * EVAL_CURVE_RANGE(frameOverTime, normalizedTime, a_rndSeed + TEXTURE_ANIMATION_RAND_OFFSET), 1.); - float startRow = floor(random(floor(u_psTime * 1000.)) * frameTile.y); - float from = startRow * rowLength; - float to = from + rowLength; - frameIndex = mix(from, to, f); - } - else { - float from = float(u_row_index) * rowLength; - float to = from + rowLength; - frameIndex = mix(from, to, repeat(u_cycles * EVAL_CURVE_RANGE(frameOverTime, normalizedTime, a_rndSeed + TEXTURE_ANIMATION_RAND_OFFSET), 1.)); - } - } -#endif - uv = computeUV(frameIndex, a_vertIdx_size_angle.xy, frameTile) * mainTiling + mainOffset; - -#if COLOR_OVERTIME_MODULE_ENABLE - color = a_color * EVAL_GRADIENT_RANGE(color, normalizedTime, a_rndSeed + COLOR_OVERTIME_RAND_OFFSET); -#else - color = a_color; -#endif - - gl_Position = pos; -} \ No newline at end of file diff --git a/cocos/renderer/bin/chunks/particle-vs-legacy.inc b/cocos/renderer/bin/chunks/particle-vs-legacy.inc deleted file mode 100644 index 47042a9ac6..0000000000 --- a/cocos/renderer/bin/chunks/particle-vs-legacy.inc +++ /dev/null @@ -1,55 +0,0 @@ -#include -attribute vec3 a_position; // center position -attribute vec3 a_uv; // xy:vertex index,z:frame index -attribute vec2 a_uv0; // size, angle -attribute vec4 a_color; -#if USE_STRETCHED_BILLBOARD -attribute vec3 a_color0; // velocity.x, velocity.y, velocity.z, scale -#endif - - -void lpvs_main() { - vec4 pos = vec4(a_position, 1); -#if USE_STRETCHED_BILLBOARD - vec4 velocity = vec4(a_color0.xyz, 0); -#endif - -#if !USE_WORLD_SPACE -// // simulate in world space. apply model matrix on CPU side. -// #else - pos = model * pos; - #if USE_STRETCHED_BILLBOARD - velocity = model * velocity; - #endif -#endif - - vec2 cornerOffset = vec2((a_uv.xy - 0.5) * a_uv0.x); -#if !USE_STRETCHED_BILLBOARD -// // rotation will not be applied in stretchedBillboard mode(Unity). -// #else - // rotation - rotateCorner(cornerOffset, a_uv0.y); -#endif - - computeVertPos(pos, cornerOffset - #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD - , view - #endif - #if USE_STRETCHED_BILLBOARD - , eye - , velocity - , velocityScale - , lengthScale - , a_uv0.x - , a_uv.x - #endif - ); - - pos = viewProj * pos; - - uv = computeUV(a_uv.z, a_uv.xy, frameTile) * mainTiling + mainOffset; - - color = a_color; - - gl_Position = pos; -} diff --git a/cocos/renderer/bin/chunks/pbr-fs.inc b/cocos/renderer/bin/chunks/pbr-fs.inc deleted file mode 100644 index 5a0690ac75..0000000000 --- a/cocos/renderer/bin/chunks/pbr-fs.inc +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -#if USE_NORMAL_TEXTURE -#extension GL_OES_standard_derivatives : enable -#endif - -#if USE_TEX_LOD -#extension GL_EXT_shader_texture_lod: enable -#endif - -#include -#include - -struct LightInfo { - vec3 lightDir; - vec3 radiance; -}; - -#if NUM_DIR_LIGHTS > 0 - #pragma for id in range(0, NUM_DIR_LIGHTS) - uniform vec3 dir_light{id}_direction; - uniform vec3 dir_light{id}_color; - #pragma endFor -#endif - -#if NUM_POINT_LIGHTS > 0 - #pragma for id in range(0, NUM_POINT_LIGHTS) - uniform vec3 point_light{id}_position; - uniform vec3 point_light{id}_color; - uniform float point_light{id}_range; - #pragma endFor -#endif - -#if NUM_SPOT_LIGHTS > 0 - #pragma for id in range(0, NUM_SPOT_LIGHTS) - uniform vec3 spot_light{id}_position; - uniform vec3 spot_light{id}_direction; - uniform vec3 spot_light{id}_color; - uniform vec2 spot_light{id}_spot; - uniform float spot_light{id}_range; - #pragma endFor -#endif - -// directional light -LightInfo computeDirectionalLighting( - vec3 lightDirection, - vec3 lightColor -) { - LightInfo ret; - ret.lightDir = -normalize(lightDirection); - ret.radiance = lightColor; - - return ret; -} - -// point light -LightInfo computePointLighting( - vec3 lightPosition, - vec3 positionW, - vec3 lightColor, - float lightRange -) { - LightInfo ret; - vec3 lightDir = lightPosition - positionW; - float attenuation = max(0.0, 1.0 - length(lightDir) / lightRange); - ret.lightDir = normalize(lightDir); - ret.radiance = lightColor * attenuation; - - return ret; -} - -// spot light -LightInfo computeSpotLighting( - vec3 lightPosition, - vec3 positionW, - vec3 lightDirection, - vec3 lightColor, - vec2 lightSpot, - float lightRange -) { - LightInfo ret; - vec3 lightDir = lightPosition - positionW; - float attenuation = max(0., 1.0 - length(lightDir) / lightRange); - float cosConeAngle = max(0., dot(lightDirection, -lightDir)); - cosConeAngle = cosConeAngle < lightSpot.x ? 0.0 : cosConeAngle; - cosConeAngle = pow(cosConeAngle,lightSpot.y); - ret.lightDir = normalize(lightDir); - ret.radiance = lightColor * attenuation * cosConeAngle; - - return ret; -} - -#include - -#if USE_SHADOW_MAP - #include - #include -#endif - -uniform vec3 eye; - -varying vec3 pos_w; -varying vec3 normal_w; - -#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_EMISSIVE_TEXTURE - varying vec2 uv0; -#endif - -#if USE_IBL - uniform samplerCube diffuseEnvTexture; - uniform samplerCube specularEnvTexture; - uniform sampler2D brdfLUT; - #if USE_TEX_LOD - uniform float maxReflectionLod; - #endif -#endif - -// material parameters -uniform vec4 albedo; -#if USE_ALBEDO_TEXTURE - uniform sampler2D albedo_texture; -#endif - -#if USE_MRA_TEXTURE - uniform sampler2D mra_texture; -#endif - -uniform float metallic; -#if USE_METALLIC_TEXTURE - uniform sampler2D metallic_texture; -#endif - -uniform float roughness; -#if USE_ROUGHNESS_TEXTURE - uniform sampler2D roughness_texture; -#endif - -uniform float ao; -#if USE_AO_TEXTURE - uniform sampler2D ao_texture; -#endif - -#if USE_EMISSIVE - uniform vec3 emissive; - #if USE_EMISSIVE_TEXTURE - uniform sampler2D emissive_texture; - #endif -#endif - -#if USE_ALPHA_TEST - uniform float alphaTestThreshold; -#endif - -#if USE_NORMAL_TEXTURE - uniform sampler2D normal_texture; - // get world-space normal from normal texture - vec3 getNormalFromTexture() { - vec3 tangentNormal = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0; - vec3 q1 = dFdx(pos_w); - vec3 q2 = dFdy(pos_w); - vec2 st1 = dFdx(uv0); - vec2 st2 = dFdy(uv0); - vec3 N = normalize(normal_w); - vec3 T = normalize(q1*st2.t - q2*st1.t); - vec3 B = -normalize(cross(N, T)); - mat3 TBN = mat3(T, B, N); - - return normalize(TBN * tangentNormal); - } -#endif - -// Cook-Torrance BRDF model -// D() Normal distribution function (Trowbridge-Reitz GGX) -// https://disney-animation.s3.amazonaws.com/library/s2012_pbs_disney_brdf_notes_v2.pdf -float distributionGGX(vec3 N, vec3 H, float roughness) { - float a = roughness * roughness; - float a2 = a * a; - float NdotH = max(dot(N, H), 0.0); - float NdotH2 = NdotH * NdotH; - float nom = a2; - float denom = (NdotH2 * (a2 - 1.0) + 1.0); - denom = PI * denom * denom; - - return nom / denom; -} -// G() Geometry function (Smith's Schlick GGX) -// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf -float geometrySchlickGGX(float NdotV, float roughness) { - float r = (roughness + 1.0); - float k = (r * r) / 8.0; - float nom = NdotV; - float denom = NdotV * (1.0 - k) + k; - - return nom / denom; -} -float geometrySmith(vec3 N, vec3 V, vec3 L, float roughness) { - float NdotV = max(dot(N, V), 0.0); - float NdotL = max(dot(N, L), 0.0); - float ggx2 = geometrySchlickGGX(NdotV, roughness); - float ggx1 = geometrySchlickGGX(NdotL, roughness); - - return ggx1 * ggx2; -} -// F() Fresnel equation (Fresnel-Schlick approximation) -// Optimized variant (presented by Epic at SIGGRAPH '13) -// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf -vec3 fresnelSchlick(float cosTheta, vec3 F0) { - float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta); - return F0 + (1.0 - F0) * fresnel; -} -vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) { - float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta); - return F0 + (max(vec3(1.0 - roughness), F0) - F0) * fresnel; -} - -// BRDF equation -vec3 brdf(LightInfo lightInfo, vec3 N, vec3 V, vec3 F0, vec3 albedo, float metallic, float roughness) { - vec3 H = normalize(V + lightInfo.lightDir); - float NDF = distributionGGX(N, H, roughness); - float G = geometrySmith(N, V, lightInfo.lightDir, roughness); - vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0); - vec3 nominator = NDF * G * F; - float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, lightInfo.lightDir), 0.0) + 0.001; // 0.001 to prevent divide by zero. - vec3 specular = nominator / denominator; - // kS is equal to Fresnel - vec3 kS = F; - // for energy conservation, the diffuse and specular light can't - // be above 1.0 (unless the surface emits light); to preserve this - // relationship the diffuse component (kD) should equal 1.0 - kS. - vec3 kD = vec3(1.0) - kS; - // multiply kD by the inverse metalness such that only non-metals - // have diffuse lighting, or a linear blend if partly metal (pure metals - // have no diffuse light). - kD *= 1.0 - metallic; - float NdotL = max(dot(N, lightInfo.lightDir), 0.0); - - return (kD * albedo / PI + specular) * lightInfo.radiance * NdotL; -} - -vec4 frag() { - float opacity = 1.0; - - #if USE_ALBEDO_TEXTURE - vec4 baseColor = albedo * gammaToLinearSpaceRGBA(texture2D(albedo_texture, uv0)); - vec3 albedo = baseColor.rgb; - opacity = baseColor.a; - #else - opacity = albedo.a; - vec3 albedo = albedo.rgb; - #endif - - #if USE_ALPHA_TEST - if(opacity < alphaTestThreshold) discard; - #endif - - #if USE_MRA_TEXTURE - vec3 metalRoughness = texture2D(mra_texture, uv0).rgb; - float metallic = metalRoughness.r; - float roughness = metalRoughness.g; - float ao = metalRoughness.b; - #else - #if USE_METALLIC_TEXTURE - float metallic = texture2D(metallic_texture, uv0).r; - #endif - #if USE_ROUGHNESS_TEXTURE - float roughness = texture2D(roughness_texture, uv0).r; - #endif - #if USE_AO_TEXTURE - float ao = texture2D(ao_texture, uv0).r; - #endif - #endif - - vec3 N = normalize(normal_w); - #if USE_NORMAL_TEXTURE - N = getNormalFromTexture(); - #endif - vec3 V = normalize(eye - pos_w); - - // calculate reflectance at normal incidence; if dia-electric (like plastic) use F0 - // of 0.04 and if it's a metal, use the albedo color as F0 (metallic workflow) - vec3 F0 = vec3(0.04); - F0 = mix(F0, albedo, metallic); - - // reflection - vec3 Lo = vec3(0.0); - - // point light (a 'for' loop to accumulate all light sources) - #if NUM_POINT_LIGHTS > 0 - #pragma for id in range(0, NUM_POINT_LIGHTS) - LightInfo pointLight{id}; - pointLight{id} = computePointLighting(point_light{id}_position, pos_w, point_light{id}_color, point_light{id}_range); - Lo += brdf(pointLight{id}, N, V, F0, albedo, metallic, roughness); - #pragma endFor - #endif - - #if NUM_DIR_LIGHTS > 0 - #pragma for id in range(0, NUM_DIR_LIGHTS) - LightInfo directionalLight{id}; - directionalLight{id} = computeDirectionalLighting(dir_light{id}_direction, dir_light{id}_color); - Lo += brdf(directionalLight{id}, N, V, F0, albedo, metallic, roughness); - #pragma endFor - #endif - - #if NUM_SPOT_LIGHTS > 0 - #pragma for id in range(0, NUM_SPOT_LIGHTS) - LightInfo spotLight{id}; - spotLight{id} = computeSpotLighting(spot_light{id}_position, pos_w, spot_light{id}_direction, spot_light{id}_color, spot_light{id}_spot, spot_light{id}_range); - Lo += brdf(spotLight{id}, N, V, F0, albedo, metallic, roughness); - #pragma endFor - #endif - - #if USE_EMISSIVE - vec3 emissiveColor = emissive; - #if USE_EMISSIVE_TEXTURE - emissiveColor *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb); - #endif - Lo += emissiveColor; - #endif - - // ambient lighting, will be replaced by IBL if IBL used. - vec3 ambient = vec3(0.03) * albedo * ao; - - #if USE_IBL - // generate ambient when using IBL. - vec3 F = fresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness); - vec3 kS = F; - vec3 kD = vec3(1.0) - kS; - kD *= 1.0 - metallic; - #if USE_RGBE_IBL_DIFFUSE - vec3 diffuseEnv = unpackRGBE(textureCube(diffuseEnvTexture, N)); - #else - vec3 diffuseEnv = textureCube(diffuseEnvTexture, N).rgb; - #endif - vec3 diffuse = diffuseEnv * albedo; - // sample both the specularEnvTexture and the BRDF lut and combine them together as per the Split-Sum approximation to get the IBL specular part. - vec3 R = reflect(-V, N); - #if USE_TEX_LOD - #if USE_RGBE_IBL_SPECULAR - vec3 specularEnv = unpackRGBE(textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod)); - #else - vec3 specularEnv = textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod).rgb; - #endif - #else - #if USE_RGBE_IBL_SPECULAR - vec3 specularEnv = unpackRGBE(textureCube(specularEnvTexture, R)); - #else - vec3 specularEnv = textureCube(specularEnvTexture, R).rgb; - #endif - #endif - vec2 brdf = texture2D(brdfLUT, vec2(max(dot(N, V), 0.0), 1.0 - roughness)).rg; - vec3 specular = specularEnv * (F * brdf.x + brdf.y); - ambient = (kD * diffuse + specular) * ao; - #endif - - #if USE_SHADOW_MAP - float shadow = 1.0; - #if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - shadow *= computeShadowESM(shadowMap_{id}, pos_lightspace_{id}, vDepth_{id}, depthScale_{id}, darkness_{id}, frustumEdgeFalloff_{id}); - #pragma endFor - #endif - vec3 color = (ambient + Lo) * shadow; - #else - vec3 color = ambient + Lo; - #endif - - // HDR tone mapping. - color = color / (color + vec3(1.0)); - // gamma correction. - vec4 finalColor = vec4(color, opacity); - - return linearToGammaSpaceRGBA(finalColor); -} diff --git a/cocos/renderer/bin/chunks/pbr-vs.inc b/cocos/renderer/bin/chunks/pbr-vs.inc deleted file mode 100644 index 15d3fb238a..0000000000 --- a/cocos/renderer/bin/chunks/pbr-vs.inc +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -attribute vec3 a_position; -attribute vec3 a_normal; - -varying vec3 pos_w; -varying vec3 normal_w; - -uniform mat4 model; -uniform mat4 viewProj; -uniform mat3 normalMatrix; - -#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 - attribute vec2 a_uv0; - uniform vec2 mainTiling; - uniform vec2 mainOffset; - varying vec2 uv0; -#endif - -#if USE_SKINNING - #include -#endif - -#if USE_SHADOW_MAP - #if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - uniform mat4 lightViewProjMatrix_{id}; - uniform float minDepth_{id}; - uniform float maxDepth_{id}; - varying vec4 pos_lightspace_{id}; - varying float vDepth_{id}; - #pragma endFor - #endif -#endif - -vec4 vert () { - vec4 pos = vec4(a_position, 1); - - #if USE_SKINNING - mat4 skinMat = skinMatrix(); - pos = skinMat * pos; - #endif - - pos_w = (model * pos).xyz; - pos = viewProj * model * pos; - - #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 - uv0 = a_uv0 * mainTiling + mainOffset; - #endif - - vec4 normal = vec4(a_normal, 0); - #if USE_SKINNING - normal = skinMat * normal; - #endif - normal_w = normalMatrix * normal.xyz; - - #if USE_SHADOW_MAP - #if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - pos_lightspace_{id} = lightViewProjMatrix_{id} * vec4(pos_w, 1.0); - vDepth_{id} = (pos_lightspace_{id}.z + minDepth_{id}) / (minDepth_{id} + maxDepth_{id}); - #pragma endFor - #endif - #endif - - return pos; -} diff --git a/cocos/renderer/bin/chunks/phong-fs.inc b/cocos/renderer/bin/chunks/phong-fs.inc deleted file mode 100644 index c0753d6248..0000000000 --- a/cocos/renderer/bin/chunks/phong-fs.inc +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -#if USE_NORMAL_TEXTURE -#extension GL_OES_standard_derivatives : enable -#endif - -#include -#include - -struct LightInfo { - vec3 diffuse; - vec3 specular; -}; - -LightInfo computeDirectionalLighting( - vec3 lightDirection, - vec3 lightColor, - vec3 normal, - vec3 viewDirection, - float glossiness -) { - LightInfo lightingResult; - float ndl = 0.0; - float ndh = 0.0; - vec3 lightDir = -normalize(lightDirection); - ndl = max(0.0, dot(normal, lightDir)); - lightingResult.diffuse = lightColor * ndl; - - vec3 dirH = normalize(viewDirection + lightDir); - ndh = max(0.0, dot(normal, dirH)); - ndh = (ndl == 0.0) ? 0.0: ndh; - ndh = pow(ndh, max(1.0, glossiness * 128.0)); - lightingResult.specular = lightColor * ndh; - - return lightingResult; -} - -LightInfo computePointLighting( - vec3 lightPosition, - vec3 lightColor, - float lightRange, - vec3 normal, - vec3 positionW, - vec3 viewDirection, - float glossiness -) { - LightInfo lightingResult; - float ndl = 0.0; - float ndh = 0.0; - vec3 lightDir = vec3(0, 0, 0); - float attenuation = 1.0; - lightDir = lightPosition - positionW; - attenuation = max(0., 1.0 - length(lightDir) / lightRange); - lightDir = normalize(lightDir); - ndl = max(0.0, dot(normal, lightDir)); - lightingResult.diffuse = lightColor * ndl * attenuation; - - vec3 dirH = normalize(viewDirection + lightDir); - ndh = max(0.0, dot(normal, dirH)); - ndh = (ndl == 0.0) ? 0.0: ndh; - ndh = pow(ndh, max(1.0, glossiness * 128.0)); - lightingResult.specular = lightColor * ndh * attenuation; - - return lightingResult; -} - -LightInfo computeSpotLighting( - vec3 lightPosition, - vec3 lightDirection, - vec3 lightColor, - float lightRange, - vec2 lightSpot, - vec3 normal, - vec3 positionW, - vec3 viewDirection, - float glossiness -) { - LightInfo lightingResult; - float ndl = 0.0; - float ndh = 0.0; - vec3 lightDir = vec3(0, 0, 0); - float attenuation = 1.0; - float cosConeAngle = 1.0; - - lightDir = lightPosition - positionW; - attenuation = max(0., 1.0 - length(lightDir) / lightRange); - lightDir = normalize(lightDir); - cosConeAngle = max(0., dot(lightDirection, -lightDir)); - cosConeAngle = cosConeAngle < lightSpot.x ? 0.0 : cosConeAngle; - cosConeAngle = pow(cosConeAngle,lightSpot.y); - ndl = max(0.0, dot(normal, lightDir)); - lightingResult.diffuse = lightColor * ndl * attenuation * cosConeAngle; - - vec3 dirH = normalize(viewDirection + lightDir); - ndh = max(0.0, dot(normal, dirH)); - ndh = (ndl == 0.0) ? 0.0: ndh; - ndh = pow(ndh, max(1.0, glossiness * 128.0)); - lightingResult.specular = lightColor * ndh * attenuation * cosConeAngle; - - return lightingResult; -} - -#if NUM_DIR_LIGHTS > 0 - #pragma for id in range(0, NUM_DIR_LIGHTS) - uniform vec3 dir_light{id}_direction; - uniform vec3 dir_light{id}_color; - #pragma endFor -#endif - -#if NUM_POINT_LIGHTS > 0 - #pragma for id in range(0, NUM_POINT_LIGHTS) - uniform vec3 point_light{id}_position; - uniform vec3 point_light{id}_color; - uniform float point_light{id}_range; - #pragma endFor -#endif - -#if NUM_SPOT_LIGHTS > 0 - #pragma for id in range(0, NUM_SPOT_LIGHTS) - uniform vec3 spot_light{id}_position; - uniform vec3 spot_light{id}_direction; - uniform vec3 spot_light{id}_color; - uniform float spot_light{id}_range; - uniform vec2 spot_light{id}_spot; - #pragma endFor -#endif - -LightInfo getPhongLighting( - vec3 normal, - vec3 positionW, - vec3 viewDirection, - float glossiness -) { - LightInfo result; - result.diffuse = vec3(0, 0, 0); - result.specular = vec3(0, 0, 0); - LightInfo dirLighting; - #if NUM_DIR_LIGHTS > 0 - #pragma for id in range(0, NUM_DIR_LIGHTS) - dirLighting = computeDirectionalLighting(dir_light{id}_direction,dir_light{id}_color,normal, viewDirection, glossiness); - result.diffuse += dirLighting.diffuse; - result.specular += dirLighting.specular; - #pragma endFor - #endif - - LightInfo pointLighting; - #if NUM_POINT_LIGHTS > 0 - #pragma for id in range(0, NUM_POINT_LIGHTS) - pointLighting = computePointLighting(point_light{id}_position, point_light{id}_color, point_light{id}_range, - normal, positionW, viewDirection, glossiness); - result.diffuse += pointLighting.diffuse; - result.specular += pointLighting.specular; - #pragma endFor - #endif - - LightInfo spotLighting; - #if NUM_SPOT_LIGHTS > 0 - #pragma for id in range(0, NUM_SPOT_LIGHTS) - spotLighting = computeSpotLighting(spot_light{id}_position, spot_light{id}_direction, spot_light{id}_color, - spot_light{id}_range, spot_light{id}_spot,normal, positionW, viewDirection, glossiness); - result.diffuse += spotLighting.diffuse; - result.specular += spotLighting.specular; - #pragma endFor - #endif - return result; -} - -#if USE_SHADOW_MAP - #include - #include -#endif - -uniform vec3 eye; -uniform vec3 sceneAmbient; - -varying vec3 normal_w; -varying vec3 pos_w; - -#if USE_NORMAL_TEXTURE || USE_DIFFUSE_TEXTURE || USE_EMISSIVE_TEXTURE - varying vec2 uv0; -#endif - -struct phongMaterial -{ - vec3 diffuse; - vec3 emissive; - vec3 specular; - float glossiness; - float opacity; -}; - -uniform vec4 diffuseColor; -#if USE_DIFFUSE_TEXTURE - uniform sampler2D diffuse_texture; -#endif - -#if USE_EMISSIVE - uniform vec3 emissiveColor; - #if USE_EMISSIVE_TEXTURE - uniform sampler2D emissive_texture; - #endif -#endif - -#if USE_SPECULAR - uniform vec3 specularColor; - uniform float glossiness; - #if USE_SPECULAR_TEXTURE - uniform sampler2D specular_texture; - #endif -#endif - -#if USE_NORMAL_TEXTURE - uniform sampler2D normal_texture; - uniform float normalScale; //this is not used yet - vec3 getNormal(vec3 pos, vec3 normal) { - vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) ); - vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) ); - vec2 st0 = dFdx( uv0.st ); - vec2 st1 = dFdy( uv0.st ); - vec3 S = normalize( q0 * st1.t - q1 * st0.t ); - vec3 T = normalize( -q0 * st1.s + q1 * st0.s ); - vec3 N = normal; - vec3 mapN = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0; - mapN.xy = 1.0 * mapN.xy; - mat3 tsn = mat3( S, T, N ); - return normalize( tsn * mapN ); - } -#endif - -#if USE_ALPHA_TEST - uniform float alphaTestThreshold; -#endif - -phongMaterial getPhongMaterial() { - phongMaterial result; - - #if USE_DIFFUSE_TEXTURE - vec4 baseColor = diffuseColor * gammaToLinearSpaceRGBA(texture2D(diffuse_texture, uv0)); - result.diffuse = baseColor.rgb; - result.opacity = baseColor.a; - #else - result.diffuse = diffuseColor.rgb; - result.opacity = diffuseColor.a; - #endif - - #if USE_EMISSIVE - result.emissive = gammaToLinearSpaceRGB(emissiveColor); - #if USE_EMISSIVE_TEXTURE - result.emissive *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb); - #endif - #endif - - #if USE_SPECULAR - result.specular = gammaToLinearSpaceRGB(specularColor); - #if USE_SPECULAR_TEXTURE - result.specular = gammaToLinearSpaceRGB(texture2D(specular_texture, uv0).rgb); - #endif - - result.glossiness = glossiness; - #endif - - return result; -} - -vec4 composePhongShading(LightInfo lighting, phongMaterial mtl, float shadow) -{ - vec4 o = vec4(0.0, 0.0, 0.0, 1.0); - - //diffuse is always calculated - o.xyz = lighting.diffuse * mtl.diffuse; - #if USE_EMISSIVE - o.xyz += mtl.emissive; - #endif - #if USE_SPECULAR - o.xyz += lighting.specular * mtl.specular; - #endif - o.xyz *= shadow; - o.w = mtl.opacity; - - return o; -} - -vec4 frag () { - LightInfo phongLighting; - vec3 viewDirection = normalize(eye - pos_w); - - phongMaterial mtl = getPhongMaterial(); - #if USE_ALPHA_TEST - if(mtl.opacity < alphaTestThreshold) discard; - #endif - vec3 normal = normalize(normal_w); - #if USE_NORMAL_TEXTURE - normal = getNormal(pos_w, normal); - #endif - phongLighting = getPhongLighting(normal, pos_w, viewDirection, mtl.glossiness); - phongLighting.diffuse += sceneAmbient; - - #if USE_SHADOW_MAP - float shadow = 1.0; - #if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - shadow *= computeShadowESM(shadowMap_{id}, pos_lightspace_{id}, vDepth_{id}, depthScale_{id}, darkness_{id}, frustumEdgeFalloff_{id}); - #pragma endFor - #endif - vec4 finalColor = composePhongShading(phongLighting, mtl, shadow); - #else - vec4 finalColor = composePhongShading(phongLighting, mtl, 1.0); - #endif - - return linearToGammaSpaceRGBA(finalColor); -} diff --git a/cocos/renderer/bin/chunks/phong-vs.inc b/cocos/renderer/bin/chunks/phong-vs.inc deleted file mode 100644 index 0154730b74..0000000000 --- a/cocos/renderer/bin/chunks/phong-vs.inc +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -attribute vec3 a_position; -attribute vec3 a_normal; - -uniform mat4 model; -uniform mat4 viewProj; -uniform mat3 normalMatrix; - -varying vec3 normal_w; -varying vec3 pos_w; - -#if USE_NORMAL_TEXTURE || USE_DIFFUSE_TEXTURE || USE_EMISSIVE_TEXTURE - attribute vec2 a_uv0; - uniform vec2 mainTiling; - uniform vec2 mainOffset; - varying vec2 uv0; -#endif - -#if USE_SKINNING - #include -#endif - -#if USE_SHADOW_MAP - #if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - uniform mat4 lightViewProjMatrix_{id}; - uniform float minDepth_{id}; - uniform float maxDepth_{id}; - varying vec4 pos_lightspace_{id}; - varying float vDepth_{id}; - #pragma endFor - #endif -#endif - -vec4 vert () { - vec4 pos = vec4(a_position, 1); - - #if USE_SKINNING - mat4 skinMat = skinMatrix(); - pos = skinMat * pos; - #endif - - pos_w = (model * pos).xyz; - pos = viewProj * model * pos; - - #if USE_NORMAL_TEXTURE || USE_DIFFUSE_TEXTURE || USE_EMISSIVE_TEXTURE - uv0 = a_uv0 * mainTiling + mainOffset; - #endif - - vec4 normal = vec4(a_normal, 0); - #if USE_SKINNING - normal = skinMat * normal; - #endif - normal_w = normalMatrix * normal.xyz; - - #if USE_SHADOW_MAP - #if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - pos_lightspace_{id} = lightViewProjMatrix_{id} * vec4(pos_w, 1.0); - vDepth_{id} = (pos_lightspace_{id}.z + minDepth_{id}) / (minDepth_{id} + maxDepth_{id}); - #pragma endFor - #endif - #endif - - return pos; -} diff --git a/cocos/renderer/bin/chunks/rect-area-light.inc b/cocos/renderer/bin/chunks/rect-area-light.inc deleted file mode 100644 index 85a1d00f2c..0000000000 --- a/cocos/renderer/bin/chunks/rect-area-light.inc +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -mat3 transpose(mat3 v) { - mat3 tmp; - tmp[0] = vec3(v[0].x, v[1].x, v[2].x); - tmp[1] = vec3(v[0].y, v[1].y, v[2].y); - tmp[2] = vec3(v[0].z, v[1].z, v[2].z); - - return tmp; -} - -void ClipQuadToHorizon(inout vec3 L[5], out int n) { - // detect clipping config - int config = 0; - if (L[0].z > 0.0) config += 1; - if (L[1].z > 0.0) config += 2; - if (L[2].z > 0.0) config += 4; - if (L[3].z > 0.0) config += 8; - config = 15; - - // clip - n = 0; - - if (config == 0) - { - // clip all - } - else if (config == 1) // V1 clip V2 V3 V4 - { - n = 3; - L[1] = -L[1].z * L[0] + L[0].z * L[1]; - L[2] = -L[3].z * L[0] + L[0].z * L[3]; - } - else if (config == 2) // V2 clip V1 V3 V4 - { - n = 3; - L[0] = -L[0].z * L[1] + L[1].z * L[0]; - L[2] = -L[2].z * L[1] + L[1].z * L[2]; - } - else if (config == 3) // V1 V2 clip V3 V4 - { - n = 4; - L[2] = -L[2].z * L[1] + L[1].z * L[2]; - L[3] = -L[3].z * L[0] + L[0].z * L[3]; - } - else if (config == 4) // V3 clip V1 V2 V4 - { - n = 3; - L[0] = -L[3].z * L[2] + L[2].z * L[3]; - L[1] = -L[1].z * L[2] + L[2].z * L[1]; - } - else if (config == 5) // V1 V3 clip V2 V4) impossible - { - n = 0; - } - else if (config == 6) // V2 V3 clip V1 V4 - { - n = 4; - L[0] = -L[0].z * L[1] + L[1].z * L[0]; - L[3] = -L[3].z * L[2] + L[2].z * L[3]; - } - else if (config == 7) // V1 V2 V3 clip V4 - { - n = 5; - L[4] = -L[3].z * L[0] + L[0].z * L[3]; - L[3] = -L[3].z * L[2] + L[2].z * L[3]; - } - else if (config == 8) // V4 clip V1 V2 V3 - { - n = 3; - L[0] = -L[0].z * L[3] + L[3].z * L[0]; - L[1] = -L[2].z * L[3] + L[3].z * L[2]; - L[2] = L[3]; - } - else if (config == 9) // V1 V4 clip V2 V3 - { - n = 4; - L[1] = -L[1].z * L[0] + L[0].z * L[1]; - L[2] = -L[2].z * L[3] + L[3].z * L[2]; - } - else if (config == 10) // V2 V4 clip V1 V3) impossible - { - n = 0; - } - else if (config == 11) // V1 V2 V4 clip V3 - { - n = 5; - L[4] = L[3]; - L[3] = -L[2].z * L[3] + L[3].z * L[2]; - L[2] = -L[2].z * L[1] + L[1].z * L[2]; - } - else if (config == 12) // V3 V4 clip V1 V2 - { - n = 4; - L[1] = -L[1].z * L[2] + L[2].z * L[1]; - L[0] = -L[0].z * L[3] + L[3].z * L[0]; - } - else if (config == 13) // V1 V3 V4 clip V2 - { - n = 5; - L[4] = L[3]; - L[3] = L[2]; - L[2] = -L[1].z * L[2] + L[2].z * L[1]; - L[1] = -L[1].z * L[0] + L[0].z * L[1]; - } - else if (config == 14) // V2 V3 V4 clip V1 - { - n = 5; - L[4] = -L[0].z * L[3] + L[3].z * L[0]; - L[0] = -L[0].z * L[1] + L[1].z * L[0]; - } - else if (config == 15) // V1 V2 V3 V4 - { - n = 4; - } - - if (n == 3) - L[3] = L[0]; - if (n == 4) - L[4] = L[0]; -} - -// https://eheitzresearch.wordpress.com/415-2/ -float IntegrateEdge(vec3 v1, vec3 v2) { - float cosTheta = dot(v1, v2); - float theta = acos(cosTheta); - return cross(v1, v2).z * ((theta > 0.001) ? theta/sin(theta) : 4.0); -} - -vec3 LTC_Evaluate(vec3 N, vec3 V, vec3 P, mat3 Minv, vec3 points[4]) { - // construct orthonormal basis around N - vec3 T1, T2; - T1 = normalize(V - N*dot(V, N)); - T2 = cross(N, T1); - - // rotate area light in (T1, T2, N) basis - Minv = Minv * transpose(mat3(T1, T2, N)); - - // polygon (allocate 5 vertices for clipping) - vec3 L[5]; - L[0] = Minv * (points[0] - P); - L[1] = Minv * (points[1] - P); - L[2] = Minv * (points[2] - P); - L[3] = Minv * (points[3] - P); - - int n; - ClipQuadToHorizon(L, n); - - if (n == 0) - return vec3(0, 0, 0); - - // project onto sphere - L[0] = normalize(L[0]); - L[1] = normalize(L[1]); - L[2] = normalize(L[2]); - L[3] = normalize(L[3]); - L[4] = normalize(L[4]); - - // integrate - float sum = 0.0; - - sum += IntegrateEdge(L[0], L[1]); - sum += IntegrateEdge(L[1], L[2]); - sum += IntegrateEdge(L[2], L[3]); - if (n >= 4) - sum += IntegrateEdge(L[3], L[4]); - if (n == 5) - sum += IntegrateEdge(L[4], L[0]); - - sum = max(0.0, sum); - - vec3 Lo_i = vec3(sum, sum, sum); - - return Lo_i; -} diff --git a/cocos/renderer/bin/chunks/shadow-depth-fs.inc b/cocos/renderer/bin/chunks/shadow-depth-fs.inc deleted file mode 100644 index b726b706a9..0000000000 --- a/cocos/renderer/bin/chunks/shadow-depth-fs.inc +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -uniform float depthScale; -varying float vDepth; - -#include - -vec4 frag() { - // doing exp() here will cause float precision issue. - //float depth = clamp(exp(-min(87.0, depthScale * vDepth)), 0.0, 1.0); - return packDepthToRGBA(vDepth); - // TODO: if support float32 * 4 color buffer? - //gl_FragColor = vec4(depth, 1.0, 1.0, 1.0); -} diff --git a/cocos/renderer/bin/chunks/shadow-depth-vs.inc b/cocos/renderer/bin/chunks/shadow-depth-vs.inc deleted file mode 100644 index 91bb83f4da..0000000000 --- a/cocos/renderer/bin/chunks/shadow-depth-vs.inc +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -attribute vec3 a_position; - -uniform mat4 model; -uniform mat4 lightViewProjMatrix; -uniform float minDepth; -uniform float maxDepth; -uniform float bias; -varying float vDepth; - -#if USE_SKINNING - #include -#endif - -vec4 vert() { - vec4 pos = vec4(a_position, 1); - - #if USE_SKINNING - mat4 skinMat = skinMatrix(); - pos = skinMat * pos; - #endif - - // compute vDepth according to active camera's minDepth and maxDepth. - vDepth = ((gl_Position.z + minDepth) / (minDepth + maxDepth)) + bias; - return lightViewProjMatrix * model * pos; -} diff --git a/cocos/renderer/bin/chunks/shadow-mapping.inc b/cocos/renderer/bin/chunks/shadow-mapping.inc deleted file mode 100644 index 0a241154a4..0000000000 --- a/cocos/renderer/bin/chunks/shadow-mapping.inc +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -#if NUM_SHADOW_LIGHTS > 0 - #pragma for id in range(0, NUM_SHADOW_LIGHTS) - uniform sampler2D shadowMap_{id}; - uniform float darkness_{id}; - uniform float depthScale_{id}; - uniform float frustumEdgeFalloff_{id}; - uniform float bias_{id}; - uniform vec2 texelSize_{id}; - varying vec4 pos_lightspace_{id}; - varying float vDepth_{id}; - #pragma endFor -#endif - -float computeShadow(sampler2D shadowMap, vec4 pos_lightspace, float bias) { - vec3 projCoords = pos_lightspace.xyz / pos_lightspace.w; - projCoords = projCoords * 0.5 + 0.5; - float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy)); - float currentDepth = projCoords.z; - float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0; - return shadow; -} - -float computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) { - float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0)); - return mix(esm, 1.0, mask); -} - -// unused for float precision issue. -// float computeShadowESM_Unused() { -// vec2 projCoords = pos_lightspace.xy / pos_lightspace.w; -// vec2 shadowUV = projCoords * 0.5 + vec2(0.5); -// if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) { -// return 1.0; -// } -// float currentDepth = clamp(vDepth, 0.0, 1.0); -// float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV)); -// float esm = 1.0 - clamp(exp(min(87.0, depthScale * currentDepth)) * closestDepth, 0.0, darkness); -// return computeFallOff(esm, projCoords, frustumEdgeFalloff); -// } - -float computeShadowESM(sampler2D shadowMap, vec4 pos_lightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) { - vec2 projCoords = pos_lightspace.xy / pos_lightspace.w; - vec2 shadowUV = projCoords * 0.5 + vec2(0.5); - if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) { - return 1.0; - } - float currentDepth = clamp(vDepth, 0.0, 1.0); - float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV)); - //float esm = clamp(exp(min(87.0, -depthScale * (currentDepth - closestDepth))), 1.0 - darkness, 1.0); - float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0); - return computeFallOff(esm, projCoords, frustumEdgeFalloff); -} - -float computeShadowPCF(sampler2D shadowMap, vec4 pos_lightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) { - vec2 projCoords = pos_lightspace.xy / pos_lightspace.w; - vec2 shadowUV = projCoords * 0.5 + vec2(0.5); - if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) { - return 1.0; - } - float currentDepth = clamp(vDepth, 0.0, 1.0); - float visibility = 1.0; - vec2 poissonDisk[4]; - poissonDisk[0] = vec2(-0.94201624, -0.39906216); - poissonDisk[1] = vec2(0.94558609, -0.76890725); - poissonDisk[2] = vec2(-0.094184101, -0.92938870); - poissonDisk[3] = vec2(0.34495938, 0.29387760); - if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25; - if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25; - if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25; - if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25; - - return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff); -} \ No newline at end of file diff --git a/cocos/renderer/bin/chunks/skinning.inc b/cocos/renderer/bin/chunks/skinning.inc deleted file mode 100644 index 42201f5ca3..0000000000 --- a/cocos/renderer/bin/chunks/skinning.inc +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -attribute vec4 a_weights; -attribute vec4 a_joints; - -#if USE_JOINTS_TEXTURE -uniform sampler2D u_jointsTexture; -uniform float u_jointsTextureSize; - -mat4 getBoneMatrix(const in float i) { - float size = u_jointsTextureSize; - float j = i * 4.0; - float x = mod(j, size); - float y = floor(j / size); - - float dx = 1.0 / size; - float dy = 1.0 / size; - - y = dy * (y + 0.5); - - vec4 v1 = texture2D(u_jointsTexture, vec2(dx * (x + 0.5), y)); - vec4 v2 = texture2D(u_jointsTexture, vec2(dx * (x + 1.5), y)); - vec4 v3 = texture2D(u_jointsTexture, vec2(dx * (x + 2.5), y)); - vec4 v4 = texture2D(u_jointsTexture, vec2(dx * (x + 3.5), y)); - - return mat4(v1, v2, v3, v4); -} -#else -uniform mat4 u_jointMatrices[128]; - -mat4 getBoneMatrix(const in float i) { - return u_jointMatrices[int(i)]; -} -#endif - -mat4 skinMatrix() { - return - getBoneMatrix(a_joints.x) * a_weights.x + - getBoneMatrix(a_joints.y) * a_weights.y + - getBoneMatrix(a_joints.z) * a_weights.z + - getBoneMatrix(a_joints.w) * a_weights.w - ; -} \ No newline at end of file diff --git a/cocos/renderer/bin/chunks/sprite-fs.inc b/cocos/renderer/bin/chunks/sprite-fs.inc deleted file mode 100644 index 1ef0462f55..0000000000 --- a/cocos/renderer/bin/chunks/sprite-fs.inc +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -uniform sampler2D mainTexture; -varying vec2 uv0; -varying vec4 color; - -vec4 frag () { - vec4 o = vec4(1, 1, 1, 1); - - o *= texture2D(mainTexture, uv0); - o *= color; - - return o; -} diff --git a/cocos/renderer/bin/chunks/sprite-vs.inc b/cocos/renderer/bin/chunks/sprite-vs.inc deleted file mode 100644 index ba0bb0aeaa..0000000000 --- a/cocos/renderer/bin/chunks/sprite-vs.inc +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -attribute vec3 a_position; -uniform mat4 model; -uniform mat4 viewProj; - -attribute vec2 a_uv0; -attribute vec4 a_color; -varying vec2 uv0; -varying vec4 color; - -vec4 vert () { - vec4 pos = vec4(a_position, 1); - - pos = viewProj * model * pos; - - uv0 = a_uv0; - - color = a_color; - - return pos; -} diff --git a/cocos/renderer/bin/chunks/unlit-fs.inc b/cocos/renderer/bin/chunks/unlit-fs.inc deleted file mode 100644 index 29b7d9290d..0000000000 --- a/cocos/renderer/bin/chunks/unlit-fs.inc +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -#if USE_TEXTURE - uniform sampler2D mainTexture; - varying vec2 uv0; -#endif - -#if USE_COLOR - uniform vec4 color; -#endif - -vec4 frag () { - vec4 o = vec4(1, 1, 1, 1); - - #if USE_TEXTURE - o *= texture2D(mainTexture, uv0); - #endif - - #if USE_COLOR - o *= color; - #endif - - return o; -} diff --git a/cocos/renderer/bin/chunks/unlit-vs.inc b/cocos/renderer/bin/chunks/unlit-vs.inc deleted file mode 100644 index 84852a89eb..0000000000 --- a/cocos/renderer/bin/chunks/unlit-vs.inc +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -attribute vec3 a_position; - -uniform mat4 model; -uniform mat4 viewProj; - -#if USE_TEXTURE - attribute vec2 a_uv0; - uniform vec2 mainTiling; - uniform vec2 mainOffset; - varying vec2 uv0; -#endif - -#if USE_SKINNING - #include -#endif - -vec4 vert () { - vec4 pos = vec4(a_position, 1); - - #if USE_SKINNING - pos = skinMatrix() * pos; - #endif - - pos = viewProj * model * pos; - - #if USE_TEXTURE - uv0 = a_uv0 * mainTiling + mainOffset; - #endif - - return pos; -} diff --git a/cocos/renderer/bin/chunks/unpack.inc b/cocos/renderer/bin/chunks/unpack.inc deleted file mode 100644 index 0db1f5c564..0000000000 --- a/cocos/renderer/bin/chunks/unpack.inc +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -vec3 unpackNormal(vec4 nmap) { - return nmap.xyz * 2.0 - 1.0; -} - -vec3 unpackRGBE(vec4 rgbe) { - return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0); -} \ No newline at end of file diff --git a/cocos/renderer/bin/shdc-lib.js b/cocos/renderer/bin/shdc-lib.js deleted file mode 100644 index 04ee22fec3..0000000000 --- a/cocos/renderer/bin/shdc-lib.js +++ /dev/null @@ -1,400 +0,0 @@ -'use strict'; - -const tokenizer = require('glsl-tokenizer/string'); -const mappings = require('../../../bin/mappings'); -const { sha3_224 } = require('js-sha3'); - -let includeRE = /#include +<([\w-.]+)>/gm; -let defineRE = /#define\s+(\w+)\(([\w,\s]+)\)\s+(.*##.*)\n/g; -let whitespaces = /\s+/g; -let ident = /^[_a-zA-Z]\w*$/; -let extensionRE = /(?:GL_)?(\w+)/; -let comparators = /^[<=>]+$/; -let ifprocessor = /#(el)?if/; -let rangePragma = /range\(([\d.,\s]+)\)\s(\w+)/; -let defaultPragma = /default\(([\d.,]+)\)/; -let namePragma = /name\(([^)]+)\)/; -let precision = /(low|medium|high)p/; - -// (HACKY) extract all builtin uniforms to the ignore list -let uniformIgnoreList = (function() { - const fs = require('fs'); - let result = new Set(), extract = function(path) { - let renderer = fs.readFileSync(path, { encoding: 'utf8' }); - let re = /set(Uniform|Texture)\([`'"](\w+)[`'"]/g, cap = re.exec(renderer); - while (cap) { result[cap[2]] = true; cap = re.exec(renderer); } - }; - extract('resources/3d/engine/cocos/renderer/renderers/forward-renderer.js'); - extract('resources/3d/engine/cocos/renderer/core/base-renderer.js'); - return result; -})(); - -function convertType(t) { let tp = mappings.typeParams[t.toUpperCase()]; return tp === undefined ? t : tp; } - -function unwindIncludes(str, chunks) { - function replace(match, include) { - let replace = chunks[include]; - if (replace === undefined) { - console.error(`can not resolve #include <${include}>`); - } - return unwindIncludes(replace, chunks); - } - return str.replace(includeRE, replace); -} - -function glslStripComment(code) { - let tokens = tokenizer(code); - - let result = ''; - for (let i = 0; i < tokens.length; ++i) { - let t = tokens[i]; - if (t.type != 'block-comment' && t.type != 'line-comment' && t.type != 'eof') { - result += t.data; - } - } - - return result; -} - -function extractDefines(tokens, defines, cache) { - let curDefs = [], save = (line) => { - cache[line] = curDefs.reduce((acc, val) => acc.concat(val), []); - cache.lines.push(line); - }; - for (let i = 0; i < tokens.length; ++i) { - let t = tokens[i], str = t.data, id, df; - if (t.type !== 'preprocessor') continue; - str = str.split(whitespaces); - if (str[0] === '#endif') { - curDefs.pop(); save(t.line); continue; - } else if (str[0] === '#else') { - curDefs[curDefs.length - 1].length = 0; save(t.line); continue; - } else if (str[0] === '#pragma') { - if (str[1] === 'for') { curDefs.push(0); save(t.line); } - else if (str[1] === 'endFor') { curDefs.pop(); save(t.line); } - else if (str[1][0] === '#') cache[t.line] = str.splice(1); - else { - let mc = rangePragma.exec(t.data); - if (!mc) continue; - let def = defines.find(d => d.name === mc[2]); - if (!def) defines.push(def = { name: mc[2] }); - def.type = 'number'; - def.range = JSON.parse(`[${mc[1]}]`); - } - continue; - } else if (!ifprocessor.test(str[0])) continue; - if (str[0] === '#elif') { curDefs.pop(); save(t.line); } - let defs = []; - str.splice(1).some(s => { - id = s.match(ident); - if (id) { // is identifier - defs.push(id[0]); - df = defines.find(d => d.name === id[0]); - if (df) return; // first encounter - defines.push(df = { name: id[0], type: 'boolean' }); - } else if (comparators.test(s)) df.type = 'number'; - else if (s === '||') return true; - }); - curDefs.push(defs); save(t.line); - } - return defines; -} - -function extractParams(tokens, cache, uniforms, attributes, extensions) { - let getDefs = line => { - let idx = cache.lines.findIndex(i => i > line); - return cache[cache.lines[idx - 1]] || []; - }; - for (let i = 0; i < tokens.length; i++) { - let t = tokens[i], tp = t.type, str = t.data, dest; - if (tp === 'keyword' && str === 'uniform') dest = uniforms; - else if (tp === 'keyword' && str === 'attribute') dest = attributes; - else if (tp === 'preprocessor' && str.startsWith('#extension')) dest = extensions; - else continue; - let defines = getDefs(t.line), param = {}; - if (defines.findIndex(i => !i) >= 0) continue; // inside pragmas - if (dest === uniforms && uniformIgnoreList[tokens[i+4].data]) continue; - if (dest === extensions) { - if (defines.length !== 1) console.warn('extensions must be under controll of exactly 1 define'); - param.name = extensionRE.exec(str.split(whitespaces)[1])[1]; - param.define = defines[0]; - dest.push(param); - continue; - } else { // uniforms and attributes - let offset = precision.exec(tokens[i+2].data) ? 4 : 2; - param.name = tokens[i+offset+2].data; - param.type = convertType(tokens[i+offset].data); - let tags = cache[t.line - 1]; - if (tags && tags[0][0] === '#') { // tags - let mc = defaultPragma.exec(tags.join('')); - if (mc && mc[1].length > 0) { - mc = JSON.parse(`[${mc[1]}]`); - if (mc.length === 1) param.value = mc[0]; - else param.value = mc; - } - mc = namePragma.exec(tags.join(' ')); - if (mc) param.displayName = mc[1]; - for (let j = 0; j < tags.length; j++) { - let tag = tags[j]; - if (tag === '#color') param.type = convertType(param.type); - else if (tag === '#property') param.property = true; - } - } - } - param.defines = defines; - dest.push(param); - } -} - -let expandStructMacro = (function() { - function matchParenthesisPair(string, startIdx) { - let parHead = startIdx; - let parTail = parHead; - let depth = 0; - for (let i = startIdx; i < string.length; i++) - if (string[i] === '(') { parHead = i; depth = 1; break; } - if (depth === 0) return parHead; - for (let i = parHead + 1; i < string.length; i++) { - if (string[i] === '(') depth++; - if (string[i] === ')') depth--; - if (depth === 0) { parTail = i; break; } - } - if (depth !== 0) return parHead; - return parTail; - } - function generateHypenRE(hyphen, macroParam) { - return '(' + [hyphen + macroParam + hyphen, hyphen + macroParam, macroParam + hyphen].join('|') + ')'; - } - function generateParamRE(param) { - return '\\b' + param + '\\b'; - } - return function (code) { - code = code.replace(/\\\n/g, ''); - let defineCapture = defineRE.exec(code); - //defineCapture[1] - the macro name - //defineCapture[2] - the macro parameters - //defineCapture[3] - the macro body - while (defineCapture != null) { - let macroRE = new RegExp('\\n.*' + defineCapture[1] + '\\s*\\(', 'g'); - let macroCapture = macroRE.exec(code); - while (macroCapture != null) { - let macroIndex = macroCapture[0].lastIndexOf(defineCapture[1]); - //the whole macro string,include name and arguments - let macroStr = code.slice(macroCapture.index + macroIndex, matchParenthesisPair(code, macroCapture.index + macroCapture[0].length - 1) + 1); - //the macro arguments list - let macroArguLine = macroStr.slice(macroCapture[0].length - macroIndex, -1); - //the string before macro's name in the matched line - let prefix = macroCapture[0].slice(0, macroIndex); - let containDefine = prefix.indexOf('#define') !== -1; - let containParenthesis = prefix.indexOf('(') !== -1; - let macroParams = defineCapture[2].split(','); - //erase the white space in the macro's parameters - for (let i = 0; i < macroParams.length; i++) { - macroParams[i] = macroParams[i].replace(/\s/g, ''); - } - let macroArgus = macroArguLine.split(','); - for (let i = 0; i < macroArgus.length; i++) { - macroArgus[i] = macroArgus[i].replace(/\s/g, ''); - } - //if the matched macro is defined in another macro, then just replace the parameters with the arguments - if (containDefine && containParenthesis) { - code = code.replace(new RegExp(defineCapture[1] + '\\(' + macroArguLine + '\\)', 'g'), (matched, offset) => { - //if the matched string is the marco we just found,the replace it - if (macroCapture.index + prefix.length == offset) { - let ret = defineCapture[3]; - for (let i = 0; i < macroParams.length; i++) { - ret = ret.replace(new RegExp(generateParamRE(macroParams[i]), 'g'), macroArgus[i]); - } - return ret; - } - return matched; - }); - //move the next match index to the beginning of the line,in case of the same macro on the same line. - macroRE.lastIndex -= macroCapture[0].length; - } - //if the matched macro is defined in the executable code block,we should consider the hypen sign('##') - if (!containDefine) { - let repStr = defineCapture[3]; - for (let i = 0; i < macroParams.length; i++) { - let hypenRE = new RegExp(generateHypenRE('##', macroParams[i]), 'g'); - if (hypenRE.test(repStr)) { - //replace the hypen sign - repStr = repStr.replace(hypenRE, macroArgus[i]); - } else { - repStr = repStr.replace(new RegExp(generateParamRE(macroParams[i]), 'g'), macroArgus[i]); - } - } - code = code.replace(macroStr, repStr); - //move the next match index to the beginning of the line,in case of the same macro on the same line. - macroRE.lastIndex -= macroCapture[0].length; - } - macroCapture = macroRE.exec(code); - } - defineCapture = defineRE.exec(code); - } - return code; - }; -})(); - -let assembleShader = (function() { - let entryRE = /([\w-]+)(?::(\w+))?/; - let integrity = /void\s+main\s*\([\w\s,]*\)/; - let wrapperFactory = (vert, fn) => `\nvoid main() { ${vert ? 'gl_Position' : 'gl_FragColor'} = ${fn}(); }\n`; - return function(name, cache, vert) { - let entryCap = entryRE.exec(name), content = cache[entryCap[1]]; - if (!content) { console.error(`shader ${entryCap[1]} not found!`); return ''; } - if (!entryCap[2]) { - if (!integrity.test(content)) console.warn(`shader main entry not found in ${name}!`); - return cache[name]; - } - return content + wrapperFactory(vert, entryCap[2]); - }; -})(); - -let buildShader = function(vertName, fragName, cache) { - let vert = assembleShader(vertName, cache, true); - let frag = assembleShader(fragName, cache); - - let defines = [], defCache = { lines: [] }, tokens; - let uniforms = [], attributes = [], extensions = []; - - vert = glslStripComment(vert); - vert = unwindIncludes(vert, cache); - vert = expandStructMacro(vert); - tokens = tokenizer(vert); - extractDefines(tokens, defines, defCache); - extractParams(tokens, defCache, uniforms, attributes, extensions); - - defCache = { lines: [] }; - frag = glslStripComment(frag); - frag = unwindIncludes(frag, cache); - frag = expandStructMacro(frag); - tokens = tokenizer(frag); - extractDefines(tokens, defines, defCache); - extractParams(tokens, defCache, uniforms, attributes, extensions); - - return { vert, frag, defines, uniforms, attributes, extensions }; -}; - -// ================== -// effects -// ================== - -let queueRE = /(\w+)(?:([+-])(\d+))?/; -let parseQueue = function (queue) { - let m = queueRE.exec(queue); - if (m === null) return 0; - let q = mappings.RenderQueue[m[1].toUpperCase()]; - if (m.length === 4) { - if (m[2] === '+') q += parseInt(m[3]); - if (m[2] === '-') q -= parseInt(m[3]); - } - return q; -}; - -function mapPassParam(p) { - let num; - switch (typeof p) { - case 'string': - num = parseInt(p); - return isNaN(num) ? mappings.passParams[p.toUpperCase()] : num; - case 'object': - return ((p[0] * 255) << 24 | (p[1] * 255) << 16 | (p[2] * 255) << 8 | (p[3] || 0) * 255) >>> 0; - } - return p; -} - -function buildEffectJSON(json) { - // map param's type offline. - for (let j = 0; j < json.techniques.length; ++j) { - let jsonTech = json.techniques[j]; - jsonTech.queue = parseQueue(jsonTech.queue ? jsonTech.queue : 'opaque'); - if (jsonTech.priority == null) { - jsonTech.priority = 0; - } - for (let k = 0; k < jsonTech.passes.length; ++k) { - let pass = jsonTech.passes[k]; - if (pass.stage == null) { - pass.stage = 'default'; - } - for (let key in pass) { - if (key === "vert" || key === 'frag') continue; - pass[key] = mapPassParam(pass[key]); - } - } - } - for (let prop in json.properties) { - let info = json.properties[prop]; - info.type = mappings.typeParams[info.type.toUpperCase()]; - } - return json; -} - -let parseEffect = (function() { - let effectRE = /%{([^%]+)%}/; - let blockRE = /%%\s*([\w-]+)\s*{([^]+)}/; - let parenRE = /[{}]/g; - let trimToSize = content => { - let level = 1, end = content.length; - content.replace(parenRE, (p, i) => { - if (p === '{') level++; - else if (level === 1) { end = i; level = 1e9; } - else level--; - }); - return content.substring(0, end); - }; - return function (content) { - let effectCap = effectRE.exec(content); - let effect = JSON.parse(`{${effectCap[1]}}`), templates = {}; - content = content.substring(effectCap.index + effectCap[0].length); - let blockCap = blockRE.exec(content); - while (blockCap) { - let str = templates[blockCap[1]] = trimToSize(blockCap[2]); - content = content.substring(blockCap.index + str.length); - blockCap = blockRE.exec(content); - } - return { effect, templates }; - }; -})(); - -// (HACKY) fixed builtin headers -let chunksCache = (function() { - const path_ = require('path'); - const fsJetpack = require('fs-jetpack'); - const fs = require('fs'); - let files = fsJetpack.find('resources/3d/engine/cocos/renderer/bin/chunks', { matching: ['**/*.inc'] }), cache = {}; - for (let i = 0; i < files.length; ++i) { - let name = path_.basename(files[i], '.inc'); - let content = fs.readFileSync(files[i], { encoding: 'utf8' }); - cache[name] = glslStripComment(content); - } - return cache; -})(); - -let buildEffect = function (name, content) { - let { effect, templates } = parseEffect(content); - effect = buildEffectJSON(effect); effect.name = name; - Object.assign(templates, chunksCache); - let shaders = effect.shaders = []; - for (let j = 0; j < effect.techniques.length; ++j) { - let jsonTech = effect.techniques[j]; - for (let k = 0; k < jsonTech.passes.length; ++k) { - let pass = jsonTech.passes[k]; - let vert = pass.vert, frag = pass.frag; - let shader = buildShader(vert, frag, templates); - let name = sha3_224(shader.vert + shader.frag); - shader.name = pass.program = name; - delete pass.vert; delete pass.frag; - shaders.push(shader); - } - } - return effect; -}; - -// ================== -// exports -// ================== - -module.exports = { - buildEffect -}; diff --git a/cocos/renderer/core/base-renderer.js b/cocos/renderer/core/base-renderer.js index c0bf38e2d6..ea7d6cab28 100644 --- a/cocos/renderer/core/base-renderer.js +++ b/cocos/renderer/core/base-renderer.js @@ -571,10 +571,10 @@ export default class BaseRenderer { view.getPosition(_camPos); // update uniforms - this._device.setUniform('view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - this._device.setUniform('eye', vec3.array(_a3_camPos, _camPos)); + this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); + this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); + this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); + this._device.setUniform('_eye', vec3.array(_a3_camPos, _camPos)); // calculate sorting key for (let i = 0; i < stageItems.length; ++i) { @@ -607,10 +607,10 @@ export default class BaseRenderer { view.getForward(_camFwd); // update uniforms - this._device.setUniform('view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - this._device.setUniform('eye', vec3.array(_a3_camPos, _camPos)); + this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); + this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); + this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); + this._device.setUniform('_eye', vec3.array(_a3_camPos, _camPos)); // calculate zdist for (let i = 0; i < stageItems.length; ++i) { @@ -644,9 +644,9 @@ export default class BaseRenderer { _renderOverlay(view, stageItems) { // update uniforms - this._device.setUniform('view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); + this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); + this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); + this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); // sort items stageItems.sort((a, b) => { @@ -682,6 +682,12 @@ export default class BaseRenderer { _int4_pool.reset(); _int64_pool.reset(); + node.getWorldMatrix(_m4_tmp); + device.setUniform('_model', mat4.array(_float16_pool.add(), _m4_tmp)); + + mat3.normalFromMat4(_m3_tmp, _m4_tmp); + device.setUniform('_normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp)); + // set uniforms for (let name in effect._properties) { let propInfo = effect._properties[name]; @@ -691,16 +697,6 @@ export default class BaseRenderer { prop = this._type2defaultValue[propInfo.type]; } - // set common uniforms - if (name === 'model') { - node.getWorldMatrix(_m4_tmp); - prop = _m4_tmp; - } - else if (name === 'normalMatrix') { - mat3.normalFromMat4(_m3_tmp, _m4_tmp); - prop = _m3_tmp; - } - if (prop === undefined || prop === null) { console.warn(`Failed to set technique property ${name}, value not found.`); continue; diff --git a/cocos/renderer/core/pass.js b/cocos/renderer/core/pass.js index a5d5de2279..d1bd128b0b 100644 --- a/cocos/renderer/core/pass.js +++ b/cocos/renderer/core/pass.js @@ -15,8 +15,8 @@ export default class Pass { this._blend = false; this._blendEq = gfx.BLEND_FUNC_ADD; this._blendAlphaEq = gfx.BLEND_FUNC_ADD; - this._blendSrc = gfx.BLEND_ONE; - this._blendDst = gfx.BLEND_ZERO; + this._blendSrc = gfx.BLEND_SRC_ALPHA; + this._blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA; this._blendSrcAlpha = gfx.BLEND_ONE; this._blendDstAlpha = gfx.BLEND_ZERO; this._blendColor = 0xffffffff; diff --git a/cocos/renderer/gfx/device.js b/cocos/renderer/gfx/device.js index fcab420606..7b9f1dbeaa 100644 --- a/cocos/renderer/gfx/device.js +++ b/cocos/renderer/gfx/device.js @@ -633,7 +633,7 @@ export default class Device { this._initExtension(builtin_exts[i]); } let exts = gl.getSupportedExtensions(); - this._supportedExts = exts.reduce((acc, cur) => acc[cur] = true, {}); + this._supportedExts = exts.reduce((acc, cur) => { acc[cur] = true; return acc; }, {}); this._initCaps(); this._initStates(); diff --git a/cocos/renderer/renderers/forward-renderer.js b/cocos/renderer/renderers/forward-renderer.js index ec1fba6a89..a02b8f013f 100644 --- a/cocos/renderer/renderers/forward-renderer.js +++ b/cocos/renderer/renderers/forward-renderer.js @@ -144,55 +144,55 @@ export default class ForwardRenderer extends BaseRenderer { } _submitLightUniforms() { - this._device.setUniform('sceneAmbient', this._sceneAmbient); + this._device.setUniform('_sceneAmbient', this._sceneAmbient); if (this._directionalLights.length > 0) { for (let index = 0; index < this._directionalLights.length; ++index) { let light = this._directionalLights[index]; - this._device.setUniform(`dir_light${index}_direction`, light._directionUniform); - this._device.setUniform(`dir_light${index}_color`, light._colorUniform); + this._device.setUniform(`_dir_light${index}_direction`, light._directionUniform); + this._device.setUniform(`_dir_light${index}_color`, light._colorUniform); } } if (this._pointLights.length > 0) { for (let index = 0; index < this._pointLights.length; ++index) { let light = this._pointLights[index]; - this._device.setUniform(`point_light${index}_position`, light._positionUniform); - this._device.setUniform(`point_light${index}_color`, light._colorUniform); - this._device.setUniform(`point_light${index}_range`, light._range); + this._device.setUniform(`_point_light${index}_position`, light._positionUniform); + this._device.setUniform(`_point_light${index}_color`, light._colorUniform); + this._device.setUniform(`_point_light${index}_range`, light._range); } } if (this._spotLights.length > 0) { for (let index = 0; index < this._spotLights.length; ++index) { let light = this._spotLights[index]; - this._device.setUniform(`spot_light${index}_position`, light._positionUniform); - this._device.setUniform(`spot_light${index}_direction`, light._directionUniform); - this._device.setUniform(`spot_light${index}_color`, light._colorUniform); - this._device.setUniform(`spot_light${index}_range`, light._range); - this._device.setUniform(`spot_light${index}_spot`, light._spotUniform); + this._device.setUniform(`_spot_light${index}_position`, light._positionUniform); + this._device.setUniform(`_spot_light${index}_direction`, light._directionUniform); + this._device.setUniform(`_spot_light${index}_color`, light._colorUniform); + this._device.setUniform(`_spot_light${index}_range`, light._range); + this._device.setUniform(`_spot_light${index}_spot`, light._spotUniform); } } } _submitShadowStageUniforms(view) { let light = view._shadowLight; - this._device.setUniform('minDepth', light.shadowMinDepth); - this._device.setUniform('maxDepth', light.shadowMaxDepth); - this._device.setUniform('bias', light.shadowBias); - this._device.setUniform('depthScale', light.shadowDepthScale); + this._device.setUniform('_minDepth', light.shadowMinDepth); + this._device.setUniform('_maxDepth', light.shadowMaxDepth); + this._device.setUniform('_bias', light.shadowBias); + this._device.setUniform('_depthScale', light.shadowDepthScale); } _submitOtherStagesUniforms() { for (let index = 0; index < this._shadowLights.length; ++index) { let light = this._shadowLights[index]; - this._device.setUniform(`lightViewProjMatrix_${index}`, mat4.array(_a16_lightViewProj, light.viewProjMatrix)); - this._device.setUniform(`minDepth_${index}`, light.shadowMinDepth); - this._device.setUniform(`maxDepth_${index}`, light.shadowMaxDepth); - this._device.setUniform(`bias_${index}`, light.shadowBias); - this._device.setUniform(`depthScale_${index}`, light.shadowDepthScale); - this._device.setUniform(`darkness_${index}`, light.shadowDarkness); - this._device.setUniform(`frustumEdgeFalloff_${index}`, light.frustumEdgeFalloff); - this._device.setUniform(`texelSize_${index}`, new Float32Array([1.0 / light.shadowResolution, 1.0 / light.shadowResolution])); + this._device.setUniform(`_lightViewProjMatrix_${index}`, mat4.array(_a16_lightViewProj, light.viewProjMatrix)); + this._device.setUniform(`_minDepth_${index}`, light.shadowMinDepth); + this._device.setUniform(`_maxDepth_${index}`, light.shadowMaxDepth); + this._device.setUniform(`_bias_${index}`, light.shadowBias); + this._device.setUniform(`_depthScale_${index}`, light.shadowDepthScale); + this._device.setUniform(`_darkness_${index}`, light.shadowDarkness); + this._device.setUniform(`_frustumEdgeFalloff_${index}`, light.frustumEdgeFalloff); + this._device.setUniform(`_texelSize_${index}`, new Float32Array([1.0 / light.shadowResolution, 1.0 / light.shadowResolution])); } } @@ -210,7 +210,7 @@ export default class ForwardRenderer extends BaseRenderer { } _shadowStage(item) { - this._device.setUniform('lightViewProjMatrix', mat4.array(_a16_viewProj, this._currentView._matViewProj)); + this._device.setUniform('_lightViewProjMatrix', mat4.array(_a16_viewProj, this._currentView._matViewProj)); // update rendering // this._submitLightUniforms(); @@ -240,7 +240,7 @@ export default class ForwardRenderer extends BaseRenderer { for (let index = 0; index < this._shadowLights.length; ++index) { let light = this._shadowLights[index]; - this._device.setTexture(`shadowMap_${index}`, light.shadowMap, this._allocTextureUnit()); + this._device.setTexture(`_shadowMap_${index}`, light.shadowMap, this._allocTextureUnit()); } this._drawPass(item); @@ -254,11 +254,11 @@ export default class ForwardRenderer extends BaseRenderer { defines.USE_SKINNING = true; if (model._jointsTexture != null) { defines.USE_JOINTS_TEXTURE = true; - this._device.setTexture('u_jointsTexture', model._jointsTexture, this._allocTextureUnit()); - this._device.setUniform('u_jointsTextureSize', model._jointsTexture._width); + this._device.setTexture('_u_jointsTexture', model._jointsTexture, this._allocTextureUnit()); + this._device.setUniform('_u_jointsTextureSize', model._jointsTexture._width); } else if (model._jointsMatrixArray != null) { defines.USE_JOINTS_TEXTURE = false; - this._device.setUniform("u_jointMatrices", model._jointsMatrixArray); + this._device.setUniform("_u_jointMatrices", model._jointsMatrixArray); } this._draw(item); diff --git a/cocos/scene-graph/layers.js b/cocos/scene-graph/layers.js index b4d26c6491..911bbe3e55 100644 --- a/cocos/scene-graph/layers.js +++ b/cocos/scene-graph/layers.js @@ -9,7 +9,7 @@ class Layers { * @return {number} new layer's index */ static addLayer(name) { - if (Layers._nextAvailable > 31) + if (Layers._nextAvailable > 31) return new Error('maximum layers reached.'); Layers[name] = (1 << Layers._nextAvailable++); return Layers[name]; @@ -56,8 +56,8 @@ Layers.Gizmos = (1 << 2); Layers.PanPlanes = (1 << 3); // masks -Layers.All = Layers.makeExclusiveMask([Layers.Gizmos]); -Layers.RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.IgnoreRaycast]); +Layers.All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.PanPlanes]); +Layers.RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.PanPlanes, Layers.IgnoreRaycast]); export default Layers; cc.Layers = Layers; diff --git a/package.json b/package.json index a28f7838db..59b7933793 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,7 @@ "scripts": { "server": "http-server . -p 8002", "build": "npm run build:dev && npm run build:min", - "build:effect": "rollup -c ./rollup/mappings.config.js && node ./rollup/build-effect.js", - "build:dev": "npm run build:effect && rollup -c ./rollup/config.js", + "build:dev": "rollup -c ./rollup/config.js", "build:min": "uglifyjs ./bin/cocos-3d.dev.js --mangle --source-map -o ./bin/cocos-3d.min.js", "dev": "rollup -w -c ./rollup/config.js" }, @@ -36,7 +35,6 @@ "event-stream": "3.3.2", "fire-fs": "0.2.1", "fs-jetpack": "^1.1.0", - "glsl-tokenizer": "^2.1.5", "gulp": "^3.9.1", "gulp-babel": "6.1.2", "gulp-cached": "1.1.0", @@ -55,7 +53,6 @@ "gulp-util": "3.0.6", "http-server": "^0.11.1", "jshint-stylish": "2.1.0", - "js-sha3": "^0.8.0", "multipipe": "0.3.0", "persistify": "^1.1.1", "require-dir": "0.3.0", diff --git a/playground/savePrimitivesAsWavefrontOBJ.html b/playground/savePrimitivesAsWavefrontOBJ.html new file mode 100644 index 0000000000..4cf4276c1d --- /dev/null +++ b/playground/savePrimitivesAsWavefrontOBJ.html @@ -0,0 +1,53 @@ + + + + + spec-scroll-view + + + + + + + + + + + + + diff --git a/rollup/build-effect.js b/rollup/build-effect.js deleted file mode 100644 index d1e933da9f..0000000000 --- a/rollup/build-effect.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const shdcLib = require('../cocos/renderer/bin/shdc-lib'); - -const path_ = require('path'); -const fs = require('fs'); -const fsJetpack = require('fs-jetpack'); - -let stringifyShaders = (function() { - let newlines = /\n+/g; - let toOneLiner = o => '\n ' + JSON.stringify(o).replace(/([,:])/g, '$1 '); - return function (shaders) { - let code = ''; - for (let i = 0; i < shaders.length; ++i) { - let { name, vert, frag, defines, uniforms, attributes, extensions } = shaders[i]; - vert = vert.replace(newlines, '\\n'); - frag = frag.replace(newlines, '\\n'); - code += ' {\n'; - code += ` "name": "${name}",\n`; - code += ` "vert": "${vert}",\n`; - code += ` "frag": "${frag}",\n`; - code += ' "defines": ['; - code += defines.map(toOneLiner); - code += (defines.length ? '\n ' : '') + '],\n'; - code += ' "uniforms": ['; - code += uniforms.map(toOneLiner); - code += (uniforms.length ? '\n ' : '') + '],\n'; - code += ' "attributes": ['; - code += attributes.map(toOneLiner); - code += (attributes.length ? '\n ' : '') + '],\n'; - code += ' "extensions": ['; - code += extensions.map(toOneLiner); - code += (extensions.length ? '\n ' : '') + ']\n'; - code += ' },\n'; - } - return `[\n${code.slice(0, -2)}\n]`; - }; -})(); - -let indent = (str, num) => str.replace(/\n/g, '\n'+' '.repeat(num)); -let path = './cocos/3d/builtin/effects'; -let dest = path_.join(path, 'index.json'); -let files = fsJetpack.find(path, { matching: ['**/*.effect'] }), code = ``; -for (let i = 0; i < files.length; ++i) { - let name = path_.basename(files[i], '.effect'); - let content = fs.readFileSync(files[i], { encoding: 'utf8' }); - let effect = shdcLib.buildEffect(name, content); - code += ' {\n'; - code += ` "name": "${effect.name}",\n`; - code += ` "techniques": ${JSON.stringify(effect.techniques)},\n`; - code += ` "properties": ${JSON.stringify(effect.properties)},\n`; - code += ` "shaders": ${indent(stringifyShaders(effect.shaders), 4)}\n`; - code += ' },\n'; -} -fs.writeFileSync(dest, `[\n${code.slice(0, -2)}\n]\n`, { encoding: 'utf8' }); diff --git a/rollup/mappings.config.js b/rollup/mappings.config.js deleted file mode 100644 index d31c47a170..0000000000 --- a/rollup/mappings.config.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const fsJetpack = require('fs-jetpack'); -const resolve = require('rollup-plugin-node-resolve'); - -console.log('rollup mappings...'); - -let dest = './bin'; -let file = 'mappings'; -let name = 'mappings'; -let sourcemap = true; -let globals = {}; - -fsJetpack.dir(dest); - -module.exports = { - input: './cocos/3d/misc/offline-mappings.js', - external: [], - plugins: [ - resolve({ - jsnext: false, - main: false, - root: process.cwd() - }), - ], - output: [ - { - file: `${dest}/${file}.js`, - format: 'cjs', - name, - globals, - sourcemap, - }, - ], -};