From ac0d84f92dd4d6006510ffcb6076a62145d5b3b5 Mon Sep 17 00:00:00 2001 From: Myway Date: Tue, 23 Jul 2019 17:37:58 +0800 Subject: [PATCH] 3d v1.0.0 terrain (#4953) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 上传地形系统 * 上传地形系统 * 新增地形导出 * 新增Terrain Shader * vmath相关修改 * 修复TerrainSample启动崩溃问题 --- cocos/3d/builtin/effects.ts | 74 + cocos/renderer/index.ts | 1 + cocos/renderer/terrain/height-field.ts | 70 + cocos/renderer/terrain/terrain-brush.ts | 182 +++ .../renderer/terrain/terrain-editor-manage.ts | 7 + cocos/renderer/terrain/terrain-editor-mode.ts | 15 + .../renderer/terrain/terrain-editor-paint.ts | 176 +++ .../renderer/terrain/terrain-editor-sculpt.ts | 112 ++ cocos/renderer/terrain/terrain-editor.ts | 143 ++ cocos/renderer/terrain/terrain-operation.ts | 193 +++ cocos/renderer/terrain/terrain-sample.ts | 185 +++ cocos/renderer/terrain/terrain.ts | 1254 +++++++++++++++++ 12 files changed, 2412 insertions(+) create mode 100644 cocos/renderer/terrain/height-field.ts create mode 100644 cocos/renderer/terrain/terrain-brush.ts create mode 100644 cocos/renderer/terrain/terrain-editor-manage.ts create mode 100644 cocos/renderer/terrain/terrain-editor-mode.ts create mode 100644 cocos/renderer/terrain/terrain-editor-paint.ts create mode 100644 cocos/renderer/terrain/terrain-editor-sculpt.ts create mode 100644 cocos/renderer/terrain/terrain-editor.ts create mode 100644 cocos/renderer/terrain/terrain-operation.ts create mode 100644 cocos/renderer/terrain/terrain-sample.ts create mode 100644 cocos/renderer/terrain/terrain.ts diff --git a/cocos/3d/builtin/effects.ts b/cocos/3d/builtin/effects.ts index d68fdf1493..e762f1a096 100644 --- a/cocos/3d/builtin/effects.ts +++ b/cocos/3d/builtin/effects.ts @@ -249,6 +249,44 @@ export default [ } ] }, + { + "name": "builtin-terrain", + "techniques": [ + {"name":"opaque", "passes":[{"program":"builtin-terrain|terrain-vs:vert|terrain-fs:frag", "properties":{"UVScale":{"value":[1, 1, 1, 1], "type":16}, "weightMap":{"value":"black", "type":28}, "detailMap0":{"value":"grey", "type":28}, "detailMap1":{"value":"grey", "type":28}, "detailMap2":{"value":"grey", "type":28}, "detailMap3":{"value":"grey", "type":28}}}]} + ], + "shaders": [ + { + "name": "builtin-terrain|terrain-vs:vert|terrain-fs:frag", + "hash": 2211091679, + "glsl3": { + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nout vec2 uvw;\nout vec2 uv0;\nout vec2 uv1;\nout vec2 uv2;\nout vec2 uv3;\nout vec3 diffuse;\nuniform TexCoords {\n vec4 UVScale;\n};\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n pos = cc_matViewProj * pos;\n uvw = a_texCoord;\n uv0 = a_position.xz * UVScale.x;\n uv1 = a_position.xz * UVScale.y;\n uv2 = a_position.xz * UVScale.z;\n uv3 = a_position.xz * UVScale.w;\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 N = a_normal;\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n diffuse = ambDiff + vec3(dot(N, L));\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n in vec2 uvw;\n in vec2 uv0;\n in vec2 uv1;\n in vec2 uv2;\n in vec2 uv3;\n in vec3 diffuse;\n uniform sampler2D weightMap;\n uniform sampler2D detailMap0;\n uniform sampler2D detailMap1;\n uniform sampler2D detailMap2;\n uniform sampler2D detailMap3;\nvec4 frag () {\n vec4 color = vec4(0, 0, 0, 0);\n #if LAYERS == 1\n color = texture(detailMap0, uv0);\n #elif LAYERS == 2\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n #elif LAYERS == 3\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n color += texture(detailMap2, uv2) * w.b;\n #elif LAYERS == 4\n vec4 w = texture(weightMap, uvw);\n color += texture(detailMap0, uv0) * w.r;\n color += texture(detailMap1, uv1) * w.g;\n color += texture(detailMap2, uv2) * w.b;\n color += texture(detailMap3, uv3) * w.a;\n #else\n color = texture(detailMap0, uv0);\n #endif\n color.rgb *= diffuse;\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + }, + "glsl1": { + "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform vec4 cc_mainLitDir;\nuniform vec4 cc_ambientSky;\nuniform vec4 cc_ambientGround;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nvarying vec2 uvw;\nvarying vec2 uv0;\nvarying vec2 uv1;\nvarying vec2 uv2;\nvarying vec2 uv3;\nvarying vec3 diffuse;\nuniform vec4 UVScale;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matWorld * pos;\n pos = cc_matViewProj * pos;\n uvw = a_texCoord;\n uv0 = a_position.xz * UVScale.x;\n uv1 = a_position.xz * UVScale.y;\n uv2 = a_position.xz * UVScale.z;\n uv3 = a_position.xz * UVScale.w;\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 N = a_normal;\n float fAmb = dot(N, vec3(0.0, -1.0, 0.0)) * 0.5 + 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n diffuse = ambDiff + vec3(dot(N, L));\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n varying vec2 uvw;\n varying vec2 uv0;\n varying vec2 uv1;\n varying vec2 uv2;\n varying vec2 uv3;\n varying vec3 diffuse;\n uniform sampler2D weightMap;\n uniform sampler2D detailMap0;\n uniform sampler2D detailMap1;\n uniform sampler2D detailMap2;\n uniform sampler2D detailMap3;\nvec4 frag () {\n vec4 color = vec4(0, 0, 0, 0);\n #if LAYERS == 1\n color = texture2D(detailMap0, uv0);\n #elif LAYERS == 2\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n #elif LAYERS == 3\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n color += texture2D(detailMap2, uv2) * w.b;\n #elif LAYERS == 4\n vec4 w = texture2D(weightMap, uvw);\n color += texture2D(detailMap0, uv0) * w.r;\n color += texture2D(detailMap1, uv1) * w.g;\n color += texture2D(detailMap2, uv2) * w.b;\n color += texture2D(detailMap3, uv3) * w.a;\n #else\n color = texture2D(detailMap0, uv0);\n #endif\n color.rgb *= diffuse;\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }\n` + }, + "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, + "defines": [ + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]}, + {"name":"LAYERS", "type":"number", "defines":[], "range":[0, 3]} + ], + "blocks": [ + {"name": "TexCoords", "defines": [], "binding": 0, "members": [ + {"name":"UVScale", "type":16, "count":1} + ]} + ], + "samplers": [ + {"name":"weightMap", "type":28, "count":1, "defines":[], "binding":30}, + {"name":"detailMap0", "type":28, "count":1, "defines":[], "binding":31}, + {"name":"detailMap1", "type":28, "count":1, "defines":[], "binding":32}, + {"name":"detailMap2", "type":28, "count":1, "defines":[], "binding":33}, + {"name":"detailMap3", "type":28, "count":1, "defines":[], "binding":34} + ], + "dependencies": {} + } + ] + }, { "name": "builtin-unlit", "techniques": [ @@ -289,6 +327,42 @@ export default [ } ] }, + { + "name": "editor/terrain-circle-brush", + "techniques": [ + {"name":"transparent", "passes":[{"blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"editor/terrain-circle-brush|terrain-brush-vs:vert|terrain-brush-fs:frag", "depthStencilState":{"depthTest":true, "depthWrite":false}, "properties":{"BrushPos":{"value":[0, 0, 0, 1], "type":16}, "BrushParams":{"value":[2.5, 2.5, 0, 0], "type":16}}}]} + ], + "shaders": [ + { + "name": "editor/terrain-circle-brush|terrain-brush-vs:vert|terrain-brush-fs:frag", + "hash": 3864386462, + "glsl3": { + "vert": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nuniform CCLocal {\n highp mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nin vec3 a_position;\nout vec4 wposition;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n wposition = cc_matWorld * pos;\n wposition.y += 0.01;\n pos = cc_matViewProj * wposition;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision mediump float;\nuniform CCGlobal {\n vec4 cc_time;\n vec4 cc_screenSize;\n vec4 cc_screenScale;\n vec4 cc_nativeSize;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos;\n vec4 cc_exposure;\n vec4 cc_mainLitDir;\n vec4 cc_mainLitColor;\n vec4 cc_ambientSky;\n vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nin vec4 wposition;\nuniform TexCoords {\n vec4 BrushPos;\n vec4 BrushParams;\n};\nvec4 frag () {\n float Radius = BrushParams.x;\n float Falloff = BrushParams.y;\n float Distance = length(wposition.xz - BrushPos.xz);\n float k = 0.0;\n #if LINEAR\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n #elif SMOOTH\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Distance - Radius) / Falloff;\n k = sqrt(1.0 - y * y);\n }\n #elif SPHERICAL\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n k = k*k*(3 - 2 * k);\n #elif TIP\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Falloff + Radius - Distance) / Falloff;\n k = 1.0 - sqrt(1.0 - y * y);\n }\n #endif\n vec4 color = vec4(0, 0, 0, 0);\n color.rgb = vec3(100, 100, 135) / 255.0;\n color.a = 0.85 * k;\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }\n` + }, + "glsl1": { + "vert": `\nprecision mediump float;\nuniform mat4 cc_matViewProj;\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nvarying vec4 wposition;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n wposition = cc_matWorld * pos;\n wposition.y += 0.01;\n pos = cc_matViewProj * wposition;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n`, + "frag": `\nprecision mediump float;\nuniform vec4 cc_exposure;\nvec3 SRGBToLinear(vec3 gamma)\n{\n return pow(gamma, vec3(2.2));\n}\nvec3 LinearToSRGB(vec3 linear)\n{\n return pow(linear, vec3(0.454545));\n}\nvec4 CCFragOutput(vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvarying vec4 wposition;\nuniform vec4 BrushPos;\nuniform vec4 BrushParams;\nvec4 frag () {\n float Radius = BrushParams.x;\n float Falloff = BrushParams.y;\n float Distance = length(wposition.xz - BrushPos.xz);\n float k = 0.0;\n #if LINEAR\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n #elif SMOOTH\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Distance - Radius) / Falloff;\n k = sqrt(1.0 - y * y);\n }\n #elif SPHERICAL\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n k = max(0.0, 1.0 - (Distance - Radius) / Falloff);\n }\n k = k*k*(3 - 2 * k);\n #elif TIP\n if (Distance <= Radius) {\n k = 1.0;\n }\n else if (Distance > Radius + Falloff) {\n k = 0.0;\n }\n else {\n float y = (Falloff + Radius - Distance) / Falloff;\n k = 1.0 - sqrt(1.0 - y * y);\n }\n #endif\n vec4 color = vec4(0, 0, 0, 0);\n color.rgb = vec3(100, 100, 135) / 255.0;\n color.a = 0.85 * k;\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }\n` + }, + "builtins": {"globals":{"blocks":[{"name":"CCGlobal", "defines":[]}], "samplers":[]}, "locals":{"blocks":[{"name":"CCLocal", "defines":[]}], "samplers":[]}}, + "defines": [ + {"name":"CC_USE_HDR", "type":"boolean", "defines":[]}, + {"name":"LINEAR", "type":"boolean", "defines":[]}, + {"name":"SMOOTH", "type":"boolean", "defines":[]}, + {"name":"SPHERICAL", "type":"boolean", "defines":[]}, + {"name":"TIP", "type":"boolean", "defines":[]} + ], + "blocks": [ + {"name": "TexCoords", "defines": [], "binding": 0, "members": [ + {"name":"BrushPos", "type":16, "count":1}, + {"name":"BrushParams", "type":16, "count":1} + ]} + ], + "samplers": [], + "dependencies": {} + } + ] + }, { "name": "pipeline/planar-shadow", "techniques": [ diff --git a/cocos/renderer/index.ts b/cocos/renderer/index.ts index f47f3b4246..0071da715d 100644 --- a/cocos/renderer/index.ts +++ b/cocos/renderer/index.ts @@ -14,6 +14,7 @@ export { samplerLib }; export { Light } from './scene/light'; export { Camera } from './scene/camera'; export { Model } from './scene/model'; +export { TerrainSample } from './terrain/terrain-sample'; export { default as ParticleBatchModel } from './models/particle-batch-model'; export { SkinningModel } from './models/skinning-model'; diff --git a/cocos/renderer/terrain/height-field.ts b/cocos/renderer/terrain/height-field.ts new file mode 100644 index 0000000000..be4914dbd4 --- /dev/null +++ b/cocos/renderer/terrain/height-field.ts @@ -0,0 +1,70 @@ +import { clamp } from '../../core/vmath'; + +export class HeightField +{ + data: Uint16Array = new Uint16Array; + w: number = 0; + h: number = 0; + + constructor(w: number, h: number) { + this.w = w; + this.h = h; + this.data = new Uint16Array(w * h); + + for (let i = 0; i < w * h; ++i) { + this.data[i] = 0; + } + } + + set(i: number, j: number, value: number) { + this.data[j * this.w + i] = value; + } + + get(i: number, j: number) { + return this.data[j * this.w + i]; + } + + getClamp(i: number, j: number) { + i = clamp(i, 0, this.w - 1); + j = clamp(j, 0, this.h - 1); + + return this.get(i, j); + } + + getAt(x: number, y: number) { + let fx = x / this.w; + let fy = y / this.h; + + let ix0 = Math.floor(fx); + let iz0 = Math.floor(fy); + let ix1 = ix0 + 1; + let iz1 = iz0 + 1; + let dx = fx - ix0; + let dz = fy - iz0; + + ix0 = clamp(ix0, 0, this.w - 1); + iz0 = clamp(iz0, 0, this.h - 1); + ix1 = clamp(ix1, 0, this.w - 1); + iz1 = clamp(iz1, 0, this.h - 1); + + let a = this.get(ix0, iz0); + let b = this.get(ix1, iz0); + let c = this.get(ix0, iz1); + let d = this.get(ix1, iz1); + let m = (b + c) * 0.5; + + if (dx + dz <= 1.0) { + d = m + (m - a); + } + else { + a = m + (m - d); + } + + let h1 = a * (1.0 - dx) + b * dx; + let h2 = c * (1.0 - dx) + d * dx; + + let h = h1 * (1.0 - dz) + h2 * dz; + + return h; + } +} \ No newline at end of file diff --git a/cocos/renderer/terrain/terrain-brush.ts b/cocos/renderer/terrain/terrain-brush.ts new file mode 100644 index 0000000000..976a1df5a8 --- /dev/null +++ b/cocos/renderer/terrain/terrain-brush.ts @@ -0,0 +1,182 @@ +import { Vec3, Vec4 } from "../../core"; +import { max } from "../../core/vmath/bits"; +import { Material } from '../../3d/assets/material'; +import { IDefineMap } from '../core/pass'; + +// TerrainBrush Interface +// +export class TerrainBrush +{ + material: Material|null = null; + position: Vec3 = new Vec3(0, 0, 0); + radius: number = 5; + strength: number = 1; + + getDelta(x: number, z: number) { + return 0; + } + + update(pos: Vec3) { + this.position = pos; + } +} + +// TerrainBrushData Interface +// +export class TerrainBrushData +{ + bmin: number[] = [0, 0]; + bmax: number[] = [0, 0]; + + width() { + return this.bmax[0] - this.bmax[0] + 1; + } + + height() { + return this.bmax[1] - this.bmax[1] + 1; + } +} + +// +export enum eTerrainCircleBrushType { + Linear, + Smooth, + Spherical, + Tip, +} + +export class TerrainCircleBrush extends TerrainBrush +{ + protected type: eTerrainCircleBrushType = eTerrainCircleBrushType.Linear; + protected falloff: number = 0.5; + + constructor() { + super(); + + this._updateMaterial(); + } + + setType(type: eTerrainCircleBrushType) { + if (this.type != type) { + this.type = type; + + this._updateMaterial(); + } + } + + getType() { + return this.type; + } + + _updateMaterial() { + let effect = cc.EffectAsset.get('editor/terrain-circle-brush'); + if (effect != null) { + this.material = new Material; + this.material.initialize({ + effectAsset: effect, + defines: this._getTypeDefine() + }); + } + } + + _getTypeDefine(): IDefineMap { + switch (this.type) { + case eTerrainCircleBrushType.Linear: + return { LINEAR: 1 }; + case eTerrainCircleBrushType.Smooth: + return { SMOOTH: 1 }; + case eTerrainCircleBrushType.Spherical: + return { SPHERICAL: 1 }; + case eTerrainCircleBrushType.Tip: + return { TIP: 1 }; + } + + return { LINEAR: 1 }; + } + + _calculateFalloff_Linear(Distance: number, Radius: number, Falloff: number) { + if (Distance <= Radius) { + return 1.0; + } + if (Distance > Radius + Falloff) { + return 0.0; + } + + return max(0.0, 1.0 - (Distance - Radius) / Falloff); + }; + + _calculateFalloff_Spherical(Distance: number, Radius: number, Falloff: number) { + let y = this._calculateFalloff_Linear(Distance, Radius, Falloff); + + return y*y*(3 - 2 * y); + }; + + _calculateFalloff_Smooth(Distance: number, Radius: number, Falloff: number) { + if (Distance <= Radius) { + return 1.0; + } + if (Distance > Radius + Falloff) { + return 0.0; + } + + let y = (Distance - Radius) / Falloff; + + return Math.sqrt(1.0 - y * y); + } + + _calculateFalloff_Tip(Distance: number, Radius: number, Falloff: number) { + if (Distance <= Radius) { + return 1.0; + } + if (Distance > Radius + Falloff) { + return 0.0; + } + + let y = (Falloff + Radius - Distance) / Falloff; + + return 1.0 - Math.sqrt(1.0 - y * y); + } + + getDelta(x: number, z: number) { + let DetlaX = x - this.position.x, DeltaZ = z - this.position.z; + let Distance = Math.sqrt(DetlaX * DetlaX + DeltaZ * DeltaZ); + let Radius = (1.0 - this.falloff) * this.radius; + let Falloff = this.falloff * this.radius; + + let k = 0; + switch (this.type) { + case eTerrainCircleBrushType.Linear: + k = this._calculateFalloff_Linear(Distance, Radius, Falloff); + break; + case eTerrainCircleBrushType.Smooth: + k = this._calculateFalloff_Smooth(Distance, Radius, Falloff); + break; + case eTerrainCircleBrushType.Spherical: + k = this._calculateFalloff_Spherical(Distance, Radius, Falloff); + break; + case eTerrainCircleBrushType.Tip: + k = this._calculateFalloff_Tip(Distance, Radius, Falloff); + break; + } + + return k * this.strength; + } + + update(pos: Vec3) { + super.update(pos); + + if (this.material != null) { + let Radius = (1.0 - this.falloff) * this.radius; + let Falloff = this.falloff * this.radius; + + let BrushPos = pos; + let BrushParams = new Vec4; + + BrushParams.x = Radius; + BrushParams.y = Falloff; + + this.material.setProperty("BrushPos", BrushPos); + this.material.setProperty("BrushParams", BrushParams); + } + } +} \ No newline at end of file diff --git a/cocos/renderer/terrain/terrain-editor-manage.ts b/cocos/renderer/terrain/terrain-editor-manage.ts new file mode 100644 index 0000000000..5dcf952a88 --- /dev/null +++ b/cocos/renderer/terrain/terrain-editor-manage.ts @@ -0,0 +1,7 @@ +import { TerrainEditor_Mode } from './terrain-editor-mode' + +// 管理模式 +// +export class TerrainEditor_Manage extends TerrainEditor_Mode +{ +} diff --git a/cocos/renderer/terrain/terrain-editor-mode.ts b/cocos/renderer/terrain/terrain-editor-mode.ts new file mode 100644 index 0000000000..83e87e3c2f --- /dev/null +++ b/cocos/renderer/terrain/terrain-editor-mode.ts @@ -0,0 +1,15 @@ +import { Terrain, TERRAIN_BLOCK_TILE_COMPLEXITY } from './terrain' + +export enum eTerrainEditorMode +{ + MANAGE, + SCULPT, + PAINT, +} + +export class TerrainEditor_Mode +{ + onUpdate(terrain: Terrain, dtime: number) { + } +} + diff --git a/cocos/renderer/terrain/terrain-editor-paint.ts b/cocos/renderer/terrain/terrain-editor-paint.ts new file mode 100644 index 0000000000..47897611b4 --- /dev/null +++ b/cocos/renderer/terrain/terrain-editor-paint.ts @@ -0,0 +1,176 @@ +import { TerrainEditor_Mode } from './terrain-editor-mode' +import { Terrain, TERRAIN_BLOCK_TILE_COMPLEXITY } from './terrain' +import { Vec3, Rect } from '../../core/value-types'; +import { clamp } from '../../core/vmath'; +import { TerrainBrush, TerrainCircleBrush } from './terrain-brush'; +import { TerrainWeightOperation, TerrainWeightUndoRedo } from './terrain-operation'; + +export class TerrainEditor_Paint extends TerrainEditor_Mode +{ + _brush: TerrainBrush = new TerrainCircleBrush; + _undo: TerrainWeightUndoRedo|null = null; + _currentLayer: number = -1; + + onUpdate(terrain: Terrain, dtime: number) { + if (this._undo != null) { + this._updateWeight(terrain, dtime); + } + } + + onUpdateBrushPosition(terrain: Terrain, pos: Vec3) { + this._brush.update(pos); + + let blocks = terrain.getBlocks(); + for (let i = 0; i < blocks.length; ++i) { + let block = blocks[i]; + let index = block.getIndex(); + + let bound = new Rect; + bound.x = index[0] * terrain.info.tileSize; + bound.y = index[1] * terrain.info.tileSize; + bound.width = TERRAIN_BLOCK_TILE_COMPLEXITY * terrain.info.tileSize; + bound.height = TERRAIN_BLOCK_TILE_COMPLEXITY * terrain.info.tileSize; + + let brushRect = new Rect; + brushRect.x = this._brush.position.x - this._brush.radius; + brushRect.y = this._brush.position.z - this._brush.radius; + brushRect.width = this._brush.radius * 2; + brushRect.height = this._brush.radius * 2; + + if (bound.intersects(brushRect)) { + block.setBrushMaterial(this._brush.material); + } + else { + block.setBrushMaterial(null); + } + } + } + + onMouseDown() + { + if (this._currentLayer == -1) { + return; + } + + this._undo = new TerrainWeightUndoRedo; + } + + onMouseUp() + { + this._undo = null; + } + + _updateWeight(terrain: Terrain, dtime: number) + { + let uWeigthComplexity = terrain.info.weightMapSize * terrain.info.blockCount[0]; + let vWeigthComplexity = terrain.info.weightMapSize * terrain.info.blockCount[1]; + if (uWeigthComplexity == 0 || vWeigthComplexity == 0) { + return ; + } + + let x1 = this._brush.position.x - this._brush.radius; + let y1 = this._brush.position.z - this._brush.radius; + let x2 = this._brush.position.x + this._brush.radius; + let y2 = this._brush.position.z + this._brush.radius; + + x1 /= terrain.info.size[0]; + y1 /= terrain.info.size[1]; + x2 /= terrain.info.size[0]; + y2 /= terrain.info.size[1]; + + x1 *= uWeigthComplexity - 1; + y1 *= vWeigthComplexity - 1; + x2 *= uWeigthComplexity - 1; + y2 *= vWeigthComplexity - 1; + + x1 = Math.floor(x1); + y1 = Math.floor(y1); + x2 = Math.floor(x2); + y2 = Math.floor(y2); + + if (x1 > uWeigthComplexity - 1 || x2 < 0) + return; + if (y1 > vWeigthComplexity - 1 || y2 < 0) + return; + + x1 = clamp(x1, 0, uWeigthComplexity - 1); + y1 = clamp(y1, 0, vWeigthComplexity - 1); + x2 = clamp(x2, 0, uWeigthComplexity - 1); + y2 = clamp(y2, 0, vWeigthComplexity - 1); + + let op = new TerrainWeightOperation; + for (let y = y1; y <= y2; ++y) { + for (let x = x1; x <= x2; ++x) { + let w = terrain.getWeight(x, y); + let bx = Math.floor(x / terrain.info.weightMapSize); + let by = Math.floor(y / terrain.info.weightMapSize); + let block = terrain.getBlock(bx, by); + let layers = [block.getLayer(0), block.getLayer(1), block.getLayer(2), block.getLayer(3)]; + + let xpos = x / (uWeigthComplexity - 1) * terrain.info.size[0]; + let ypos = y / (vWeigthComplexity - 1) * terrain.info.size[1]; + let delta = this._brush.getDelta(xpos, ypos) * dtime; + + if (delta == 0) { + continue; + } + + if (layers[0] == this._currentLayer) { + w.x += delta; + } + else if (layers[1] == this._currentLayer) { + w.y += delta; + } + else if (layers[2] == this._currentLayer) { + w.z += delta; + } + else if (layers[3] == this._currentLayer) { + w.w += delta; + } + else { + if (layers[0] == -1) { + block.setLayer(0, this._currentLayer); + w.x += delta; + } + else if (layers[1] == -1) { + block.setLayer(1, this._currentLayer); + w.y += delta; + } + else if (layers[3] == -1) { + block.setLayer(2, this._currentLayer); + w.z += delta; + } + else if (layers[4] == -1) { + block.setLayer(3, this._currentLayer); + w.w += delta; + } + else { + continue; + } + } + + let sum = w.x + w.y + w.z + w.w; + if (sum > 0) { + w.multiply(1.0 / sum); + } + + if (this._undo != null) { + this._undo.push(x, y, terrain.getWeight(x, y)); + this._undo.pushBlock(block, layers); + } + + op.push(x, y, w); + } + } + + op.apply(terrain); + } + + setCurrentLayer(layer: number) { + this._currentLayer = layer; + } + + getCurrentLayer() { + return this._currentLayer; + } +} diff --git a/cocos/renderer/terrain/terrain-editor-sculpt.ts b/cocos/renderer/terrain/terrain-editor-sculpt.ts new file mode 100644 index 0000000000..57b637ab21 --- /dev/null +++ b/cocos/renderer/terrain/terrain-editor-sculpt.ts @@ -0,0 +1,112 @@ +import { TerrainEditor_Mode } from './terrain-editor-mode' +import { Terrain, TERRAIN_BLOCK_TILE_COMPLEXITY } from './terrain' +import { Vec3, Rect } from '../../core/value-types'; +import { clamp } from '../../core/vmath'; +import { TerrainBrush, TerrainCircleBrush } from './terrain-brush'; +import { TerrainHeightOperation, TerrainHeightUndoRedo } from './terrain-operation'; + +export class TerrainEditor_Sculpt extends TerrainEditor_Mode +{ + _brush: TerrainBrush = new TerrainCircleBrush; + _undo: TerrainHeightUndoRedo|null = null; + + onUpdate(terrain: Terrain, dtime: number) { + if (this._undo != null) { + this._updateHeight(terrain, dtime, false); + } + } + + onUpdateBrushPosition(terrain: Terrain, pos: Vec3) { + this._brush.update(pos); + + let blocks = terrain.getBlocks(); + for (let i = 0; i < blocks.length; ++i) { + let block = blocks[i]; + let index = block.getIndex(); + + let bound = new Rect; + bound.x = index[0] * terrain.info.tileSize; + bound.y = index[1] * terrain.info.tileSize; + bound.width = TERRAIN_BLOCK_TILE_COMPLEXITY * terrain.info.tileSize; + bound.height = TERRAIN_BLOCK_TILE_COMPLEXITY * terrain.info.tileSize; + + let brushRect = new Rect; + brushRect.x = this._brush.position.x - this._brush.radius; + brushRect.y = this._brush.position.z - this._brush.radius; + brushRect.width = this._brush.radius * 2; + brushRect.height = this._brush.radius * 2; + + if (bound.intersects(brushRect)) { + block.setBrushMaterial(this._brush.material); + } + else { + block.setBrushMaterial(null); + } + } + } + + onMouseDown() + { + this._undo = new TerrainHeightUndoRedo; + } + + onMouseUp() + { + this._undo = null; + } + + _updateHeight(terrain: Terrain, dtime: number, shift_pressed: boolean) + { + let x1 = this._brush.position.x - this._brush.radius; + let y1 = this._brush.position.z - this._brush.radius; + let x2 = this._brush.position.x + this._brush.radius; + let y2 = this._brush.position.z + this._brush.radius; + + x1 /= terrain.info.tileSize; + y1 /= terrain.info.tileSize; + x2 /= terrain.info.tileSize; + y2 /= terrain.info.tileSize; + + x1 = Math.floor(x1); + y1 = Math.floor(y1); + x2 = Math.floor(x2); + y2 = Math.floor(y2); + + if (x1 > terrain.info.vertexCount[0] - 1 || x2 < 0) + return; + if (y1 > terrain.info.vertexCount[1] - 1 || y2 < 0) + return; + + x1 = clamp(x1, 0, terrain.info.vertexCount[0] - 1); + y1 = clamp(y1, 0, terrain.info.vertexCount[1] - 1); + x2 = clamp(x2, 0, terrain.info.vertexCount[0] - 1); + y2 = clamp(y2, 0, terrain.info.vertexCount[1] - 1); + + let op = new TerrainHeightOperation; + for (let y = y1; y <= y2; ++y) { + for (let x = x1; x <= x2; ++x) { + let h = terrain.getHeight(x, y); + + if (this._undo != null) { + this._undo.push(x, y, h); + } + + let xpos = x * terrain.info.tileSize; + let ypos = y * terrain.info.tileSize; + let delta = this._brush.getDelta(xpos, ypos) * dtime; + + if (!shift_pressed) { + h += delta; + } + else { + h -= delta; + } + + op.push(x, y, h); + } + } + + op.apply(terrain); + } + +} diff --git a/cocos/renderer/terrain/terrain-editor.ts b/cocos/renderer/terrain/terrain-editor.ts new file mode 100644 index 0000000000..2d5e2378af --- /dev/null +++ b/cocos/renderer/terrain/terrain-editor.ts @@ -0,0 +1,143 @@ +import { TerrainEditor_Mode, eTerrainEditorMode} from './terrain-editor-mode' +import { TerrainEditor_Manage } from './terrain-editor-manage' +import { TerrainEditor_Sculpt } from './terrain-editor-sculpt' +import { TerrainEditor_Paint } from './terrain-editor-paint' +import { Terrain } from './terrain' +import { Node } from '../../scene-graph/node'; +import { CameraComponent } from '../../3d/framework'; + +export class TerrainEditor +{ + static Instance: TerrainEditor; + + _terrain: Terrain|null = null; + _modes: Array = [ + new TerrainEditor_Manage, + new TerrainEditor_Sculpt, + new TerrainEditor_Paint, + ]; + + _currentMode: TerrainEditor_Mode | null = null; + + constructor() { + TerrainEditor.Instance = this; + + this.setMode(eTerrainEditorMode.SCULPT); + } + + setEditTerrain(t: Terrain) { + this._terrain = t; + } + + setMode(mode: eTerrainEditorMode) { + let m = this._modes[mode]; + + this._currentMode = m; + } + + getMode(mode: eTerrainEditorMode) { + return this._modes[mode]; + } + + getCurrentMode() { + return this._currentMode; + } + + getCurrentModeType() { + if (this._currentMode == this._modes[0]) { + return eTerrainEditorMode.MANAGE; + } + else if (this._currentMode == this._modes[1]) { + return eTerrainEditorMode.SCULPT; + } + else if (this._currentMode == this._modes[2]) { + return eTerrainEditorMode.PAINT; + } + + return eTerrainEditorMode.SCULPT; + } + + setCurrentLayer(id: number) { + let paintMode = this.getMode(eTerrainEditorMode.PAINT) as TerrainEditor_Paint; + + paintMode.setCurrentLayer(id); + } + + update(dtime: number) { + if (this._currentMode == null || this._terrain == null) { + return; + } + + this._currentMode.onUpdate(this._terrain, dtime); + } + + onMouseDown(id: number, x: number, y: number) { + if (this._terrain == null) { + return; + } + + let sculptMode = this.getMode(eTerrainEditorMode.SCULPT) as TerrainEditor_Sculpt; + let paintMode = this.getMode(eTerrainEditorMode.PAINT) as TerrainEditor_Paint; + + if (this._currentMode == sculptMode) { + sculptMode.onMouseDown(); + } + else if (this._currentMode == paintMode) { + paintMode.onMouseDown(); + } + } + + onMouseUp(id: number, x: number, y: number) { + if (this._terrain == null) { + return; + } + + let sculptMode = this.getMode(eTerrainEditorMode.SCULPT) as TerrainEditor_Sculpt; + let paintMode = this.getMode(eTerrainEditorMode.PAINT) as TerrainEditor_Paint; + + if (this._currentMode == sculptMode) { + sculptMode.onMouseUp(); + } + else if (this._currentMode == paintMode) { + paintMode.onMouseUp(); + } + } + + onMouseMove(camera: Node, x: number, y: number) { + if (this._terrain == null) { + return; + } + + const scene = this._terrain.node.scene; + if (camera != null) { + const cameraComponent = camera.getComponent(CameraComponent); + if (cameraComponent == null) { + return; + } + + const from = camera.getPosition(); + const to = new cc.vmath.vec3(); + + cameraComponent.screenToWorld(new cc.vmath.vec3(x, y, 0), to); + + const dir = new cc.Vec3(); + cc.vmath.vec3.subtract(dir, to, from); + cc.vmath.vec3.normalize(dir, dir); + + let vhit = this._terrain.rayCheck(from, dir, 0.1); + if (vhit == null) { + return ; + } + + let sculptMode = this.getMode(eTerrainEditorMode.SCULPT) as TerrainEditor_Sculpt; + let paintMode = this.getMode(eTerrainEditorMode.PAINT) as TerrainEditor_Paint; + + if (this._currentMode == sculptMode) { + sculptMode.onUpdateBrushPosition(this._terrain, vhit); + } + else if (this._currentMode == paintMode) { + paintMode.onUpdateBrushPosition(this._terrain, vhit); + } + } + } +} \ No newline at end of file diff --git a/cocos/renderer/terrain/terrain-operation.ts b/cocos/renderer/terrain/terrain-operation.ts new file mode 100644 index 0000000000..4fd725ae3d --- /dev/null +++ b/cocos/renderer/terrain/terrain-operation.ts @@ -0,0 +1,193 @@ +import { TerrainBlock, Terrain } from './terrain' +import { Vec2, Vec4, Rect } from '../../core/value-types'; + +export class TerrainHeightData +{ + x: number = 0; + y: number = 0; + value: number = 0; +} + +export class TerrainHeightOperation +{ + data: Array = new Array(); + + static addChangeList(changelist: Array, block: TerrainBlock) { + for (let i = 0; i < changelist.length; ++i) { + if (changelist[i] == block) { + return; + } + } + + changelist.push(block); + } + + push(x: number, y: number, value: number) { + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].x == x && this.data[i].y == y) { + return ; + } + } + + let point = new TerrainHeightData; + point.x = x; + point.y = y; + point.value = value; + this.data.push(point); + } + + apply(terrain: Terrain) { + // update data + for (let i = 0; i < this.data.length; ++i) { + let p = this.data[i]; + + terrain.setHeight(p.x, p.y, p.value); + } + + // update normal + for (let i = 0; i < this.data.length; ++i) { + let p = this.data[i]; + let n = terrain._calcuNormal(p.x, p.y); + + terrain._setNormal(p.x, p.y, n); + } + + // update block + let changelist = new Array(); + + for (let i = 0; i < terrain.getBlocks().length; ++i) { + let block = terrain.getBlocks()[i]; + let rect = block.getRect(); + + for (let j = 0; j < this.data.length; ++j) { + let p = this.data[j]; + if (!rect.contains(new Vec2(p.x, p.y))) + continue; + + TerrainHeightOperation.addChangeList(changelist, block); + } + } + + for (let i = 0; i < changelist.length; ++i) { + changelist[i]._updateHeight(); + } + } +} + +// +export class TerrainHeightUndoRedo extends TerrainHeightOperation +{ +} + +// +export class TerrainWeightData +{ + x: number = 0; + y: number = 0; + value: Vec4 = new Vec4; +} + +export class TerrainWeightOperation +{ + data: Array = new Array(); + + static addChangeList(changelist: Array, block: TerrainBlock) { + for (let i = 0; i < changelist.length; ++i) { + if (changelist[i] == block) { + return; + } + } + + changelist.push(block); + } + + push(x: number, y: number, value: Vec4) { + for (let i = 0; i < this.data.length; ++i) { + if (this.data[i].x == x && this.data[i].y == y) { + return ; + } + } + + let point = new TerrainWeightData; + point.x = x; + point.y = y; + point.value = value; + this.data.push(point); + } + + apply(terrain: Terrain) { + // update data + for (let i = 0; i < this.data.length; ++i) { + let p = this.data[i]; + + terrain.setWeight(p.x, p.y, p.value); + } + + // update block + let changelist = new Array(); + + for (let i = 0; i < terrain.getBlocks().length; ++i) { + let block = terrain.getBlocks()[i]; + + let rect = new Rect; + rect.x = block.getIndex()[0] * terrain.info.weightMapSize; + rect.y = block.getIndex()[1] * terrain.info.weightMapSize; + rect.width = terrain.info.weightMapSize; + rect.height = terrain.info.weightMapSize; + + for (let j = 0; j < this.data.length; ++j) { + let p = this.data[j]; + if (!rect.contains(new Vec2(p.x, p.y))) + continue; + + TerrainWeightOperation.addChangeList(changelist, block); + } + } + + for (let i = 0; i < changelist.length; ++i) { + changelist[i]._updateWeightMap(); + } + } +} + +export class TerrainBlockLayerData +{ + block: TerrainBlock; + layers: number[] + + constructor(block: TerrainBlock, layers: number[]) + { + this.block = block; + this.layers = layers; + } +} + +export class TerrainWeightUndoRedo extends TerrainWeightOperation +{ + blockLayers: Array = new Array(); + + pushBlock(block: TerrainBlock, layers: number[]) + { + for (let i = 0; i < this.blockLayers.length; ++i) { + if (this.blockLayers[i].block == block) { + return; + } + } + + this.blockLayers.push(new TerrainBlockLayerData(block, layers)); + } + + apply(terrain: Terrain) { + super.apply(terrain); + + for (let i = 0; i < this.blockLayers.length; ++i) { + let block = this.blockLayers[i].block; + let layers = this.blockLayers[i].layers; + + block.setLayer(0, layers[0]); + block.setLayer(1, layers[1]); + block.setLayer(2, layers[2]); + block.setLayer(3, layers[3]); + } + } +} \ No newline at end of file diff --git a/cocos/renderer/terrain/terrain-sample.ts b/cocos/renderer/terrain/terrain-sample.ts new file mode 100644 index 0000000000..c1fb2db874 --- /dev/null +++ b/cocos/renderer/terrain/terrain-sample.ts @@ -0,0 +1,185 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import { Terrain, TerrainInfo, TerrainLayer } from './terrain' +import { Scene } from '../../scene-graph/scene'; +import { Node } from '../../scene-graph/node'; +import { Texture2D } from '../../assets'; +import { TerrainEditor } from './terrain-editor'; +import { eTerrainEditorMode} from './terrain-editor-mode' +import { TerrainEditor_Manage } from './terrain-editor-manage' +import { TerrainEditor_Sculpt } from './terrain-editor-sculpt' +import { TerrainEditor_Paint } from './terrain-editor-paint' + +export class TerrainSample +{ + terrain: Terrain|null = null; + editor: TerrainEditor|null = null; + camera: Node|null = null; + + onInit(scene: Scene) { + console.log("TerrainSample::onInit1"); + + let info = new TerrainInfo; + info.tileSize = 1; + info.blockCount[0] = 1; + info.blockCount[1] = 1; + + let _node = new Node('Terrain'); + _node.setParent(scene); + + this.terrain = _node.addComponent(Terrain); + if (this.terrain != null) { + // build terrain + this.terrain.build(info); + + this.editor = new TerrainEditor; + this.editor.setEditTerrain(this.terrain as Terrain); + + // load layer + cc.loader.loadRes("decal_1/texture", Texture2D, (err, asset) => { + let layer = new TerrainLayer; + layer.detailMap = asset; + layer.tileSize = 8.0; + + if (this.terrain != null) { + this.terrain.addLayer(layer); + } + }); + + cc.loader.loadRes("decal_2/texture", Texture2D, (err, asset) => { + let layer = new TerrainLayer; + layer.detailMap = asset; + layer.tileSize = 8.0; + + if (this.terrain != null) { + this.terrain.addLayer(layer); + } + }); + + let paintMode = this.editor.getMode(eTerrainEditorMode.PAINT) as TerrainEditor_Paint; + + paintMode.setCurrentLayer(0); + } + + this.camera = scene.getChildByName("Camera"); + if (this.camera == null) { + console.log('Camera is null'); + } + } + + onUpdate(dtime: number) { + if (this.editor != null) { + this.editor.update(dtime); + } + } + + onKeyDown(id: number) { + if (this.terrain == null || this.editor == null) { + return; + } + + let mode = this.editor.getCurrentModeType(); + if (id == cc.macro.KEY.tab) { + // change editor mode + if (mode == eTerrainEditorMode.MANAGE) { + this.editor.setMode(eTerrainEditorMode.SCULPT); + } + else if (mode == eTerrainEditorMode.SCULPT) { + this.editor.setMode(eTerrainEditorMode.PAINT); + } + else if (mode == eTerrainEditorMode.PAINT) { + this.editor.setMode(eTerrainEditorMode.SCULPT); + } + } + else if (mode == eTerrainEditorMode.MANAGE) { + if (id == cc.macro.KEY[1]) { + this.onRebuildHeight(); + } + else if (id== cc.macro.KEY[2]) { + this.onRebuildBlock(); + } + } + else if (mode == eTerrainEditorMode.SCULPT) { + } + else if (mode == eTerrainEditorMode.PAINT) { + // change current layer + if (id == cc.macro.KEY[1]) { + this.editor.setCurrentLayer(0); + } + else if (id== cc.macro.KEY[2]) { + this.editor.setCurrentLayer(1); + } + } + } + + onMouseDown(id: number, x: number, y: number) { + this.editor!.onMouseDown(id, x, y); + } + + onMouseUp(id: number, x: number, y: number) { + this.editor!.onMouseUp(id, x, y); + } + + onMouseMove(x: number, y: number) { + if (this.editor == null || this.camera == null) { + return; + } + + this.editor.onMouseMove(this.camera, x, y); + } + + onRebuildHeight() { + if (this.terrain == null || this.editor == null) { + return; + } + + let info = new TerrainInfo; + info.tileSize = this.terrain.info.tileSize * 2; + info.blockCount[0] = this.terrain.info.blockCount[0]; + info.blockCount[1] = this.terrain.info.blockCount[1]; + info.weightMapSize = this.terrain.info.weightMapSize; + info.lightMapSize = this.terrain.info.lightMapSize; + this.terrain!.rebuild(info); + + if (this.camera != null) { + let pos = this.camera.getPosition(); + pos.x = info.size[0] / 2; + + this.camera.setPosition(pos); + } + } + + onRebuildBlock() { + if (this.terrain == null || this.editor == null) { + return; + } + + let info = new TerrainInfo; + info.tileSize = this.terrain.info.tileSize; + info.blockCount[0] = this.terrain.info.blockCount[0] + 1; + info.blockCount[1] = this.terrain.info.blockCount[1] + 1; + info.weightMapSize = this.terrain.info.weightMapSize; + info.lightMapSize = this.terrain.info.lightMapSize; + this.terrain.rebuild(info); + + if (this.camera != null) { + let pos = this.camera.getPosition(); + pos.x = info.size[0] / 2; + + this.camera.setPosition(pos); + } + } + + onRebuildWeight() { + if (this.terrain == null || this.editor == null) { + return; + } + + let info = new TerrainInfo; + info.tileSize = this.terrain.info.tileSize; + info.blockCount[0] = this.terrain.info.blockCount[0]; + info.blockCount[1] = this.terrain.info.blockCount[1]; + info.weightMapSize = 256; + info.lightMapSize = this.terrain.info.lightMapSize; + this.terrain.rebuild(info); + } +} diff --git a/cocos/renderer/terrain/terrain.ts b/cocos/renderer/terrain/terrain.ts new file mode 100644 index 0000000000..cc0ccbf115 --- /dev/null +++ b/cocos/renderer/terrain/terrain.ts @@ -0,0 +1,1254 @@ + +import { Vec3, Vec4, Vec2, Rect } from '../../core/value-types'; +import { clamp, vec3, vec4 } from '../../core/vmath'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXDevice } from '../../gfx/device'; +import { GFXInputAssembler, IGFXInputAssemblerInfo, IGFXAttribute } from '../../gfx/input-assembler'; +import { GFXBufferUsageBit, GFXAttributeName, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; +import { Material } from '../../3d/assets/material'; +import { Model } from '../../renderer/scene/model' +import { HeightField } from './height-field' +import { Node } from '../../scene-graph/node'; +import { Scene } from '../../scene-graph/scene'; +import { Texture2D } from '../../assets'; +import { Filter, PixelFormat, WrapMode } from '../../assets/asset-enum'; +import { EffectAsset } from '../../3d/assets/effect-asset'; +import { IDefineMap } from '../core/pass'; +import { Component } from '../../components'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { RenderableComponent } from '../../3d/framework/renderable-component'; +import { builtinResMgr } from '../../3d/builtin'; + +export const TERRAIN_MAX_LEVELS = 4; +export const TERRAIN_MAX_BLEND_LAYERS = 4; +export const TERRAIN_MAX_LAYER_COUNT = 256; +export const TERRAIN_BLOCK_TILE_COMPLEXITY = 32; +export const TERRAIN_BLOCK_VERTEX_COMPLEXITY = 33; +export const TERRAIN_BLOCK_VERTEX_SIZE = 8; // position + normal + uv +export const TERRAIN_NORTH_INDEX = 0; +export const TERRAIN_SOUTH_INDEX = 1; +export const TERRAIN_WEST_INDEX = 2; +export const TERRAIN_EAST_INDEX = 3; + +/** + * 地形信息。 + */ +@ccclass('cc.TerrainInfo') +export class TerrainInfo +{ + @property({ + visible : false + }) + tileSize: number = 1; + + @property({ + visible : false + }) + blockCount: number[] = [1, 1]; + + @property({ + visible : false + }) + weightMapSize: number = 128; + + @property({ + visible : false + }) + lightMapSize: number = 128; + + @property({ + visible : false + }) + effect: EffectAsset|null = cc.EffectAsset.get('builtin-terrain'); + + @property({ + visible : false + }) + DefaultLayerTex: Texture2D|null = cc.builtinResMgr.get('default-texture'); + + // + protected _tileCount: number[] = [0, 0]; + protected _vertexCount: number[] = [0, 0]; + protected _size: number[] = [0, 0]; + + initialize() { + this._tileCount[0] = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY; + this._tileCount[1] = this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY; + this._vertexCount[0] = this._tileCount[0] + 1; + this._vertexCount[1] = this._tileCount[1] + 1; + this._size[0] = this._tileCount[0] * this.tileSize; + this._size[1] = this._tileCount[1] * this.tileSize; + } + + get tileCount() { + return this._tileCount; + } + + get vertexCount() { + return this._vertexCount; + } + + get size() { + return this._size; + } +} + +@ccclass('cc.TerrainLayer') +export class TerrainLayer +{ + @property + detailMap: Texture2D|null = null; + @property + tileSize: number = 1; +} + +export class TerrainVertex +{ + position: Vec3 = new Vec3(0, 0, 0); + normal: Vec3 = new Vec3(0, 1, 0); + uv: Vec2 = new Vec2(0, 0); +} + +export class TerrainRenderable extends RenderableComponent { + _model: Model | null = null; + _meshData: IRenderingSubmesh | null = null; + + _brushMaterial: Material | null = null; + _currentMaterial: Material | null = null; + _currentMaterialLayers: number = 0; + + public destroy () { + this._invalidMaterial(); + if (this._model != null) { + this._getRenderScene().destroyModel(this._model); + this._model = null; + } + + super.destroy(); + } + + private _getBuiltinMaterial () { + return builtinResMgr.get('missing-material'); + } + + public _onMaterialModified (idx: number, mtl: Material | null) { + if (this._model == null) { + return; + } + this._onRebuildPSO(idx, mtl || this._getBuiltinMaterial()); + } + + protected _onRebuildPSO (idx: number, material: Material) { + if (this._model) { + this._model.setSubModelMaterial(idx, material); + } + } + + protected _clearMaterials () { + if (this._model == null) { + return; + } + + this._onMaterialModified(0, null); + } + + _invalidMaterial() { + if (this._currentMaterial == null) { + return; + } + + this._clearMaterials(); + + this._currentMaterial = null; + if (this._model != null) { + this._model.enabled = false; + } + } + + _updateBrushMaterial() { + if (this._currentMaterial == null || this._brushMaterial == null) { + return; + } + + let passes = this._currentMaterial.passes; + + passes.push(this._brushMaterial.passes[0]); + + //this._currentMaterial = this._brushMaterial; + } + + _updateMaterial(block: TerrainBlock, init: boolean) { + if (this._meshData == null || block._terrain.info.effect == null) { + return; + } + + let nlayers = block.getMaxLayer(); + if (this._currentMaterial == null || nlayers != this._currentMaterialLayers) { + if (this._model != null) { + this._currentMaterial = new Material; + + this._currentMaterial.initialize({ + effectAsset: block._terrain.info.effect, + defines: block._getMaterialDefines(nlayers) + }); + + this._updateBrushMaterial(); + + if (init) { + this._model.initSubModel(0, this._meshData, this._currentMaterial); + } + + this.setMaterial(this._currentMaterial, 0); + this._currentMaterialLayers = nlayers; + this._model.enabled = true; + } + } + } +} + +export class TerrainBlock +{ + _terrain: Terrain; + _node: Node; + _renderable: TerrainRenderable; + + _index: number[] = [1, 1]; + _neighbor: TerrainBlock|null[] = [null, null, null, null]; + _layers: number[] = [-1, -1, -1, -1]; + _weightMap: Texture2D | null = null; + + constructor(t: Terrain, i: number, j: number) { + this._terrain = t; + this._index[0] = i; + this._index[1] = j; + + this._node = new Node(''); + this._node.setParent(this._terrain.node); + + this._renderable = this._node.addComponent(TerrainRenderable) as TerrainRenderable; + } + + build() { + const gfxDevice = cc.director.root.device as GFXDevice; + + // vertex buffer + let vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY); + + let index = 0; + for (let j = 0; j < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++j) { + for (let i = 0; i < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++i) { + let x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + i; + let y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + j; + + let position = this._terrain.getPosition(x, y); + let normal = this._terrain.getNormal(x, y); + let uv = new Vec2(i / TERRAIN_BLOCK_VERTEX_COMPLEXITY, j / TERRAIN_BLOCK_VERTEX_COMPLEXITY); + + vertexData[index++] = position.x; + vertexData[index++] = position.y; + vertexData[index++] = position.z; + vertexData[index++] = normal.x; + vertexData[index++] = normal.y; + vertexData[index++] = normal.z; + vertexData[index++] = uv.x; + vertexData[index++] = uv.y; + } + } + + const vertexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: TERRAIN_BLOCK_VERTEX_SIZE * Float32Array.BYTES_PER_ELEMENT * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY, + stride: TERRAIN_BLOCK_VERTEX_SIZE * Float32Array.BYTES_PER_ELEMENT, + }); + vertexBuffer.update(vertexData); + + // index buffer + const indexBuffer = this._terrain.getSharedIndexBuffer(); + + // + const gfxAttributes: IGFXAttribute[] = [ + { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, + { name: GFXAttributeName.ATTR_NORMAL, format: GFXFormat.RGB32F }, + { name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RG32F} + ]; + + this._renderable._meshData = { + attributes: gfxAttributes, + vertexBuffers: [vertexBuffer], + indexBuffer : indexBuffer, + primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST, + }; + + this._renderable._model = this._renderable._getRenderScene().createModel(Model, this._node); + + // + this._updateWeightMap(); + + // + this._updateMaterial(true); + } + + rebuild() { + this._updateHeight(); + this._updateWeightMap(); + + this._renderable._invalidMaterial(); + this._updateMaterial(false); + } + + destroy() { + if (this._renderable != null) { + this._renderable.destroy(); + } + if (this._node != null) { + this._node.destroy(); + } + if (this._weightMap != null) { + this._weightMap.destroy(); + } + } + + update(dtime: number) { + this._updateMaterial(false); + + let mtl = this._renderable._currentMaterial; + if (mtl != null) { + let nlayers = this.getMaxLayer(); + let uvScale = new Vec4(1, 1, 1, 1); + + if (nlayers == 0) { + if (this._layers[0] != -1) { + let l0 = this._terrain.getLayer(this._layers[0]); + + if (l0 != null) { + uvScale.x = 1.0 / l0.tileSize; + } + + mtl.setProperty('detailMap0', l0 != null ? l0.detailMap : null); + } + else { + mtl.setProperty('detailMap0', this._terrain.info.DefaultLayerTex); + } + } + else if (nlayers == 1) { + let l0 = this._terrain.getLayer(this._layers[0]); + let l1 = this._terrain.getLayer(this._layers[1]); + + if (l0 != null) { + uvScale.x = 1.0 / l0.tileSize; + } + if (l1 != null) { + uvScale.y = 1.0 / l1.tileSize; + } + + mtl.setProperty('weightMap', this._weightMap); + mtl.setProperty('detailMap0', l0 != null ? l0.detailMap : null); + mtl.setProperty('detailMap1', l1 != null ? l1.detailMap : null); + } + else if (nlayers == 2) { + let l0 = this._terrain.getLayer(this._layers[0]); + let l1 = this._terrain.getLayer(this._layers[1]); + let l2 = this._terrain.getLayer(this._layers[2]); + + if (l0 != null) { + uvScale.x = 1.0 / l0.tileSize; + } + if (l1 != null) { + uvScale.y = 1.0 / l1.tileSize; + } + if (l2 != null) { + uvScale.z = 1.0 / l2.tileSize; + } + + mtl.setProperty('weightMap', this._weightMap); + mtl.setProperty('detailMap0', l0 != null ? l0.detailMap : null); + mtl.setProperty('detailMap1', l1 != null ? l1.detailMap : null); + mtl.setProperty('detailMap2', l2 != null ? l2.detailMap : null); + } + else if (nlayers == 3) { + let l0 = this._terrain.getLayer(this._layers[0]); + let l1 = this._terrain.getLayer(this._layers[1]); + let l2 = this._terrain.getLayer(this._layers[2]); + let l3 = this._terrain.getLayer(this._layers[3]); + + if (l0 != null) { + uvScale.x = 1.0 / l0.tileSize; + } + if (l1 != null) { + uvScale.y = 1.0 / l1.tileSize; + } + if (l2 != null) { + uvScale.z = 1.0 / l2.tileSize; + } + if (l3 != null) { + uvScale.z = 1.0 / l3.tileSize; + } + + mtl.setProperty('weightMap', this._weightMap); + mtl.setProperty('detailMap0', l0 != null ? l0.detailMap : null); + mtl.setProperty('detailMap1', l1 != null ? l1.detailMap : null); + mtl.setProperty('detailMap2', l2 != null ? l2.detailMap : null); + mtl.setProperty('detailMap3', l3 != null ? l3.detailMap : null); + } + + mtl.setProperty('UVScale', uvScale); + } + } + + setBrushMaterial(mtl: Material|null) { + if (this._renderable._brushMaterial != mtl) { + this._renderable._brushMaterial = mtl; + this._renderable._invalidMaterial(); + } + } + + getIndex() { + return this._index; + } + + getRect() { + let xtile = TERRAIN_BLOCK_TILE_COMPLEXITY; + let ztile = TERRAIN_BLOCK_TILE_COMPLEXITY; + + let rect = new Rect; + rect.x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY; + rect.y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY; + rect.width = TERRAIN_BLOCK_TILE_COMPLEXITY; + rect.height = TERRAIN_BLOCK_TILE_COMPLEXITY; + + return rect; + } + + setLayer(index: number, layerId: number) { + if (this._layers[index] != layerId) { + this._layers[index] = layerId; + this._renderable._invalidMaterial(); + } + } + + getLayer(index: number) { + return this._layers[index]; + } + + getMaxLayer() { + if (this._layers[3] >= 0) { + return 3; + } + else if (this._layers[2] >= 0) { + return 2; + } + else if (this._layers[1] >= 0) { + return 1; + } + else { + return 0; + } + } + + _getMaterialDefines(nlayers: number): IDefineMap { + if (nlayers == 0) { + return { LAYERS: 1 }; + } + else if (nlayers == 1) { + return { LAYERS: 2 }; + } + else if (nlayers == 2) { + return { LAYERS: 3 }; + } + else if (nlayers == 3) { + return { LAYERS: 4 }; + } + + return { LAYERS: 0 }; + } + + _updateMaterial(init: boolean) { + this._renderable._updateMaterial(this, init); + } + + _updateHeight() { + let vertexData = new Float32Array(TERRAIN_BLOCK_VERTEX_SIZE * TERRAIN_BLOCK_VERTEX_COMPLEXITY * TERRAIN_BLOCK_VERTEX_COMPLEXITY); + + let index = 0; + for (let j = 0; j < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++j) { + for (let i = 0; i < TERRAIN_BLOCK_VERTEX_COMPLEXITY; ++i) { + let x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + i; + let y = this._index[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + j; + + let position = this._terrain.getPosition(x, y); + let normal = this._terrain.getNormal(x, y); + let uv = new Vec2(i / TERRAIN_BLOCK_VERTEX_COMPLEXITY, j / TERRAIN_BLOCK_VERTEX_COMPLEXITY); + + vertexData[index++] = position.x; + vertexData[index++] = position.y; + vertexData[index++] = position.z; + vertexData[index++] = normal.x; + vertexData[index++] = normal.y; + vertexData[index++] = normal.z; + vertexData[index++] = uv.x; + vertexData[index++] = uv.y; + } + } + + this._renderable._meshData!.vertexBuffers[0].update(vertexData); + } + + _updateWeightMap() { + let nlayers = this.getMaxLayer(); + + if (nlayers == 0) { + if (this._weightMap != null) { + this._weightMap.destroy(); + this._weightMap = null; + } + + return; + } + else { + if (this._weightMap == null) { + this._weightMap = new Texture2D(); + this._weightMap.create(this._terrain.info.weightMapSize, this._terrain.info.weightMapSize, PixelFormat.RGBA8888); + this._weightMap.setFilters(Filter.LINEAR, Filter.LINEAR); + this._weightMap.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + } + } + + let weightData = new Uint8Array(this._terrain.info.weightMapSize * this._terrain.info.weightMapSize * 4); + let weightIndex = 0; + for (let j = 0; j < this._terrain.info.weightMapSize; ++j) { + for (let i = 0; i < this._terrain.info.weightMapSize; ++i) { + let x = this._index[0] * this._terrain.info.weightMapSize + i; + let y = this._index[1] * this._terrain.info.weightMapSize + j; + let w = this._terrain.getWeight(x, y); + + weightData[weightIndex * 4 + 0] = Math.floor(w.x * 255); + weightData[weightIndex * 4 + 1] = Math.floor(w.y * 255); + weightData[weightIndex * 4 + 2] = Math.floor(w.z * 255); + weightData[weightIndex * 4 + 3] = Math.floor(w.w * 255); + + weightIndex += 1; + } + } + this._weightMap.uploadData(weightData.buffer); + } +} + +@ccclass('cc.Terrain') +@menu('Components/Terrain') +@executeInEditMode +export class Terrain extends Component +{ + @property({ + visible: false, + }) + protected _info: TerrainInfo = new TerrainInfo; + + @property({ + visible: false, + }) + protected _layers: Array = []; + + @property({ + visible: false, + }) + protected _heights: Array = []; + + @property({ + visible: false, + }) + protected _normals: Array = []; + + @property({ + visible: false, + }) + protected _weights: Uint8Array = new Uint8Array(); + + protected _blocks: Array = []; + protected _sharedIndexBuffer: GFXBuffer; + + constructor() { + super(); + + const gfxDevice = cc.director.root.device as GFXDevice; + + // initialize shared index buffer + let indexData = new Uint16Array(TERRAIN_BLOCK_TILE_COMPLEXITY * TERRAIN_BLOCK_TILE_COMPLEXITY * 6); + + let index = 0; + for (let j = 0; j < TERRAIN_BLOCK_TILE_COMPLEXITY; ++j) { + for (let i = 0; i < TERRAIN_BLOCK_TILE_COMPLEXITY; ++i) { + let a = j * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i; + let b = j * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i + 1; + let c = (j + 1) * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i; + let d = (j + 1) * TERRAIN_BLOCK_VERTEX_COMPLEXITY + i + 1; + + // face 1 + indexData[index++] = a; + indexData[index++] = c; + indexData[index++] = b; + + // face 2 + indexData[index++] = b; + indexData[index++] = c; + indexData[index++] = d; + } + } + + this._sharedIndexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: Uint16Array.BYTES_PER_ELEMENT * TERRAIN_BLOCK_TILE_COMPLEXITY * TERRAIN_BLOCK_TILE_COMPLEXITY * 6, + stride: Uint16Array.BYTES_PER_ELEMENT, + }); + this._sharedIndexBuffer.update(indexData); + + // initialize layers + for (let i = 0; i < TERRAIN_MAX_LAYER_COUNT; ++i) { + this._layers.push(null); + } + } + + get info() { + return this._info; + } + + build(info: TerrainInfo) { + this._info.tileSize = info.tileSize; + this._info.blockCount[0] = info.blockCount[0]; + this._info.blockCount[1] = info.blockCount[1]; + this._info.weightMapSize = info.weightMapSize; + this._info.lightMapSize = info.lightMapSize; + this._info.initialize(); + + return this._buildImp(); + } + + _rebuildHeights(info: TerrainInfo) { + if (this.info.vertexCount[0] == info.vertexCount[0] && + this.info.vertexCount[1] == info.vertexCount[1]) { + return false; + } + + let heights = new Array(info.vertexCount[0] * info.vertexCount[1]); + for (let i = 0; i < heights.length; ++i) { + heights[i] = 0; + } + + let w = Math.min(this.info.vertexCount[0], info.vertexCount[0]); + let h = Math.min(this.info.vertexCount[1], info.vertexCount[1]); + + for (let j = 0; j < h; ++j) { + for (let i = 0; i < w; ++i) { + let index0 = j * this.info.vertexCount[1] + i; + let index1 = j * this.info.vertexCount[0] + i; + + heights[index0] = this._heights[index1]; + } + } + + this._heights = heights; + + return true; + } + + _rebuildWeights(info: TerrainInfo) { + let oldWeightMapSize = this.info.weightMapSize; + let oldWeightMapComplexityU = this.info.weightMapSize * this.info.blockCount[0]; + let oldWeightMapComplexityV = this.info.weightMapSize * this.info.blockCount[1]; + + let weightMapComplexityU = info.weightMapSize * info.blockCount[0]; + let weightMapComplexityV = info.weightMapSize * info.blockCount[1]; + + if (weightMapComplexityU == oldWeightMapComplexityU && + weightMapComplexityV == oldWeightMapComplexityV) { + return false; + } + + let weights = new Uint8Array(weightMapComplexityU * weightMapComplexityV * 4); + + for (let i = 0; i < weightMapComplexityU * weightMapComplexityV; ++i) { + weights[i * 4 + 0] = 255; + weights[i * 4 + 1] = 0; + weights[i * 4 + 2] = 0; + weights[i * 4 + 3] = 0; + } + + let w = Math.min(info.blockCount[0], this.info.blockCount[0]); + let h = Math.min(info.blockCount[1], this.info.blockCount[1]); + + for (let j = 0; j < h; ++j) { + for (let i = 0; i < w; ++i) { + let xoff = i * oldWeightMapSize; + let yoff = j * oldWeightMapSize; + + // sample weight + let getWeight = (_j: number, _i: number, _weights: Uint8Array)=> { + let index = _j * oldWeightMapComplexityU + _i; + + let w = new Vec4(); + w.x = _weights[index * 4 + 0] / 255.0; + w.y = _weights[index * 4 + 1] / 255.0; + w.z = _weights[index * 4 + 2] / 255.0; + w.w = _weights[index * 4 + 3] / 255.0; + + return w; + }; + + for (let v = 0; v < this.info.weightMapSize; ++v) { + for (let u = 0; u < this.info.weightMapSize; ++u) { + let fx = u / (this.info.weightMapSize - 1) * (oldWeightMapSize - 1); + let fy = v / (this.info.weightMapSize - 1) * (oldWeightMapSize - 1); + + let ix0 = Math.floor(fx); + let iz0 = Math.floor(fy); + let ix1 = ix0 + 1; + let iz1 = iz0 + 1; + let dx = fx - ix0; + let dz = fy - iz0; + + ix0 = clamp(ix0, 0, oldWeightMapSize - 1); + iz0 = clamp(iz0, 0, oldWeightMapSize - 1); + ix1 = clamp(ix1, 0, oldWeightMapSize - 1); + iz1 = clamp(iz1, 0, oldWeightMapSize - 1); + + let a = getWeight(ix0 + xoff, iz0 + yoff, this._weights); + let b = getWeight(ix1 + xoff, iz0 + yoff, this._weights); + let c = getWeight(ix0 + xoff, iz1 + yoff, this._weights); + let d = getWeight(ix1 + xoff, iz1 + yoff, this._weights); + let m = new Vec4; + vec4.add(m, b, c).multiply(0.5); + + if (dx + dz <= 1.0) { + d = new Vec4; + vec3.sub(d, m, a).add(m); + } + else { + a = new Vec4; + vec3.sub(a, m, d).add(m); + } + + let n1 = new Vec4, n2 = new Vec4, n = new Vec4; + vec3.lerp(n1, a, b, dx); + vec3.lerp(n2, c, d, dx); + vec3.lerp(n, n1, n2, dz); + + let du = i * this.info.weightMapSize + u; + let dv = j * this.info.weightMapSize + v; + let index = du * weightMapComplexityU + dv; + + weights[index * 4 + 0] = n.x * 255; + weights[index * 4 + 1] = n.y * 255; + weights[index * 4 + 2] = n.z * 255; + weights[index * 4 + 3] = n.w * 255; + } + } + } + } + + this._weights = weights; + + return true; + } + + rebuild(info: TerrainInfo) { + info.initialize(); + + let oldBlockCountU = this.info.blockCount[0]; + let oldBlockCountV = this.info.blockCount[1]; + let oldBlocks: Array = []; + for (let i = 0; i < this._blocks.length; ++i) { + oldBlocks.push(this._blocks[i]); + } + this._blocks = []; + + // build heights + this._rebuildHeights(info); + + // build weights + this._rebuildWeights(info); + + // update info + this._info.tileSize = info.tileSize; + this._info.blockCount[0] = info.blockCount[0]; + this._info.blockCount[1] = info.blockCount[1]; + this._info.weightMapSize = info.weightMapSize; + this._info.lightMapSize = info.lightMapSize; + this._info.effect = info.effect; + this._info.DefaultLayerTex = info.DefaultLayerTex; + this._info.initialize(); + + // build blocks + this._buildNormals(); + + for (let j = 0; j < this._info.blockCount[1]; ++j) { + for (let i = 0; i < this._info.blockCount[0]; ++i) { + let block: TerrainBlock; + if (i < oldBlockCountU && j < oldBlockCountV) { + block = oldBlocks[j * oldBlockCountU + i] as TerrainBlock; + oldBlocks[j * oldBlockCountU + i] = null; + } + else { + block = new TerrainBlock(this, i, j); + } + + this._blocks.push(block); + } + } + + for (let i = 0; i < oldBlocks.length; ++i) { + let block = oldBlocks[i]; + if (block != null) { + block.destroy(); + } + } + + for (let j = 0; j < this._info.blockCount[1]; ++j) { + for (let i = 0; i < this._info.blockCount[0]; ++i) { + let index = j * this._info.blockCount[0] + i; + if (i < oldBlockCountU && j < oldBlockCountV) { + this._blocks[index].rebuild(); + } + else { + this._blocks[index].build(); + } + } + } + } + + _buildImp() { + if (this._blocks.length > 0) { + return true; + } + + this._info.initialize(); + + if (this._info.blockCount[0] == 0 || this._info.blockCount[1] == 0) { + return false; + } + + // build heights & normals + let vcount = this._info.vertexCount[0] * this._info.vertexCount[1]; + this._heights = new Array(vcount); + this._normals = new Array(vcount * 3); + + for (let i = 0; i < vcount; ++i) { + this._heights[i] = 0; + this._normals[i * 3 + 0] = 0; + this._normals[i * 3 + 1] = 1; + this._normals[i * 3 + 2] = 0; + } + + // initialize weights + let weightMapComplexityU = this.info.weightMapSize * this.info.blockCount[0]; + let weightMapComplexityV = this.info.weightMapSize * this.info.blockCount[1]; + this._weights = new Uint8Array(weightMapComplexityU * weightMapComplexityV * 4); + for (let i = 0; i < weightMapComplexityU * weightMapComplexityV; ++i) { + this._weights[i * 4 + 0] = 255; + this._weights[i * 4 + 1] = 0; + this._weights[i * 4 + 2] = 0; + this._weights[i * 4 + 3] = 0; + } + + // build blocks + for (let j = 0; j < this._info.blockCount[1]; ++j) { + for (let i = 0; i < this._info.blockCount[0]; ++i) { + this._blocks.push(new TerrainBlock(this, i, j)); + } + } + + for (let i = 0; i < this._blocks.length; ++i) { + this._blocks[i].build(); + } + } + + destroy() { + for (let i = 0; i < this._layers.length; ++i) { + let layer = this._layers[i]; + if (layer != null) { + if (layer.detailMap != null) { + layer.detailMap.destroy(); + } + } + + this._layers[i] = null; + } + + for (let i = 0; i < this._blocks.length; ++i) { + let block = this._blocks[i]; + block.destroy(); + } + this._blocks = []; + + this._sharedIndexBuffer.destroy(); + + super.destroy(); + } + + Import(hf: HeightField, heightScale: number) { + let index = 0; + for (let j = 0; j < this._info.vertexCount[1]; ++j) { + for (let i = 0; i < this._info.vertexCount[0]; ++i) { + let u = i / this._info.tileCount[0]; + let v = j / this._info.tileCount[1]; + + let h = hf.getAt(u * hf.w, v * hf.h) * heightScale; + + this._heights[index++] = h; + } + } + + this._buildNormals(); + + // rebuild all blocks + for (let i = 0; i < this._blocks.length; ++i) { + this._blocks[i]._updateHeight(); + } + } + + Export(hf: HeightField, heightScale: number) { + let index = 0; + for (let j = 0; j < hf.h; ++j) { + for (let i = 0; i < hf.w; ++i) { + let u = i / (hf.w - 1); + let v = j / (hf.h - 1); + + let x = u * this._info.size[0]; + let y = v * this._info.size[1]; + + let h = this.getHeightAt(x, y); + if (h != null) { + hf.data[index++] = h * heightScale; + } + } + } + } + + start() { + if (this._blocks.length == 0) { + this._buildImp(); + } + } + + update(dtime: number) { + for (let i = 0; i < this._blocks.length; ++i) { + this._blocks[i].update(dtime); + } + } + + addLayer(layer: TerrainLayer) { + for (let i = 0; i < this._layers.length; ++i) { + if (this._layers[i] == null) { + this._layers[i] = layer; + return i; + } + } + + return -1; + } + + setLayer(i: number, layer: TerrainLayer) { + this._layers[i] = layer; + } + + removeLayer(id: number) { + this._layers[id] = null; + } + + getLayer(id: number) { + return this._layers[id]; + } + + getPosition(i: number, j: number) { + let x = i * this._info.tileSize; + let z = j * this._info.tileSize; + let y = this.getHeight(i, j); + + return new Vec3(x, y, z); + } + + setHeight(i: number, j: number, h: number) { + this._heights[j * this._info.vertexCount[0] + i] = h; + } + + getHeight(i: number, j: number) { + return this._heights[j * this._info.vertexCount[0] + i]; + } + + getHeightClamp(i: number, j: number) { + i = clamp(i, 0, this._info.vertexCount[0] - 1); + j = clamp(j, 0, this._info.vertexCount[1] - 1); + + return this.getHeight(i, j); + } + + getHeightAt(x: number, y: number) { + let fx = x / this._info.vertexCount[0]; + let fy = y / this._info.vertexCount[1]; + + let ix0 = Math.floor(fx); + let iz0 = Math.floor(fy); + let ix1 = ix0 + 1; + let iz1 = iz0 + 1; + let dx = fx - ix0; + let dz = fy - iz0; + + if (ix0 < 0 || ix0 > this._info.vertexCount[0] - 1 || + iz0 < 0 || iz0 > this._info.vertexCount[1] - 1) { + return null; + } + + ix0 = clamp(ix0, 0, this._info.vertexCount[0] - 1); + iz0 = clamp(iz0, 0, this._info.vertexCount[1] - 1); + ix1 = clamp(ix1, 0, this._info.vertexCount[0] - 1); + iz1 = clamp(iz1, 0, this._info.vertexCount[1] - 1); + + let a = this.getHeight(ix0, iz0); + let b = this.getHeight(ix1, iz0); + let c = this.getHeight(ix0, iz1); + let d = this.getHeight(ix1, iz1); + let m = (b + c) * 0.5; + + if (dx + dz <= 1.0) { + d = m + (m - a); + } + else { + a = m + (m - d); + } + + let h1 = a * (1.0 - dx) + b * dx; + let h2 = c * (1.0 - dx) + d * dx; + + let h = h1 * (1.0 - dz) + h2 * dz; + + return h; + } + + _setNormal(i: number, j: number, n: Vec3) { + let index = j * this._info.vertexCount[0] + i; + + this._normals[index * 3 + 0] = n.x; + this._normals[index * 3 + 1] = n.y; + this._normals[index * 3 + 2] = n.z; + } + + getNormal(i: number, j: number) { + let index = j * this._info.vertexCount[0] + i + + let n = new Vec3(); + n.x = this._normals[index * 3 + 0]; + n.y = this._normals[index * 3 + 1]; + n.z = this._normals[index * 3 + 2]; + + return n; + } + + getNormalAt(x: number, y: number) { + let fx = x / this._info.vertexCount[0]; + let fy = y / this._info.vertexCount[1]; + + let ix0 = Math.floor(fx); + let iz0 = Math.floor(fy); + let ix1 = ix0 + 1; + let iz1 = iz0 + 1; + let dx = fx - ix0; + let dz = fy - iz0; + + if (ix0 < 0 || ix0 > this._info.vertexCount[0] - 1 || + iz0 < 0 || iz0 > this._info.vertexCount[1] - 1) { + return null; + } + + ix0 = clamp(ix0, 0, this._info.vertexCount[0] - 1); + iz0 = clamp(iz0, 0, this._info.vertexCount[1] - 1); + ix1 = clamp(ix1, 0, this._info.vertexCount[0] - 1); + iz1 = clamp(iz1, 0, this._info.vertexCount[1] - 1); + + let a = this.getNormal(ix0, iz0); + let b = this.getNormal(ix1, iz0); + let c = this.getNormal(ix0, iz1); + let d = this.getNormal(ix1, iz1); + let m = new Vec3; + vec3.add(m, b, c).multiply(0.5); + + if (dx + dz <= 1.0) { + d = new Vec3; + vec3.sub(d, m, a).add(m); + } + else { + a = new Vec3; + vec3.sub(a, m, d).add(m); + } + + let n1 = new Vec3, n2 = new Vec3, n = new Vec3; + vec3.lerp(n1, a, b, dx); + vec3.lerp(n2, c, d, dx); + vec3.lerp(n, n1, n2, dz); + + return n; + } + + setWeight(i: number, j: number, w: Vec4) { + let index = j * this.info.weightMapSize * this.info.blockCount[0] + i; + + this._weights[index * 4 + 0] = w.x * 255; + this._weights[index * 4 + 1] = w.y * 255; + this._weights[index * 4 + 2] = w.z * 255; + this._weights[index * 4 + 3] = w.w * 255; + } + + getWeight(i: number, j: number) { + let index = j * this.info.weightMapSize * this.info.blockCount[0] + i; + + let w = new Vec4(); + w.x = this._weights[index * 4 + 0] / 255.0; + w.y = this._weights[index * 4 + 1] / 255.0; + w.z = this._weights[index * 4 + 2] / 255.0; + w.w = this._weights[index * 4 + 3] / 255.0; + + return w; + } + + getWeightAt(x: number, y: number) { + let fx = x / this._info.vertexCount[0]; + let fy = y / this._info.vertexCount[1]; + + let ix0 = Math.floor(fx); + let iz0 = Math.floor(fy); + let ix1 = ix0 + 1; + let iz1 = iz0 + 1; + let dx = fx - ix0; + let dz = fy - iz0; + + if (ix0 < 0 || ix0 > this._info.vertexCount[0] - 1 || + iz0 < 0 || iz0 > this._info.vertexCount[1] - 1) { + return null; + } + + ix0 = clamp(ix0, 0, this._info.vertexCount[0] - 1); + iz0 = clamp(iz0, 0, this._info.vertexCount[1] - 1); + ix1 = clamp(ix1, 0, this._info.vertexCount[0] - 1); + iz1 = clamp(iz1, 0, this._info.vertexCount[1] - 1); + + let a = this.getWeight(ix0, iz0); + let b = this.getWeight(ix1, iz0); + let c = this.getWeight(ix0, iz1); + let d = this.getWeight(ix1, iz1); + let m = new Vec4; + vec4.add(m, b, c).multiply(0.5); + + if (dx + dz <= 1.0) { + d = new Vec4; + vec3.sub(d, m, a).add(m); + } + else { + a = new Vec4; + vec3.sub(a, m, d).add(m); + } + + let n1 = new Vec4, n2 = new Vec4, n = new Vec4; + vec3.lerp(n1, a, b, dx); + vec3.lerp(n2, c, d, dx); + vec3.lerp(n, n1, n2, dz); + + return n; + } + + getBlock(i: number, j: number) { + return this._blocks[j * this._info.blockCount[0] + i]; + } + + getBlocks() { + return this._blocks; + } + + getSharedIndexBuffer() { + return this._sharedIndexBuffer; + } + + rayCheck(start: Vec3, dir: Vec3, step: number) { + const MAX_COUNT = 2000; + + let i = 0; + let trace = start; + let position: Vec3|null = null; + let dstep = new Vec3; + + dstep.set(dir); + dstep.multiply(step); + + if (dir.equals(new Vec3(0, 1, 0))) { + let y = this.getHeightAt(trace.x, trace.z); + if (y != null && trace.y <= y) { + position = new Vec3(trace.x, y, trace.z); + } + } + else if (dir.equals(new Vec3(0, -1, 0))) { + let y = this.getHeightAt(trace.x, trace.z); + if (y != null && trace.y >= y) { + position = new Vec3(trace.x, y, trace.z); + } + } + else { + // 穷举法 + while (i++ < MAX_COUNT) { + let y = this.getHeightAt(trace.x, trace.z); + if (y != null && trace.y <= y) { + position = new Vec3(trace.x, y, trace.z); + break; + } + + trace.add(dstep); + } + } + + return position; + } + + _calcuNormal(x: number, z: number) { + let flip = 1; + let here = this.getPosition(x, z); + let right: Vec3, up: Vec3; + + if (x < this._info.vertexCount[0] - 1) { + right = this.getPosition(x + 1, z); + } + else { + flip *= -1; + right = this.getPosition(x - 1, z); + } + + if (z < this._info.vertexCount[1] - 1) { + up = this.getPosition(x, z + 1); + } + else { + flip *= -1; + up = this.getPosition(x, z - 1); + } + + right.subtract(here); + up.subtract(here); + + let normal = new Vec3; + normal.set(up); + normal.cross(right); + normal.multiply(flip); + normal.normalize(); + return normal; + } + + _buildNormals() { + let index = 0; + for (let y = 0; y < this._info.vertexCount[1]; ++y) { + for (let x = 0; x < this._info.vertexCount[0]; ++x) { + let n = this._calcuNormal(x, y); + + this._normals[index * 3 + 0] = n.x; + this._normals[index * 3 + 1] = n.y; + this._normals[index * 3 + 2] = n.z; + index += 1; + } + } + } +} \ No newline at end of file